C++ Control Statements (Chapter 5) PDF
Document Details
Uploaded by DesirousBowenite1923
2017
Tags
Summary
This document is chapter 5 of a C++ programming textbook, covering control statements and iteration, with examples and explanation.
Full Transcript
Chapter 5 of C++ How to Program, 10/e © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Counter-controlled iteration requires ◦ a control variable (or loop counter) ◦ the control variable’s initial value ◦ the con...
Chapter 5 of C++ How to Program, 10/e © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Counter-controlled iteration requires ◦ a control variable (or loop counter) ◦ the control variable’s initial value ◦ the control variable’s increment that’s applied during each iteration of the loop ◦ the loop-continuation condition that determines if looping should continue. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The for iteration statement (Fig. 5.2) specifies the counter-controlled iteration details in a single line of code. The initialization occurs once when the loop is encountered. The condition is tested next and each time the body completes. The body executes if the condition is true. The increment occurs after the body executes. Then, the condition is tested again. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The general form of the for statement is for (initialization; loopContinuationCondition; increment) { statement } where the initialization expression initializes the loop’s control variable, loopContinuationCondition determines whether the loop should continue executing and increment increments the control variable. In most cases, the for statement can be represented by an equivalent while statement, as follows: initialization; while (loopContinuationCondition) { statement increment; } © 2017 by Pearson Education, Ltd. All Rights Reserved. If the initialization expression declares the control variable, the control variable can be used only in the body of the for statement—the control variable will be unknown outside the for statement. This restricted use of the control variable name is known as the variable’s scope. The scope of a variable specifies where it can be used in a program. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The three expressions in the for statement header are optional (but the two semicolon separators are required). If the loopContinuationCondition is omitted, C++ assumes that the condition is true, thus creating an infinite loop. One might omit the initialization expression if the control variable is initialized earlier in the program. One might omit the increment expression if the increment is calculated by statements in the body of the for or if no increment is needed. © 2017 by Pearson Education, Ltd. All Rights Reserved. The increment expression in the for statement acts like a standalone statement at the end of the for statement’s body. The expressions counter = counter + 1 counter += 1 ++counter counter++ are all equivalent in the increment expression (when no other code appears there). © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Count from 1 to 100 in increments of 1. for (unsigned int i = 1; i = 1; --i) Count from 7 to 77 in steps of 7. for (unsigned int i = 7; i = 2; i -= 2) Iterate over the sequence 2, 5, 8, 11, 14 , 17 , 20. for (unsigned int i = 2; i = 0; i -= 11) © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The program of Fig. 5.5 uses a for statement to sum the even integers from 2 to 20. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Consider the following problem statement: ◦ A person invests $1000.00 in a savings account yielding 5% interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts: a = p (1 + r) n where p is the original amount invested (i.e., the principal), r is the annual interest rate, n is the number of years and a is the amount on deposit at the end of the nth year. ◦ This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit (Fig. 5.6). © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Similar to the while statement. The do…while statement tests the loop- continuation condition after the loop body executes; therefore, the loop body always executes at least once. Figure 5.9 uses a do…while statement to print the numbers 1–10. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. do…while Statement UML Activity Diagram Figure 5.10 contains the do…while statement’s UML activity diagram, which makes it clear that the loop-continuation condition is not evaluated until after the loop performs its body at least once. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The switch multiple-selection statement performs many different actions based on the possible values of a variable or expression. Each action is associated with the value of an integral constant expression (i.e., any combination of character and integer constants that evaluates to a constant integer value). Figure 5.11 calculates the class average of a set of numeric grades entered by the user, and uses a switch statement to determine whether each grade is the equivalent of an A, B, C, D or F and to increment the appropriate grade counter. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Lines 16–19 prompt the user to enter integer grades or type the end-of-file indicator to terminate the input. The end-of-file indicator is a system-dependent keystroke combination used to indicate that there’s no more data to input. In Chapter 14, File Processing, you’ll see how the end-of-file indicator is used when a program reads its input from a file. © 2017 by Pearson Education, Ltd. All Rights Reserved. On UNIX/Linux/Mac OS X systems, end-of-file is entered by typing the following sequence on a line by itself ◦ d ◦ This notation means to simultaneously press both the Ctrl key and the d key. On Windows systems, end-of-file can be entered by typing ◦ z ◦ Windows typically displays the characters ^Z on the screen in response to this key combination © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The switch statement consists of a series of case labels and an optional default case. When the flow of control reaches the switch, the program evaluates the controlling expression in the parentheses. Compares the value of the controlling expression with each case label. If a match occurs, the program executes the statements for that case. The break statement causes program control to proceed with the first statement after the switch. © 2017 by Pearson Education, Ltd. All Rights Reserved. Listing cases consecutively with no statements between them enables the cases to perform the same set of statements. Each case can have multiple statements. ◦ The switch selection statement does not require braces around multiple statements in each case. Without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered. ◦ Referred to as “falling through” to the statements in subsequent cases. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. If no match occurs between the controlling expression’s value and a case label, the default case executes. If no match occurs in a switch statement that does not contain a default case, program control continues with the first statement after the switch. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. case values ◦ An integer constant is simply an integer value. ◦ In addition, you can use character constants—specific characters in single quotes, such as 'A', '7' or '$'—which represent the integer values of characters and enum constants (introduced in Section 6.8). (Appendix B shows the integer values of the characters in the ASCII character set, which is a subset of the Unicode® character set.) ◦ The expression in each case also can be a constant variable—a variable containing a value which does not change for the entire program. Such a variable is declared with keyword const © 2017 by Pearson Education, Ltd. All Rights Reserved. In addition to selection and iteration statements, C++ provides statements break (which we discussed in the context of the switch statement) and continue to alter the flow of control. © 2017 by Pearson Education, Ltd. All Rights Reserved. The break statement, when executed in a while, for, do…while or switch statement, causes immediate exit from that statement. Program execution continues with the next statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch statement. Figure 5.13 demonstrates the break statement (line 13) exiting a for iteration statement. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. In while and do…while statements, the loop- continuation test evaluates immediately after the continue statement executes. In the for statement, the increment expression executes, then the loop-continuation test evaluates. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. C++ provides logical operators that are used to form more complex conditions by combining simple conditions. The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also called logical negation). © 2017 by Pearson Education, Ltd. All Rights Reserved. The && (logical AND) operator is used to ensure that two conditions are both true before we choose a certain path of execution. The simple condition to the left of the && operator evaluates first. If necessary, the simple condition to the right of the && operator evaluates next. The right side of a logical AND expression is evaluated only if the left side is true. © 2017 by Pearson Education, Ltd. All Rights Reserved. Figure 5.15 summarizes the && operator. The table shows all four possible combinations of false and true values for expression1 and expression2. Such tables are often called truth tables. C++ evaluates to false or true all expressions that include relational operators, equality operators and/or logical operators. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The || (logical OR) operator determines if either or both of two conditions are true before we choose a certain path of execution. Figure 5.16 is a truth table for the logical OR operator (||). The && operator has a higher precedence than the || operator. Both operators associate from left to right. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. An expression containing && or || operators evaluates only until the truth or falsehood of the expression is known. This performance feature for the evaluation of logical AND and logical OR expressions is called short-circuit evaluation. © 2017 by Pearson Education, Ltd. All Rights Reserved. if (a == b || c == d || e == f) { // Do something } // if a==b, then do not check c==d, e==f. What if: if (a == b || c++ == d || e == --f) { // Do something } // if a==b, then c++ and –-f will not executed. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. The ! (logical negation, also called logical NOT or logical complement) operator “reverses” the meaning of a condition. Unlike the logical operators && and ||, which are binary operators that combine two conditions, the logical negation operator is a unary operator that has only one condition as an operand. Figure 5.17 is a truth table for the logical negation operator. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Figure 5.18 demonstrates the logical operators by producing their truth tables. The output shows each expression that is evaluated and its bool result. By default, bool values true and false are displayed by cout and the stream insertion operator as 1 and 0, respectively. Stream manipulator boolalpha (a sticky manipulator) specifies that the value of each bool expression should be displayed as either the word “true” or the word “false.” © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Figure 5.19 adds the logical and comma operators to the operator precedence and associativity chart. The operators are shown from top to bottom, in decreasing order of precedence. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Accidentally swapping the operators == (equality) and = (assignment). Damaging because they ordinarily do not cause syntax errors. Rather, statements with these errors tend to compile correctly and the programs run to completion, often generating incorrect results through runtime logic errors. [Note: Some compilers issue a warning when = is used in a context where == typically is expected.] Two aspects of C++ contribute to these problems. ◦ One is that any expression that produces a value can be used in the decision portion of any control statement. ◦ The second is that assignments produce a value—namely, the value assigned to the variable on the left side of the assignment operator. Any nonzero value is interpreted as true. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. We’ve learned that structured programming produces programs that are easier than unstructured programs to understand, test, debug, modify, and even prove correct in a mathematical sense. Figure 5.20 uses activity diagrams to summarize C++’s control statements. The initial and final states indicate the single entry point and the single exit point of each control statement. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. Figure 5.21 shows the rules for forming structured programs. The rules assume that action states may be used to indicate any action. The rules also assume that we begin with the so-called simplest activity diagram (Fig. 5.22), consisting of only an initial state, an action state, a final state and transition arrows. Applying the rules of Fig. 5.21 always results in an activity diagram with a neat, building-block appearance. Rule 2 generates a stack of control statements, so let’s call Rule 2 the stacking rule. Rule 3 is the nesting rule. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved. © 2017 by Pearson Education, Ltd. All Rights Reserved.