- 4.1 Introduction
- 4.2 Essentials of Counter-Controlled Iteration
- 4.3 for Iteration Statement
- 4.4 Examples Using the for Statement
- 4.5 Application: Summing Even Integers
- 4.6 Application: Compound-Interest Calculations
- 4.7 do... while Iteration Statement
- 4.8 switch Multiple-Selection Statement
- 4.9 C++17 Selection Statements with Initializers
- 4.10 break and continue Statements
- 4.11 Logical Operators
- 4.12 Confusing the Equality (==) and Assignment (=) Operators
- 4.13 Objects-Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files
- 4.14 C++20 Text Formatting with Field Widths and Precisions
- 4.15 Wrap-Up
4.7 do… while Iteration Statement
In a while statement, the program tests the loop-continuation condition before executing the loop’s body. If it’s false, the body never executes. The do…while iteration statement tests the loop-continuation condition after executing the loop’s body; so, the body always executes at least once. Figure 4.5 uses a do…while to output the numbers 1–10. Line 7 declares and initializes control variable counter. Upon entering the do…while statement, line 10 outputs counter’s value and line 11 increments counter. Then the program evaluates the loop-continuation test at the bottom of the loop (line 12). If the condition is true, the loop continues at the first body statement (line 10). If the condition is false, the loop terminates, and the program continues at the next statement after the loop.
1 // fig04_05.cpp 2 // do...while iteration statement. 3 #include <iostream> 4 using namespace std; 5 6 int main() { 7 int counter{1}; 8 9 do { 10 cout << counter << " "; 11 ++counter; 12 } while (counter <= 10); // end do...while 13 14 cout << "\n"; 15 }
1 2 3 4 5 6 7 8 9 10
Fig. 4.5 |do…while iteration statement.
UML Activity Diagram for the do…while Iteration Statement
The do…while’s UML activity diagram makes it clear that the loop-continuation condition is not evaluated until after the loop performs the action state at least once: