Home > Articles

This chapter is from the book

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 dowhile to output the numbers 1–10. Line 7 declares and initializes control variable counter. Upon entering the dowhile 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 |dowhile iteration statement.

UML Activity Diagram for the dowhile Iteration Statement

The dowhile’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:

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.