It is possible that the body of a while loop will never execute. The while statement checks its condition before executing any of its statements, and if the condition evaluates false, the entire body of the while loop is skipped. Listing 6.5 illustrates this.
What if you want to ensure that hello is always printed at least once? The while loop can't accomplish this because the if condition is tested before any printing is done. You can force the issue with an if statement just before entering the while:
if (counter < 1) // force a minimum value counter = 1;
but that is what programmers call a kludge, an ugly and inelegant solution.
The do...while loop executes the body of the loop before its condition is tested, and ensures that the body always executes at least one time. Listing 6.6 demonstrates this program rewritten with a do...while loop.
The user is prompted for a starting value on line 7, which is stored in the integer variable counter. In the do...while loop, the body of the loop is entered before the condition is tested, and therefore is guaranteed to be executed at least once. On line 11 the message is printed, on line 12 the counter is decremented, and on line 13 the condition is tested. If the condition evaluates true, execution jumps to the top of the loop on line 11; otherwise it falls through to line 14. |
The continue and break statements work in the do...while loop exactly as they do in the while loop. The only difference between a while loop and a do...while loop is when the condition is tested.
3.134.79.121