-
There are conditional looping situations where it is desirable to have the loop execute at least once, and then evaluate an exit expression at the end of the loop.
The do-while
loop allows you to do a statement first, and then evaluate an exit condition. The do-while
loop complements the while
loop that evaluates the exit expression at the top of the loop.
- The general form of a
do-while
loop is:
do{
statement;
}while (expression);
- The flow of control for a
do-while
loop is illustrated:
- The following fragment of code will keep a running total of integers, terminated by a sentinel zero value.
int number, total = 0;
do{
System.out.print("Enter an integer (0 to quit) --> ");
number = in.readInt();
total += number;
}while (number != 0);
In contrast to the while
loop version, the do-while
has the advantage of using only one input statement inside of the loop. Because the Boolean condition is at the bottom, you must pass through the main body of a do-while
loop at least once.
- The same strategies used to develop
while
loops apply to do-while
loops. Make sure you think about the following four sections of the loop: initialization, loop boundary, contents of the loop, and the state of variables after the loop.