Basic Program Control 133
6
ThewhileStatement ....................................................................................
Thewhilestatement, also called the whileloop,executes a block of statements as long
as a specified condition is true. The whilestatement has the following form:
while (condition)
statement
conditionis any C expression, and statementis a single or compound C statement.
When program execution reaches a whilestatement, the following events occur:
- The expression conditionis evaluated.
- If conditionevaluates to false (that is, zero), the whilestatement terminates, and
execution passes to the first statement following statement. - If conditionevaluates to true (that is, nonzero), the C statement(s) in statement
are executed. - Execution returns to step 1.
The operation of a whilestatement is shown in Figure 6.3.
FIGURE6.3
The operation of a
whilestatement.
Start
Evaluate
condition
Done
Execute
statements
while (condition)
statements;
FALSE
TRUE
Listing 6.3 is a simple program that uses a whilestatement to print the numbers 1
through 20. (This is the same task that is performed by a forstatement in Listing 6.1.)
LISTING6.3 whilest.c. A simple whilestatement
1: /* Demonstrates a simple while statement */
2:
3: #include <stdio.h>
4:
5: int count;
10 448201x-CH06 8/13/02 11:20 AM Page 133