statement, we can rewrite
void CountDown (
int iN )
while ( iN > 0 )
ShowText ( iN );
iN = iN - 1;
ShowText ( "START!!!" );
You can almost read a while statement as if it were English. What this
means is, “While iN is greater than zero, continue displaying the value
of iN and then reducing the value of iN by 1. When you get to zero,
output the word "
More formally, the flow of
execution for a while statement is as follows:
Evaluate the condition in
parentheses, yielding true or false.
If the condition is false, exit the while statement and continue
at the next statement.
If the condition is true, execute each of the statements between the
squiggly-braces, and then go back to step 1.
This type of flow is called a loop
because the third step loops back around to the top. Notice that if the
condition is false the first time through the loop, the statements
inside the loop are never executed. The statements inside the loop are
called the body of the loop.
The body of the loop
should change the value of one or more variables so that, eventually,
the condition becomes false and the loop terminates. Otherwise the loop
will repeat forever, which is called an infinite loop. An endless
source of amusement for computer scientists is the observation that the
directions on shampoo, “Lather, rinse, repeat,” are an infinite loop.
In the case of CountDown, we can prove that the loop will terminate
because we know that the value of n is finite, and we can see that the
value of iN gets smaller each time through the loop (each
iteration), so eventually we have to get to zero. In other cases it is
not so easy to tell.