Sams Teach Yourself C in 21 Days

(singke) #1
Basic Program Control 139

6


The structure of the do...whileloop is as follows:
do
statement
while (condition);
conditionis any C expression, and statementis a single or compound C statement.
When program execution reaches a do...whilestatement, the following events occur:


  1. The statements in statementare executed.
    2.conditionis evaluated. If it’s true, execution returns to step 1. If it’s false, the loop
    terminates.
    The operation of a do...whileloop is shown in Figure 6.4.


FIGURE6.4
The operation of a
do...whileloop.

Execute
statements

Start

Evaluate
condition

Done

do statements;
while (condition);

TRUE

FALSE

The statements associated with a do...whileloop are always executed at least once.
This is because the test condition is evaluated at the end, instead of the beginning, of the
loop. In contrast,forloops and whileloops evaluate the test condition at the start of the
loop, so the associated statements are not executed at all if the test condition is initially
false.
Thedo...whileloop is used less frequently than whileandforloops. It is most appro-
priate when the statement(s) associated with the loop must be executed at least once. You
could, of course, accomplish the same thing with a whileloop by making sure that the
test condition is true when execution first reaches the loop. A do...whileloop probably
would be more straightforward, however.

10 448201x-CH06 8/13/02 11:20 AM Page 139

Free download pdf