section 3.6: Loops -- Do-while

page 63

Note the semicolon following the parenthesized expression in the do-while loop; it's a required part of the syntax.

Make sure you understand the difference between a while loop and a do-while loop. A while loop executes strictly according to its conditional expression: if the expression is never true, the loop executes zero times. The do-while loop, on the other hand, makes an initial ``no peek'' foray through the loop body no matter what.

To see the difference, let's imagine three different ways of writing the loop in the itoa function on page 64. Suppose we somehow forgot to use a termination condition at all, and wrote something like

	for(;;) {
		s[i++] = n % 10 + '0';
		n /= 10;
	}
Eventually, n becomes zero, but we keep going around the loop, and we convert a number like 123 into a string like "0000000000123", except with an infinite number of leading zeroes. (Mathematically, this is correct, but it's not what we want here, especially if we want our program to use a finite amount of time and space.)

Our next attempt might be

	while(n > 0) {
		s[i++] = n % 10 + '0';
		n /= 10;
	}
so that we stop creating digits when n reaches 0. This works fine for positive numbers, but for 0, it stops too soon: it would convert the number 0 to the empty string "". That's why the do-while loop is appropriate here; the fact that it always makes at least one pass through the loop makes sure that we always generate at least one digit, even it it's 0.

(It's also useful to look at the invariants in this loop: during each trip through the loop, n contains the rest of the number we have to convert, s[] contains the digits we've already converted, and i points at the next cell in s[] which is to receive a digit. Each trip through the loop converts one digit, increments i, and divides n by 10.)


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback