do
…while
Iteration StatementThe do
…while
iteration statement is similar to the while
statement. In the while
, the app tests the loop-continuation condition at the beginning of the loop, before executing the loop’s body. If the condition is false, the body never executes. The do
…while
statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. When a do
…while
statement terminates, execution continues with the next statement in sequence. Figure 6.7 uses a do
…while
(lines 11–15) to output the numbers 1–10.
Line 9 declares and initializes control variable counter
. Upon entering the do
…while
statement, line 13 outputs counter
’s value, and line 14 increments counter
. Then the app evaluates the loop-continuation test at the bottom of the loop (line 15). If the condition is true, the loop continues from the first body statement (line 13). If the condition is false, the loop terminates, and the app continues with the next statement after the loop (line 17).
do
…while
Iteration StatementFigure 6.8 contains the UML activity diagram for the do
…while
statement. This diagram makes it clear that the loop-continuation condition is not evaluated until after the loop performs the action state at least once. Compare this activity diagram with that of the while
statement (Fig. 5.7).