|
|
|
|
|
|
|
6. The Do-While loop is a posttest loop. If there is a possibility that the loop body should be skipped entirely, use a While statement or a For statement. |
|
|
|
|
|
|
|
|
7. The For statement heading (the first line) always has three pieces within the parentheses. Most often, the first piece initializes a loop control variable, the second piece tests the variable, and the third piece increments or decrements the variable. The three pieces must be separated by semicolons. Any of the pieces can be omitted, but the semicolons still must be present. |
|
|
|
|
|
|
|
|
8. With nested control structures, the break statement can exit only one level of nestingthe innermost Switch or loop in which the break is located. |
|
|
|
|
|
|
|
|
The Switch statement is a multi-way selection statement. It allows the program to choose among a set of branches. A Switch containing break statements can always be simulated by an If-Then-Else-If structure. If a Switch can be used, however, it often makes the code easier to read and understand. A Switch statement cannot be used with floating point values as labels. |
|
|
|
|
|
|
|
|
The Do-While is a general-purpose looping statement. It is like the While loop except that its test occurs at the end of the loop, guaranteeing at least one execution of the loop body. As with a While loop, a Do-While continues as long as the loop condition is nonzero (true). |
|
|
|
|
|
|
|
|
The For statement is also a general-purpose looping statement, but its most common use is to implement count-controlled loops. The initialization, testing, and incrementation (or decrementation) of the loop control variable are centralized in one location, the first line of the For statement. |
|
|
|
|
|
|
|
|
The For, Do-While, and Switch statements are the ice cream and cake of C++. We can live without them if we absolutely must, but they are very nice to have. |
|
|
|
|
|
|
|
|
1. Given a switch expression that is the int variable nameVal, write a Switch statement that prints your first name if nameVal = 1, your middle name if nameVal = 2, and your last name if nameVal = 3. (pp. 460464) |
|
|
|
|
|
|
|
|
2. How would you change the answer to Question 1 so that it prints an error message if the value is not 1, 2, or 3? (pp. 460464) |
|
|
|
|
|
|
|
|
3. What is the primary difference between a While loop and a Do-While loop? (pp. 464468) |
|
|
|
|
|
|
|
|
4. A certain problem requires a count-controlled loop that starts at 10 and counts down to 1. Write the heading (the first line) of a For statement that controls this loop. (pp.468471) |
|
|
|
|
|
|
|
|
5. Within a loop, how does a continue statement differ from a break statement? (pp. 472474) |
|
|
|
|
|