Chapter 4 Control, Functions, and Classes
Total Page:16
File Type:pdf, Size:1020Kb
June 7, 1999 10:10 owltex Sheet number 17 Page number 99 magenta black Control, Functions, and Classes 4 If A equals success, then the formula is A = X + Y + Z. X is work. Y is play. Z is keep your mouth shut. Albert Einstein quoted in SIGACT News, Vol. 25, No. 1, March 1994 Your “if” is the only peacemaker; much virtue in “if.” William Shakespeare As You Like It, V, iv Leave all else to the gods. Horace Odes, Book I, Ode ix In the programs studied in Chapter 3, statements executed one after the other to produce output. This was true both when all statements were in main or when control was transferred from main to another function, as it was in SlicePrice in pizza.cpp, Program 3.5. However, code behind the scenes in gfly.cpp, Program 3.6, executed differently in response to the user’s input and to a simulated wind-shear effect. Many programs require nonsequential control. For example, transactions made at automatic teller machines (ATMs) process an identification number and present you with a screen of choices. The program controlling the ATM executes different code depending on your choice—for example, either to deposit money or to get cash. This type of control is called selection: a different code segment is selected and executed based on interaction with the user or on the value of a program variable. Another type of program control is repetition: the same sequence of C++ statements is repeated, usually with different values for some of the variables in the statements. For example, to print a yearly calendar your program could call a PrintMonth function twelve times: PrintMonth("January", 31); //... PrintMonth("November",30); PrintMonth("December",31); Here the name of the month and the number of days in the month are arguments passed to PrintMonth. Alternatively, you could construct the PrintMonth function to determine the name of the month as well as the number of days in the month given the year and the number of the month. This could be done for the year 2000 by repeatedly executing the following statement and assigning values of 1; 2;:::;12 to month: PrintMonth(month, 2000); 99 June 7, 1999 10:10 owltex Sheet number 18 Page number 100 magenta black 100 Chapter 4 Control, Functions, and Classes In this chapter we’ll study methods for controlling how the statements in a program are executed and how this control is used in constructing functions and classes. To do this we’ll expand our study of arithmetic operators, introduced in the last chapter, to include operators for other kinds of data. We’ll also study C++ statements that alter the flow of control within a program. Finally, we’ll see how functions and classes can be used as a foundation on which we’ll continue to build as we study how programs are used to solve problems. At the end of the chapter you’ll be able to write the function PrintMonth but you’ll also see a class that encapsulates the function so you don’t have to write it. 4.1 The Assignment Operator In the next three sections we’ll use a program that makes change using U.S. coins to study relational and assignment statements and conditional execution. We’ll use the same program as the basis for what could be a talking cash register. A run of change.cpp, Program 4.1, shows how change is made using quarters, dimes, nickels, and pennies. The program shows how values can be stored in variables using the assignment operator, =. In previous programs the user entered values for variables, but values can also be stored using the assignment operator. The code below assigns values for the circumference and area of a circle according to the radius’ value, then prints the values.1 double radius, area, circumference; cout << "enter radius: "; cin >> radius; area = 3.14159*radius*radius; circumference = 3.14159*2*radius; cout << "area="<<area << " circumference="<<circumference << endl; The assignment operator in Program 4.1 has two purposes, it assigns the number of each type of coin needed to the appropriate variable (e.g., quarters and dimes) and it resets the value of the variable amount so that change will be correctly calculated. The assignment operator = stores values in variables. The expres- Syntax: assignment operator = sion on the right-hand side of the variable = expression = is evaluated, and this value is stored in the memory location as- sociated with the variable named on the left-hand side of the =. The use of the equal sign to assign values to vari- ables can cause confusion, especially if you say “equals” when you read an expression like quarters = amount/25. Operationally, the value on the right is stored in quarters, and it would be better to write quarters ← amount / 25. The as- signment statement can be read as “The memory location of the variable quarters is 1The formula for the area of a circle is πr2, the formula for circumference is 2πr where r is the radius. June 7, 1999 10:10 owltex Sheet number 19 Page number 101 magenta black 4.1 The Assignment Operator 101 assigned the value of amount/25,” but that is cumbersome (at best). If you can bring yourself to say “gets” for =, you’ll find it easier to distinguish between = and == (the boolean equality operator). Verbalizing the process by saying “Quarters gets amount divided by twenty-five” will help you understand what’s happening when assignment statements are executed. Program 4.1 change.cpp #include <iostream> using namespace std; // make change in U.S. coins // Owen Astrachan, 03/17/99 int main() { int amount; int quarters, dimes, nickels, pennies; // input phase of program cout << "make change in coins for what amount: "; cin >> amount; // calculate number of quarters, dimes, nickels, pennies quarters = amount/25; amount = amount − quarters∗25; dimes = amount/10; amount = amount − dimes∗10; nickels = amount/5; amount = amount − nickels∗5; pennies = amount; // output phase of program cout << "# quarters =\t" << quarters << endl; cout << "# dimes =\t" << dimes << endl; cout << "# nickels =\t" << nickels << endl; cout << "# pennies =\t" << pennies << endl; return 0; } change.cpp June 7, 1999 10:10 owltex Sheet number 20 Page number 102 magenta black 102 Chapter 4 Control, Functions, and Classes int amount; int amount; 87 amount = amount - quarters*25; 12 87 - 3*25 Before execution After execution int quarters; 3 Figure 4.1 Updating a variable via assignment. OUTPUT prompt> change make change in coins for what amount: 87 # quarters = 3 # dimes = 1 # nickels = 0 # pennies = 2 prompt> change make change in coins for what amount: 42 # quarters = 1 # dimes = 1 # nickels = 1 # pennies = 2 The statement amount = amount - quarters*25 updates the value of the variable amount. The right-hand side of the statement is evaluated first. The value of this expression, amount - quarters*25, is stored in the variable on the left- hand side of the assignment statement—that is, the variable amount. This process is diagrammed in Fig. 4.1 when amount is 87. A sequence of assignments can be chained together in one statement: x=y=z=13; This statement assigns the value 13 to the variables x, y, and z. The statement is interpreted as x = (y = (z = 13)). The value of the expression (z = 13) is 13, the value assigned to z. This value is assigned to y, and the result of the assignment to y is 13. This result of the expression (y = 13) is then assigned to x. Parentheses aren’t needed in the statement x=y=z=13, because the assignment operator = is right-associative: in the absence of parentheses the rightmost = is evaluated first. June 7, 1999 10:10 owltex Sheet number 21 Page number 103 magenta black 4.2 Choices and Conditional Execution 103 Table 4.1 Escape sequences in C++ escape sequence name ASCII \n newline NL (LF) \t horizontal tab HT \v vertical tab VT \b backspace BS \r carriage return CR \f form feed FF \a alert (bell) BEL \\ backslash \ \? question mark ? \’ single quote (apostrophe) ’ \" double quote " In contrast, the subtraction operator is left-associative, so the expression 8-3-2 is equal to 3, because it is evaluated as (8-3)-2rather than 8-(3-2): here the leftmost subtraction is evaluated first. Most operators are left-associative; the associativity of all C++ operators is shown in Table A.4 in Howto A. Escape Sequences. The output of change.cpp is aligned using a tab character ’\t’. The tab character prints one tab position, ensuring that the amounts of each kind of coin line up. The backslash and t to print the tab character are an example of an escape sequence. Common escape sequences are given in Table 4.1. The table is repeated as Table A.5 in Howto A. Each escape sequence prints a single character. For example, the following statement prints the four-character string "\’". cout << "\"\\\’\"" << endl; 4.2 Choices and Conditional Execution I shall set forth from somewhere, I shall make the reckless choice Robert Frost The Sound of the Trees In this section we’ll alter Program 4.1 so that it only prints the coins used in giv- ing change. We’ll also move the output part of the program to a separate function. By parameterizing the output and using a function, we make it simpler to incorporate modifications to the original program. June 7, 1999 10:10 owltex Sheet number 22 Page number 104 magenta black 104 Chapter 4 Control, Functions, and Classes Program Tip 4.1: Avoid duplicating the same code in several places in the same program.