Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

1411116 - Programming I Assignment #3 Due Date: November 30, 2016 Submission Instructions: Submit your assignment on the blackboard link, corresponding to your Section: Please

1411116 - Programming I Assignment #3 Due Date: November 30, 2016 Submission Instructions: Submit your assignment on the blackboard link, corresponding to your Section: Please follow the following rules when sending the source code: 1) The name of the file should be q#_myID_section.cpp (for e.g: q1_u000002046_51.cpp) 2) In case two assignments are found to be similar, both students will get ZERO.' Chapter 8: Arrays Problem 1: Write a C++ program that reads an array of 10 integers. The program should then cyclically shift the array n positions to the right (n is given by the user). This means each element of the array should be moved n positions to the right, while the last n elements are moved to the beginning of the array. For example: if the array contains the numbers [ 1 2 3 4 5 6 7 8 9 0 ] Shifting 2 positions to the right should give the array [ 9 0 1 2 3 4 5 6 7 8 ]. Sample input/output Problem 2: Write a C++ program that prompts the user to input 10 integer values. The program should display the minimum and maximum of those values. The program also should display the value that occurs the most and the number of occurrences. Hints: Sort the elements in the array to find the minimum and maximum values. To find the value that occurs the most, use a two-dimensional array to store the number of occurrences for each value. Sample input/output Problem 3: Write a C++ program to generate and display a matrix as shown below. The diagonal of the matrix is filled with 0. The lower side is filled with -1 and the upper side is filled with 1. Problem 4: Write a program that reads a line of text containing alphanumeric characters into a character array t[100] and the program must reverse and prints it. as shown below: Chapter 6: User-defined Functions Problem 5: Write a C++ program that prompts the user to enter two positive integers m and n where m < n then output all prime numbers between m and n, inclusive. You must write a function isPrime() that would test a number whether it is a prime number. Sample input/output Problem 6: Write a program that prompts the user to enter two prices: the current price and the price one year ago for an item. The program then calculates and displays the inflation rate for the item. Your program uses the following function: The function calculateInflation ( ) computes and returns the inflation rate of an item price. The function takes the current price of an item and the price of one year ago and calculates the inflation rate by subtracting the current price from the price of the item one year ago and then divides the result by the price a year ago. C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) Learn what an assignment statement is and what it does Become familiar with the string data type Discover how to input data into memory using input statements Become familiar with the use of increment and decrement operators Examine ways to output results using output statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Objectives (cont'd.) Learn how to use preprocessor directives and why they are necessary Learn how to debug syntax errors Explore how to properly structure a program, including using comments to document a program Learn how to write a C++ program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 Introduction Computer program - Sequence of statements whose objective is to accomplish a task Programming - Process of planning and creating a program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 A C++ Program #include using namespace std; int main() { int num; num = 6; cout << "My first C++ program." << endl; cout << "The sum of 2 and 3 = " << 5 << endl; cout << "7 + 8 = " << 7 + 8 << endl; cout << "Num = " << num << endl; return 0; } C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6 The Basics of a C++ Program Function: collection of statements; when executed, accomplishes something - May be predefined or standard Syntax: rules that specify which statements (instructions) are legal Programming language: a set of rules, symbols, and special words Semantic rule: meaning of the instruction C++ Programming: From Problem Analysis to Program Design, Fifth Edition 7 Comments Comments are for the reader, not the compiler Two types: - Single line // This is a C++ program. It prints the sentence: // Welcome to C++ Programming. - Multiple line /* */ You can include comments that can occupy several lines. C++ Programming: From Problem Analysis to Program Design, Fifth Edition 8 Special Symbols Special symbols + * / . ; ? , <= != == >= C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9 Reserved Words (Keywords) Reserved words, keywords, or word symbols - Include: int float double char const void return C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10 Identifiers Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive - NUMBER is not the same as number Two predefined identifiers are cout and cin Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11 Identifiers (cont'd.) Legal identifiers in C++: - first - conversion - payRate C++ Programming: From Problem Analysis to Program Design, Fifth Edition 12 Whitespaces Every C++ program contains whitespaces - Include blanks, tabs, and newline characters Used to separate special symbols, reserved words, and identifiers Proper utilization of whitespaces is important - Can be used to make the program readable C++ Programming: From Problem Analysis to Program Design, Fifth Edition 13 Data Types Data type: set of values together with a set of operations C++ data types fall into three categories: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 14 Simple Data Types Three categories of simple data - Integral: integers (numbers without a decimal) - Floating-point: decimal numbers - Enumeration type: user-defined data type C++ Programming: From Problem Analysis to Program Design, Fifth Edition 15 Simple Data Types (cont'd.) Integral data types are further classified into nine categories: - char, short, int, long, bool - unsigned char, unsigned short, unsigned int, unsigned long C++ Programming: From Problem Analysis to Program Design, Fifth Edition 16 Simple Data Types (cont'd.) Different compilers may allow different ranges of values C++ Programming: From Problem Analysis to Program Design, Fifth Edition 17 int Data Type Examples: -6728 0 78 +763 Positive integers do not need a + sign No commas are used within an integer - Commas are used for separating items in a list C++ Programming: From Problem Analysis to Program Design, Fifth Edition 18 bool Data Type bool type - Two values: true and false - Manipulate logical (Boolean) expressions true and false - Logical values bool, true, and false - Reserved words C++ Programming: From Problem Analysis to Program Design, Fifth Edition 19 char Data Type The smallest integral data type Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes - 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character - Written ' ', with a space left between the single quotes C++ Programming: From Problem Analysis to Program Design, Fifth Edition 20 Floating-Point Data Types C++ uses scientific notation to represent real numbers (floating-point notation) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 21 Floating-Point Data Types (cont'd.) float: represents any real number - Range: -3.4E+38 to 3.4E+38 (four bytes) double: represents any real number - Range: -1.7E+308 to 1.7E+308 (eight bytes) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 22 Floating-Point Data Types (cont'd.) Maximum number of significant digits (decimal places) for float values is 6 or 7 Maximum number of significant digits for double is 15 Precision: maximum number of significant digits - Float values are called single precision - Double values are called double precision C++ Programming: From Problem Analysis to Program Design, Fifth Edition 23 Arithmetic Operators and Operator Precedence C++ arithmetic operators: - + addition - - subtraction - * multiplication - / division - % modulus operator +, -, *, and / can be used with integral and floating-point data types Operators can be unary or binary C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24 Order of Precedence All operations inside of () are evaluated first *, /, and % are at the same level of precedence and are evaluated next + and - have the same level of precedence and are evaluated last When operators are on the same level - Performed from left to right (associativity) 3 * 7 - 6 + 2 * 5 / 4 + 6 means (((3 * 7) - 6) + ((2 * 5) / 4 )) + 6 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 25 Expressions If all operands are integers - Expression is called an integral expression Yields an integral result Example: 2 + 3 * 5 If all operands are floating-point - Expression is called a floating-point expression Yields a floating-point result Example: 12.8 * 17.5 - 34.50 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 26 Mixed Expressions Mixed expression: - Has operands of different data types - Contains integers and floating-point Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 - 13.6 + 18 C++ Programming: From Problem Analysis to Program Design, Fifth Edition / 2 27 Mixed Expressions (cont'd.) Evaluation rules: - If operator has same types of operands Evaluated according to the type of the operands - If operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point - Entire expression is evaluated according to precedence rules C++ Programming: From Problem Analysis to Program Design, Fifth Edition 28 Type Conversion (Casting) Implicit type coercion: when value of one type is automatically changed to another type Cast operator: provides explicit type conversion static_cast(expression) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 29 Type Conversion (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 30 string Type Programmer-defined type supplied in ANSI/ISO Standard C++ library Sequence of zero or more characters Enclosed in double quotation marks Null: a string with no characters Each character has relative position in string - Position of first character is 0 Length of a string is number of characters in it - Example: length of "William Jacob" is 13 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 31 Input Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: - Instruct computer to allocate memory - Include statements to put data into memory C++ Programming: From Problem Analysis to Program Design, Fifth Edition 32 Allocating Memory with Constants and Variables Named constant: memory location whose content can't change during execution The syntax to declare a named constant is: In C++, const is a reserved word C++ Programming: From Problem Analysis to Program Design, Fifth Edition 33 Allocating Memory with Constants and Variables (cont'd.) Variable: memory location whose content may change during execution The syntax to declare a named constant is: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 34 Putting Data into Variables Ways to place data into a variable: - Use C++'s assignment statement - Use input (read) statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 35 Assignment Statement The assignment statement takes the form: Expression is evaluated and its value is assigned to the variable on the left side In C++, = is called the assignment operator C++ Programming: From Problem Analysis to Program Design, Fifth Edition 36 Assignment Statement (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37 Saving and Using the Value of an Expression To save the value of an expression: - Declare a variable of the appropriate data type - Assign the value of the expression to the variable that was declared Use the assignment statement Wherever the value of the expression is needed, use the variable holding the value C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38 Declaring & Initializing Variables Variables can be initialized when declared: int first=13, second=10; char ch=' '; double x=12.6; All variables must be initialized before they are used - But not necessarily during declaration C++ Programming: From Problem Analysis to Program Design, Fifth Edition 39 Input (Read) Statement cin is used with >> to gather input The stream extraction operator is >> For example, if miles is a double variable cin >> miles; - Causes computer to get a value of type double - Places it in the variable miles C++ Programming: From Problem Analysis to Program Design, Fifth Edition 40 Input (Read) Statement (cont'd.) Using more than one variable in cin allows more than one value to be read at a time For example, if feet and inches are variables of type int, a statement such as: cin >> feet >> inches; - Inputs two integers from the keyboard - Places them in variables feet and inches respectively C++ Programming: From Problem Analysis to Program Design, Fifth Edition 41 Input (Read) Statement (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 42 Variable Initialization There are two ways to initialize a variable: int feet; - By using the assignment statement feet = 35; - By using a read statement cin >> feet; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 43 Increment and Decrement Operators Increment operator: increment variable by 1 - Pre-increment: ++variable - Post-increment: variable++ Decrement operator: decrement variable by 1 - Pre-decrement: --variable - Post-decrement: variable What is the difference between the following? x = 5; y = ++x; x = 5; y = x++; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 44 Output The syntax of cout and << is: - Called an output statement The stream insertion operator is << Expression evaluated and its value is printed at the current cursor position on the screen C++ Programming: From Problem Analysis to Program Design, Fifth Edition 45 Output (cont'd.) A manipulator is used to format the output - Example: endl causes insertion point to move to beginning of next line C++ Programming: From Problem Analysis to Program Design, Fifth Edition 46 Output (cont'd.) The new line character is '\ ' - May appear anywhere in the string cout << "Hello there."; cout << "My name is James."; Output: Hello there.My name is James. cout << "Hello there.\ "; cout << "My name is James."; Output : Hello there. My name is James. C++ Programming: From Problem Analysis to Program Design, Fifth Edition 47 Output (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 48 Preprocessor Directives C++ has a small number of operations Many functions and symbols needed to run a C++ program are provided as collection of libraries Every library has a name and is referred to by a header file Preprocessor directives are commands supplied to the preprocessor All preprocessor commands begin with # No semicolon at the end of these commands C++ Programming: From Problem Analysis to Program Design, Fifth Edition 49 Preprocessor Directives (cont'd.) Syntax to include a header file: For example: #include - Causes the preprocessor to include the header file iostream in the program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 50 namespace and Using cin and cout in a Program cin and cout are declared in the header file iostream, but within std namespace To use cin and cout in a program, use the following two statements: #include using namespace std; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 51 Using the string Data Type in a Program To use the string type, you need to access its definition from the header file string Include the following preprocessor directive: #include C++ Programming: From Problem Analysis to Program Design, Fifth Edition 52 Creating a C++ Program C++ program has two parts: - Preprocessor directives - The program Preprocessor directives and program statements constitute C++ source code (.cpp) Compiler generates object code (.obj) Executable code is produced and saved in a file with the file extension .exe C++ Programming: From Problem Analysis to Program Design, Fifth Edition 53 Creating a C++ Program (cont'd.) A C++ program is a collection of functions, one of which is the function main The first line of the function main is called the heading of the function: - int main() The statements enclosed between the curly braces ({ and }) form the body of the function - Contains two types of statements: Declaration statements Executable statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 54 Creating a C++ Program (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 55 Creating a C++ Program (cont'd.) Sample Run: Line 9: firstNum = 18 Line 10: Enter an integer: 15 Line 13: secondNum = 15 Line 15: The new value of firstNum = 60 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 56 Debugging: Understanding and Fixing Syntax Errors Compile a program - Compiler will identify the syntax error - Specifies the line numbers where the errors occur Example2_Syntax_Errors.cpp c:\\chapter 2 source code\\example2_syntax_errors.cpp(9) : error C2146: syntax error : missing ';' before identifier 'num' c:\\chapter 2 source code\\example2_syntax_errors.cpp(11) : error C2065: 'tempNum' : undeclared identifier Learn how to spot and fix syntax errors C++ Programming: From Problem Analysis to Program Design, Fifth Edition 57 Program Style and Form Every C++ program has a function main Programs must also follow syntax rules Other rules serve the purpose of giving precise meaning to the language C++ Programming: From Problem Analysis to Program Design, Fifth Edition 58 Syntax Errors in syntax are found in compilation int x; int y double z; //Line 1 //Line 2: error //Line 3 y = w + x; //Line 4: error C++ Programming: From Problem Analysis to Program Design, Fifth Edition 59 Use of Blanks In C++, you use one or more blanks to separate numbers when data is input - Used to separate reserved words and identifiers from each other and from other symbols - Must never appear within a reserved word or identifier C++ Programming: From Problem Analysis to Program Design, Fifth Edition 60 Use of Semicolons, Brackets, and Commas All C++ statements end with a semicolon - Also called a statement terminator { and } are not C++ statements Commas separate items in a list C++ Programming: From Problem Analysis to Program Design, Fifth Edition 61 Semantics Possible to remove all syntax errors in a program and still not have it run Even if it runs, it may still not do what you meant it to do For example, 2 + 3 * 5 and (2 + 3) * 5 are both syntactically correct expressions, but have different meanings C++ Programming: From Problem Analysis to Program Design, Fifth Edition 62 Naming Identifiers Identifiers can be self-documenting: - CENTIMETERS_PER_INCH Avoid run-together words : - annualsale - Solution: Capitalize the beginning of each new word: annualSale Inserting an underscore just before a new word: annual_sale C++ Programming: From Problem Analysis to Program Design, Fifth Edition 63 Prompt Lines Prompt lines: executable statements that inform the user what to do cout << "Please enter a number between 1 and 10 and " << "press the return key" << endl; cin >> num; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 64 Documentation A well-documented program is easier to understand and modify You use comments to document programs Comments should appear in a program to: - Explain the purpose of the program - Identify who wrote it - Explain the purpose of particular statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 65 Form and Style Consider two ways of declaring variables: - Method 1 int feet, inch; double x, y; - Method 2 int feet,inch;double x,y; Both are correct; however, the second is hard to read C++ Programming: From Problem Analysis to Program Design, Fifth Edition 66 More on Assignment Statements C++ has special assignment statements called compound assignments +=, -=, *=, /=, and %= Example: x *= y; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 67 Programming Example: Convert Length Write a program that takes as input a given length expressed in feet and inches - Convert and output the length in centimeters Input: length in feet and inches Output: equivalent length in centimeters Lengths are given in feet and inches Program computes the equivalent length in centimeters One inch is equal to 2.54 centimeters C++ Programming: From Problem Analysis to Program Design, Fifth Edition 68 Programming Example: Convert Length (cont'd.) Convert the length in feet and inches to all inches: - Multiply the number of feet by 12 - Add given inches Use the conversion formula (1 inch = 2.54 centimeters) to find the equivalent length in centimeters C++ Programming: From Problem Analysis to Program Design, Fifth Edition 69 Programming Example: Convert Length (cont'd.) The algorithm is as follows: - Get the length in feet and inches - Convert the length into total inches - Convert total inches into centimeters - Output centimeters C++ Programming: From Problem Analysis to Program Design, Fifth Edition 70 Programming Example: Variables and Constants Variables int feet; //variable to hold given feet int inches; //variable to hold given inches int totalInches; //variable to hold total inches double centimeters; //variable to hold length in //centimeters Named Constant const double CENTIMETERS_PER_INCH = 2.54; const int INCHES_PER_FOOT = 12; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 71 Programming Example: Main Algorithm Prompt user for input Get data Echo the input (output the input) Find length in inches Output length in inches Convert length to centimeters Output length in centimeters C++ Programming: From Problem Analysis to Program Design, Fifth Edition 72 Programming Example: Putting It Together Program begins with comments System resources will be used for I/O Use input statements to get data and output statements to print results Data comes from keyboard and the output will display on the screen The first statement of the program, after comments, is preprocessor directive to include header file iostream C++ Programming: From Problem Analysis to Program Design, Fifth Edition 73 Programming Example: Putting It Together (cont'd.) Two types of memory locations for data manipulation: - Named constants Usually put before main - Variables This program has only one function (main), which will contain all the code The program needs variables to manipulate data, which are declared in main C++ Programming: From Problem Analysis to Program Design, Fifth Edition 74 Programming Example: Body of the Function The body of the function main has the following form: int main () { declare variables statements return 0; } C++ Programming: From Problem Analysis to Program Design, Fifth Edition 75 Programming Example: Writing a Complete Program Begin the program with comments for documentation Include header files Declare named constants, if any Write the definition of the function main C++ Programming: From Problem Analysis to Program Design, Fifth Edition 76 Programming Example: Writing a Complete Program (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 77 Programming Example: Sample Run Enter two integers, one for feet, one for inches: 15 7 The numbers you entered are 15 for feet and 7 for inches. The total number of inches = 187 The number of centimeters = 474.98 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 78 Summary C++ program: collection of functions where each program has a function called main Identifier consists of letters, digits, and underscores, and begins with letter or underscore The arithmetic operators in C++ are addition (+), subtraction (-),multiplication (*), division (/), and modulus (%) Arithmetic expressions are evaluated using the precedence associativity rules C++ Programming: From Problem Analysis to Program Design, Fifth Edition 79 Summary (cont'd.) All operands in an integral expression are integers and all operands in a floating-point expression are decimal numbers Mixed expression: contains both integers and decimal numbers Use the cast operator to explicitly convert values from one data type to another A named constant is initialized when declared All variables must be declared before used C++ Programming: From Problem Analysis to Program Design, Fifth Edition 80 Summary (cont'd.) Use cin and stream extraction operator >> to input from the standard input device Use cout and stream insertion operator << to output to the standard output device Preprocessor commands are processed before the program goes through the compiler A file containing a C++ program usually ends with the extension .cpp C++ Programming: From Problem Analysis to Program Design, Fifth Edition 81 C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined functions in a program Explore how to use the input stream functions get, ignore, putback, and peek C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) Become familiar with input failure Learn how to write data to the standard output device Discover how to use manipulators in a program to format output Learn how to perform input and output operations with the string data type Learn how to debug logic errors Become familiar with file input and output C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 I/O Streams and Standard I/O Devices I/O: sequence of bytes (stream of bytes) from source to destination - Bytes are usually characters, unless program requires other types of information Stream: sequence of characters from source to destination Input stream: sequence of characters from an input device to the computer Output stream: sequence of characters from the computer to an output device C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 I/O Streams and Standard I/O Devices (cont'd.) Use iostream header file to extract (receive) data from keyboard and send output to the screen - Contains definitions of two data types: istream: input stream ostream: output stream - Has two variables: cin: stands for common input cout: stands for common output C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 I/O Streams and Standard I/O Devices (cont'd.) To use cin and cout, the preprocessor directive #include must be used Variable declaration is similar to: - istream cin; - ostream cout; Input stream variables: type istream Output stream variables: type ostream C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6 cin and the Extraction Operator >> The syntax of an input statement using cin and the extraction operator >> is: The extraction operator >> is binary - Left-side operand is an input stream variable Example: cin - Right-side operand is a variable C++ Programming: From Problem Analysis to Program Design, Fifth Edition 7 cin and the Extraction Operator >> (cont'd.) No difference between a single cin with multiple variables and multiple cin statements with one variable When scanning, >> skips all whitespace - Blanks and certain nonprintable characters >> distinguishes between character 2 and number 2 by the right-side operand of >> - If type char or int (or double), the 2 is treated as a character or as a number 2 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 8 cin and the Extraction Operator >> (cont'd.) Entering a char value into an int or double variable causes serious errors, called input failure C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9 cin and the Extraction Operator >> (cont'd.) When reading data into a char variable - >> skips leading whitespace, finds and stores only the next character - Reading stops after a single character To read data into an int or double variable - >> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal) - Reading stops on whitespace non-digit character C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10 cin and the Extraction Operator >> (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11 cin and the Extraction Operator >> (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 12 cin and the Extraction Operator >> (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 13 Using Predefined Functions in a Program Function (subprogram): set of instructions - When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions - Predefined functions are organized as a collection of libraries called header files C++ Programming: From Problem Analysis to Program Design, Fifth Edition 14 Using Predefined Functions in a Program (cont'd.) Header file may contain several functions To use a predefined function, you need the name of the appropriate header file - You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do C++ Programming: From Problem Analysis to Program Design, Fifth Edition 15 Using Predefined Functions in a Program (cont'd.) To use pow (power), include cmath - Two numeric parameters - Syntax: pow(x,y) = xy x and y are the arguments or parameters - In pow(2,3), the parameters are 2 and 3 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 16 Using Predefined Functions in a Program (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 17 Using Predefined Functions in a Program (cont'd.) Sample Run: Line Line Line Line Line 1: 4: 5: 7: 9: 2 to the power of 6 = 64 12.5 to the power of 3 = 1953.13 Square root of 24 = 4.89898 u = 181.019 Length of str = 20 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 18 cin and the get Function The get function - Inputs next character (including whitespace) - Stores in memory location indicated by its argument The syntax of cin and the get function: varChar - Is a char variable - Is the argument (parameter) of the function C++ Programming: From Problem Analysis to Program Design, Fifth Edition 19 cin and the ignore Function ignore function - Discards a portion of the input The syntax to use the function ignore is: intExp is an integer expression chExp is a char expression If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp C++ Programming: From Problem Analysis to Program Design, Fifth Edition 20 putback and peek Functions putback function - Places previous character extracted by the get function from an input stream back to that stream peek function - Returns next character from the input stream - Does not remove the character from that stream C++ Programming: From Problem Analysis to Program Design, Fifth Edition 21 putback and peek Functions (cont'd.) The syntax for putback: - istreamVar: an input stream variable (cin) - ch is a char variable The syntax for peek: - istreamVar: an input stream variable (cin) - ch is a char variable C++ Programming: From Problem Analysis to Program Design, Fifth Edition 22 The Dot Notation Between I/O Stream Variables and I/O Functions: A Precaution In the statement cin.get(ch); cin and get are two separate identifiers separated by a dot Dot separates the input stream variable name from the member, or function, name In C++, dot is the member access operator C++ Programming: From Problem Analysis to Program Design, Fifth Edition 23 Input Failure Things can go wrong during execution If input data does not match corresponding variables, program may run into problems Trying to read a letter into an int or double variable will result in an input failure If an error occurs when reading data - Input stream enters the fail state C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24 The clear Function Once in a fail state, all further I/O statements using that stream are ignored The program continues to execute with whatever values are stored in variables - This causes incorrect results The clear function restores input stream to a working state C++ Programming: From Problem Analysis to Program Design, Fifth Edition 25 Output and Formatting Output Syntax of cout when used with << Expression is evaluated Value is printed Manipulator is used to format the output - Example: endl C++ Programming: From Problem Analysis to Program Design, Fifth Edition 26 setprecision Manipulator Syntax: Outputs decimal numbers with up to n decimal places Must include the header file iomanip: - #include C++ Programming: From Problem Analysis to Program Design, Fifth Edition 27 fixed Manipulator fixed outputs floating-point numbers in a fixed decimal format - Example: cout << fixed; - Disable by using the stream member function unsetf Example: cout.unsetf(ios::fixed); The manipulator scientific is used to output floating-point numbers in scientific format C++ Programming: From Problem Analysis to Program Design, Fifth Edition 28 showpoint Manipulator showpoint forces output to show the decimal point and trailing zeros Examples: - cout << showpoint; - cout << fixed << showpoint; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 29 setw Outputs the value of an expression in specific columns - cout << setw(5) << x << endl; If number of columns exceeds the number of columns required by the expression - Output of the expression is right-justified - Unused columns to the left are filled with spaces Must include the header file iomanip C++ Programming: From Problem Analysis to Program Design, Fifth Edition 30 Additional Output Formatting Tools Additional formatting tools that give you more control over your output: - setfill manipulator - left and right manipulators - unsetf manipulator C++ Programming: From Problem Analysis to Program Design, Fifth Edition 31 setfill Manipulator Output stream variables can use setfill to fill unused columns with a character Example: - cout << setfill('#'); C++ Programming: From Problem Analysis to Program Design, Fifth Edition 32 left and right Manipulators left: left-justifies the output Disable left by using unsetf right: right-justifies the output C++ Programming: From Problem Analysis to Program Design, Fifth Edition 33 Types of Manipulators Two types of manipulators: - With parameters - Without parameters Parameterized: require iomanip header - setprecision, setw, and setfill Nonparameterized: require iostream header - endl, fixed, showpoint, left, and flush C++ Programming: From Problem Analysis to Program Design, Fifth Edition 34 Input/Output and the string Type An input stream variable (cin) and >> operator can read a string into a variable of the data type string Extraction operator - Skips any leading whitespace characters and reading stops at a whitespace character The function getline - Reads until end of the current line C++ Programming: From Problem Analysis to Program Design, Fifth Edition 35 Understanding Logic Errors and Debugging with cout statements Syntax errors - Reported by the compiler Logic errors - Typically not caught by the compiler - Spot and correct using cout statements - Temporarily insert an output statement - Correct problem - Remove output statement C++ Programming: From Problem Analysis to Program Design, Fifth Edition 36 File Input/Output File: area in secondary storage to hold info File I/O is a five-step process 1. Include fstream header 2. Declare file stream variables 3. Associate the file stream variables with the input/output sources 4. Use the file stream variables with >>, <<, or other input/output functions 5. Close the files C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37 Programming Example: Movie Ticket Sale and Donation to Charity A theater owner agrees to donate a portion of gross ticket sales to a charity The program will prompt the user to input: - Movie name - Adult ticket price - Child ticket price - Number of adult tickets sold - Number of child tickets sold - Percentage of gross amount to be donated C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38 Programming Example: I/O Inputs: movie name, adult and child ticket price, # adult and child tickets sold, and percentage of the gross to be donated Program output: -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* Movie Name: ....................... Journey to Mars Number of Tickets Sold: ........... 2650 Gross Amount: ..................... $ 9150.00 Percentage of Gross Amount Donated: 10.00% Amount Donated: ................... $ 915.00 Net Sale: ......................... $ 8235.00 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 39 Programming Example: Problem Analysis The program needs to: 1. 2. 3. 4. 5. 6. Get the movie name Get the price of an adult ticket price Get the price of a child ticket price Get the number of adult tickets sold Get the number of child tickets sold Get the percentage of the gross amount donated to the charity. C++ Programming: From Problem Analysis to Program Design, Fifth Edition 40 Programming Example: Problem Analysis (cont'd.) 7. Calculate the gross amount grossAmount = adultTicketPrice * noOfAdultTicketsSold + childTicketPrice * noOfChildTicketsSold; 8. Calculate the amount donated to the charity amountDonated = grossAmount * percentDonation / 100; 9. Calculate the net sale amount netSale = grossAmount - amountDonated; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 41 Programming Example: Variables string movieName; double adultTicketPrice; double childTicketPrice; int noOfAdultTicketsSold; int noOfChildTicketsSold; double percentDonation; double grossAmount; double amountDonated; double netSaleAmount; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 42 Programming Example: Formatting Output First column is left-justified - When printing a value in the first column, use left Numbers in second column are rightjustified - Before printing a value in the second column, use right Use setfill to fill the empty space between the first and second columns with dots C++ Programming: From Problem Analysis to Program Design, Fifth Edition 43 Programming Example: Formatting Output (cont'd.) In the lines showing gross amount, amount donated, and net sale amount - Use blanks to fill space between the $ sign and the number Before printing the dollar sign - Use setfill to set the filling character to blank C++ Programming: From Problem Analysis to Program Design, Fifth Edition 44 Programming Example: Main Algorithm 1. Declare variables 2. Set the output of the floating-point to: - Two decimal places - Fixed - Decimal point and trailing zeros 3. Prompt the user to enter a movie name 4. Input movie name using getline because it might contain spaces 5. Prompt user for price of an adult ticket C++ Programming: From Problem Analysis to Program Design, Fifth Edition 45 Programming Example: Main Algorithm (cont'd.) 6. 7. 8. 9. Input price of an adult ticket Prompt user for price of a child ticket Input price of a child ticket Prompt user for the number of adult tickets sold 10.Input number of adult tickets sold 11.Prompt user for number of child tickets sold 12.Input the number of child tickets sold C++ Programming: From Problem Analysis to Program Design, Fifth Edition 46 Programming Example: Main Algorithm (cont'd.) 13.Prompt user for percentage of the gross amount donated 14.Input percentage of the gross amount donated 15.Calculate the gross amount 16.Calculate the amount donated 17.Calculate the net sale amount 18.Output the results C++ Programming: From Problem Analysis to Program Design, Fifth Edition 47 Summary Stream: infinite sequence of characters from a source to a destination Input stream: from a source to a computer Output stream: from a computer to a destination cin: common input cout: common output To use cin and cout, include iostream header C++ Programming: From Problem Analysis to Program Design, Fifth Edition 48 Summary (cont'd.) get reads data character-by-character putback puts last character retrieved by get back to the input stream ignore skips data in a line peek returns next character from input stream, but does not remove it Attempting to read invalid data into a variable causes the input stream to enter the fail state C++ Programming: From Problem Analysis to Program Design, Fifth Edition 49 Summary (cont'd.) The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output Include iomanip for the manipulators setprecision, setw, and setfill File: area in secondary storage to hold info Header fstream contains the definitions of ifstream and ofstream C++ Programming: From Problem Analysis to Program Design, Fifth Edition 50 C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 4: Control Structures I (Selection) Objectives In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover how to use the selection control structures if, if...else, and switch in a program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) Learn how to avoid bugs by avoiding partially understood concepts Learn to use the assert function to terminate a program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Control Structures A computer can proceed: - In sequence - Selectively (branch): making a choice - Repetitively (iteratively): looping Some statements are executed only if certain conditions are met A condition is met if it evaluates to true C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 Control Structures (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 Relational Operators A condition is represented by a logical (Boolean) expression that can be true or false Relational operators: - Allow comparisons - Require two operands (binary) - Evaluate to true or false C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6 Relational Operators (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 7 Relational Operators and Simple Data Types You can use the relational operators with all three simple data types: - 8 < 15 evaluates to true - 6 != 6 evaluates to false - 2.5 > 5.8 evaluates to false - 5.9 <= 7.5 evaluates to true C++ Programming: From Problem Analysis to Program Design, Fifth Edition 8 Comparing Characters Expression with relational operators - Depends on machine's collating sequence - ASCII character set Logical (Boolean) expressions - Expressions such as 4 < 6 and 'R' > 'T' - Returns an integer value of 1 if the logical expression evaluates to true - Returns an integer value of 0 otherwise C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9 Relational Operators and the string Type Relational operators can be applied to strings Strings are compared character by character, starting with the first character Comparison continues until either a mismatch is found or all characters are found equal If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string - The shorter string is less than the larger string C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10 Relational Operators and the string Type (cont'd.) Suppose we have the following declarations: string string string string string str1 str2 str3 str4 str4 = = = = = "Hello"; "Hi"; "Air"; "Bill"; "Big"; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11 Relational Operators and the string Type (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 12 Relational Operators and the string Type (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 13 Logical (Boolean) Operators and Logical Expressions Logical (Boolean) operators enable you to combine logical expressions C++ Programming: From Problem Analysis to Program Design, Fifth Edition 14 Logical (Boolean) Operators and Logical Expressions (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 15 Logical (Boolean) Operators and Logical Expressions (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 16 Logical (Boolean) Operators and Logical Expressions (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 17 Order of Precedence Relational and logical operators are evaluated from left to right The associativity is left to right Parentheses can override precedence C++ Programming: From Problem Analysis to Program Design, Fifth Edition 18 Order of Precedence (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 19 Order of Precedence (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 20 Order of Precedence (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 21 Order of Precedence (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 22 int Data Type and Logical (Boolean) Expressions Earlier versions of C++ did not provide built-in data types that had Boolean values Logical expressions evaluate to either 1 or 0 - The value of a logical expression was stored in a variable of the data type int You can use the int data type to manipulate logical (Boolean) expressions C++ Programming: From Problem Analysis to Program Design, Fifth Edition 23 The bool Data Type and Logical (Boolean) Expressions The data type bool has logical (Boolean) values true and false bool, true, and false are reserved words The identifier true has the value 1 The identifier false has the value 0 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24 Selection: if and if...else One-Way Selection Two-Way Selection Compound (Block of) Statements Multiple Selections: Nested if Comparing if...else Statements with a Series of if Statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 25 One-Way Selection The syntax of one-way selection is: The statement is executed if the value of the expression is true The statement is bypassed if the value is false; program goes to the next statement if is a reserved word C++ Programming: From Problem Analysis to Program Design, Fifth Edition 26 One-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 27 One-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 28 One-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 29 One-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 30 Two-Way Selection Two-way selection takes the form: If expression is true, statement1 is executed; otherwise, statement2 is executed - statement1 and statement2 are any C++ statements else is a reserved word C++ Programming: From Problem Analysis to Program Design, Fifth Edition 31 Two-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 32 Two-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 33 Two-Way Selection (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 34 Compound (Block of) Statements Compound statement (block of statements): A compound statement is a single statement C++ Programming: From Problem Analysis to Program Design, Fifth Edition 35 Compound (Block of) Statements (cont'd.) if (age > { cout << cout << } else { cout << cout << } 18) "Eligible to vote." << endl; "No longer a minor." << endl; "Not eligible to vote." << endl; "Still a minor." << endl; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 36 Multiple Selections: Nested if Nesting: one control statement in another An else is associated with the most recent if that has not been paired with an else C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37 Multiple Selections: Nested if (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38 Multiple Selections: Nested if (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 39 Multiple Selections: Nested if (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 40 Comparing if...else Statements with a Series of if Statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 41 Short-Circuit Evaluation Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known Example: (age >= 21) || ( x == 5) //Line 1 (grade == 'A') && (x >= 7) //Line 2 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 42 Comparing Floating-Point Numbers for Equality: A Precaution Comparison of floating-point numbers for equality may not behave as you would expect - Example: 1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0 evaluates to false Why? 3.0/7.0 + 2.0/7.0 + 2.0/7.0 = 0.99999999999999989 Solution: use a tolerance value - Example: fabs(x - y) < 0.000001 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 43 Associativity of Relational Operators: A Precaution C++ Programming: From Problem Analysis to Program Design, Fifth Edition 44 Associativity of Relational Operators: A Precaution (cont'd.) num = 5 num = 20 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 45 Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques Must use concepts and techniques correctly; - Otherwise solution will be either incorrect or deficient If you do not understand a concept or technique completely - Don't use it - Save yourself an enormous amount of debugging time C++ Programming: From Problem Analysis to Program Design, Fifth Edition 46 Input Failure and the if Statement If input stream enters a fail state - All subsequent input statements associated with that stream are ignored - Program continues to execute - May produce erroneous results Can use if statements to check status of input stream If stream enters the fail state, include instructions that stop program execution C++ Programming: From Problem Analysis to Program Design, Fifth Edition 47 Confusion Between the Equality (==) and Assignment (=) Operators C++ allows you to use any expression that can be evaluated to either true or false as an expression in the if statement: if (x = 5) cout << "The value is five." << endl; The appearance of = in place of == resembles a silent killer - It is not a syntax error - It is a logical error C++ Programming: From Problem Analysis to Program Design, Fifth Edition 48 Conditional Operator (?:) Conditional operator (?:) takes three arguments - Ternary operator Syntax for using the conditional operator: expression1 ? expression2 : expression3 If expression1 is true, the result of the conditional expression is expression2 - Otherwise, the result is expression3 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 49 Program Style and Form (Revisited): Indentation If your program is properly indented - Spot and fix errors quickly - Show the natural grouping of statements Insert a blank line between statements that are naturally separate Two commonly used styles for placing braces - On a line by themselves - Or left brace is placed after the expression, and the right brace is on a line by itself C++ Programming: From Problem Analysis to Program Design, Fifth Edition 50 Using Pseudocode to Develop, Test, and Debug a Program Pseudocode, or just pseudo - Informal mixture of C++ and ordinary language - Helps you quickly develop the correct structure of the program and avoid making common errors Use a wide range of values in a walkthrough to evaluate the program C++ Programming: From Problem Analysis to Program Design, Fifth Edition 51 switch Structures switch structure: alternate to if-else switch (integral) expression is evaluated first Value of the expression determines which corresponding action is taken Expression is sometimes called the selector C++ Programming: From Problem Analysis to Program Design, Fifth Edition 52 switch Structures (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 53 switch Structures (cont'd.) One or more statements may follow a case label Braces are not needed to turn multiple statements into a single compound statement The break statement may or may not appear after each statement switch, case, break, and default are reserved words C++ Programming: From Problem Analysis to Program Design, Fifth Edition 54 switch Structures (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 55 Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques: Revisited To output results correctly - The switch structure must include a break statement after each cout statement C++ Programming: From Problem Analysis to Program Design, Fifth Edition 56 Terminating a Program with the assert Function Certain types of errors that are very difficult to catch can occur in a program - Example: division by zero can be difficult to catch using any of the programming techniques examined so far The predefined function, assert, is useful in stopping program execution when certain elusive errors occur C++ Programming: From Problem Analysis to Program Design, Fifth Edition 57 The assert Function (cont'd.) Syntax: expression is any logical expression If expression evaluates to true, the next statement executes If expression evaluates to false, the program terminates and indicates where in the program the error occurred To use assert, include cassert header file C++ Programming: From Problem Analysis to Program Design, Fifth Edition 58 The assert Function (cont'd.) assert is useful for enforcing programming constraints during program development After developing and testing a program, remove or disable assert statements The preprocessor directive #define NDEBUG must be placed before the directive #include to disable the assert statement C++ Programming: From Problem Analysis to Program Design, Fifth Edition 59 Programming Example: Cable Company Billing This programming example calculates a customer's bill for a local cable company There are two types of customers: - Residential - Business Two rates for calculating a cable bill: - One for residential customers - One for business customers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 60 Programming Example: Rates For residential customer: - Bill processing fee: $4.50 - Basic service fee: $20.50 - Premium channel: $7.50 per channel For business customer: - Bill processing fee: $15.00 - Basic service fee: $75.00 for first 10 connections/ $5.00 for each additional one - Premium channel cost: $50.00 per channel for any number of connections C++ Programming: From Problem Analysis to Program Design, Fifth Edition 61 Programming Example: Requirements Ask user for account number and customer code Assume R or r stands for residential customer and B or b stands for business customer C++ Programming: From Problem Analysis to Program Design, Fifth Edition 62 Programming Example: Input and Output Input: - Customer account number - Customer code - Number of premium channels - For business customers, number of basic service connections Output: - Customer's account number - Billing amount C++ Programming: From Problem Analysis to Program Design, Fifth Edition 63 Programming Example: Program Analysis Purpose: calculate and print billing amount Calculating billing amount requires: - Customer for whom the billing amount is calculated (residential or business) - Number of premium channels to which the customer subscribes For a business customer, you need: - Number of basic service connections - Number of premium channels C++ Programming: From Problem Analysis to Program Design, Fifth Edition 64 Programming Example: Program Analysis (cont'd.) Data needed to calculate the bill, such as bill processing fees and the cost of a premium channel, are known quantities The program should print the billing amount to two decimal places C++ Programming: From Problem Analysis to Program Design, Fifth Edition 65 Programming Example: Algorithm Design Set precision to two decimal places Prompt user for account number and customer type If customer type is R or r - Prompt user for number of premium channels - Compute and print the bill If customer type is B or b - Prompt user for number of basic service connections and number of premium channels - Compute and print the bill C++ Programming: From Problem Analysis to Program Design, Fifth Edition 66 Programming Example: Variables and Named Constants C++ Programming: From Problem Analysis to Program Design, Fifth Edition 67 Programming Example: Formulas Billing for residential customers: amountDue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numOfPremChannels * RES_COST_PREM_CHANNEL; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 68 Programming Example: Formulas (cont'd.) Billing for business customers: if (numOfBasicServConn <= 10) amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL; else amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numOfBasicServConn - 10) * BUS_BASIC_CONN_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 69 Programming Example: Main Algorithm 1. Output floating-point numbers in fixed decimal with decimal point and trailing zeros - Output floating-point numbers with two decimal places and set the precision to two decimal places 2. 3. 4. 5. Prompt user to enter account number Get customer account number Prompt user to enter customer code Get customer code C++ Programming: From Problem Analysis to Program Design, Fifth Edition 70 Programming Example: Main Algorithm (cont'd.) 6. If the customer code is r or R, - Prompt user to enter number of premium channels - Get the number of premium channels - Calculate the billing amount - Print account number and billing amount C++ Programming: From Problem Analysis to Program Design, Fifth Edition 71 Programming Example: Main Algorithm (cont'd.) 7. If customer code is b or B, - Prompt user to enter number of basic service connections - Get number of basic service connections - Prompt user to enter number of premium channels - Get number of premium channels - Calculate billing amount - Print account number and billing amount C++ Programming: From Problem Analysis to Program Design, Fifth Edition 72 Programming Example: Main Algorithm (cont'd.) 8. If customer code is other than r, R, b, or B, output an error message C++ Programming: From Problem Analysis to Program Design, Fifth Edition 73 Summary Control structures alter normal control flow Most common control structures are selection and repetition Relational operators: ==, <, <=, >, >=, != Logical expressions evaluate to 1 (true) or 0 (false) Logical operators: ! (not), && (and), || (or) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 74 Summary (cont'd.) Two selection structures: one-way selection and two-way selection The expression in an if or if...else structure is usually a logical expression No stand-alone else statement in C++ - Every else has a related if A sequence of statements enclosed between braces, { and }, is called a compound statement or block of statements C++ Programming: From Problem Analysis to Program Design, Fifth Edition 75 Summary (cont'd.) Using assignment in place of the equality operator creates a semantic error switch structure handles multiway selection break statement ends switch statement Use assert to terminate a program if certain conditions are not met C++ Programming: From Problem Analysis to Program Design, Fifth Edition 76 C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countcontrolled, sentinel-controlled, flagcontrolled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) Learn how to avoid bugs by avoiding patches Learn how to debug loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers: - Declare a variable for each number, input the numbers and add the variables together - Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 while Looping (Repetition) Structure The general form of the while statement is: while is a reserved word Statement can be simple or compound Expression acts as a decision maker and is usually a logical expression Statement is called the body of the loop The parentheses are part of the syntax C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 while Looping (Repetition) Structure (cont'd.) Infinite loop: continues to execute endlessly - Avoided by including statements in loop body that assure exit condition is eventually false C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6 while Looping (Repetition) Structure (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 7 Designing while Loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 8 Case 1: Counter-Controlled while Loops If you know exactly how many pieces of data need to be read, - while loop becomes a counter-controlled loop C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9 Case 2: Sentinel-Controlled while Loops Sentinel variable is tested in the condition Loop ends when sentinel is encountered C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10 Example 5-5: Telephone Digits Example 5-5 provides an example of a sentinel-controlled loop The program converts uppercase letters to their corresponding telephone digit C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11 Case 3: Flag-Controlled while Loops A flag-controlled while loop uses a bool variable to control the loop The flag-controlled while loop takes the form: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 12 Number Guessing Game Example 5-6 implements a number guessing game using a flag-controlled while loop The program uses the function rand of the header file cstdlib to generate a random number - rand() returns an int value between 0 and 32

Step by Step Solution

There are 3 Steps involved in it

Step: 1

Lets tackle each problem in your assignment in a detailed stepbystep manner Ill provide solutions for Problems 1 2 and 3 Problem 1 Cyclically Shifting an Array StepbyStep Solution 1 Read an array of 1... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Management Fundamentals

Authors: Robert N. Lussier

8th Edition

9781506389394

More Books

Students also viewed these General Management questions

Question

4. Describe cultural differences that influence perception

Answered: 1 week ago