The Do...While Loop
Last time we
looked at the while
loop. Today we'll examine it's
sibling the do...while
loop.
Unlike the while
loop, the do...while
loop is
guaranteed to execute the loop body at least once. The loop
condition is checked at the end of each loop iteration.
The do...while
loop starts with the keyword do
followed by a single statement or block that makes
up the body of the loop. The loop body is followed by the keyword
while
and parentheses containing the condition
with a semicolon at the end.
The do...while
loop is almost always written on three or
more lines, and almost always with a block instead of a single
statement.
/* do...while loop with a single statement */
do
statement;
while (condition);
/* do...while loop with a block */
do {
block;
} while (condition);
Initialization of the loop counter or other loop variables must be done
before the do...while
statement; this often means
declaring and initializing a local variable:
int i = 0;
do {
/* ... */
} while (i < 10);
When using a loop counter, it's important to remember to advance the
counter to the next value in the body of the loop. For instance, to
log the numbers 0 through 9:
int i = 0;
do {
NSLog(@"%d", i);
i++; /* advance the loop counter */
} while (i < 10);
If you forget to advance the loop counter, you'll create an infinite
loop.
int i = 0;
/* warning, infinite loop, i is always 0 */
do {
NSLog(@"%d", i);
/* oops, forgot to increment i */
} while (i < 10);
The key thing that differentiates the do...while
loop from
the while
loop is that it always executes the loop body at
least once; the while
loop doesn't guarantee that. An
example of this difference:
BOOL looping = NO;
NSLog(@"before while loop:");
while (looping) {
NSLog(@" executing the while loop");
}
NSLog(@"after while loop:");
NSLog(@"before do...while loop:");
do {
NSLog(@" executing the do...while loop");
} while (looping);
NSLog(@"after do...while loop:");
The output of these two loops looks like this:
before while loop:
after while loop:
before do...while loop:
executing the do...while loop
after do...while loop:
Next week,
we'll look at using break
to break out of a loop.