The do
...while
repetition statement is similar to the while
statement. In the while
statement, the loop-continuation condition test occurs at the beginning of the loop before the body of the loop executes. 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.7 uses a do
...while
statement to print the numbers 1–10. Upon entering the do
...while
statement, line 12 outputs counter
’s value and line 13 increments counter
. Then the program evaluates the loop-continuation test at the bottom of the loop (line 14). If the condition is true, the loop continues from the first body statement in the do
...while
(line 12). If the condition is false, the loop terminates and the program continues with the next statement after the loop (line 16).
1 // Fig. 5.7: fig05_07.cpp
2 // do...while repetition statement.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 unsigned int counter = 1; // initialize counter
9
10 do
11 {
12 cout << counter << " "; // display counter
13 ++counter; // increment counter
14 } while ( counter <= 10 ); // end do...while
15
16 cout << endl; // output a newline
17 } // end main
1 2 3 4 5 6 7 8 9 10
13.59.237.58