Sams Teach Yourself C in 21 Days

(singke) #1

  1. If conditionevaluates to false (that is, it is equal to zero), the forstatement termi-
    nates and execution passes to the first statement following statement.

  2. If conditionevaluates to true (that is, it is equal to a nonzero value), the C state-
    ment(s) in statementare executed.

  3. The expression incrementis evaluated, and execution returns to step 2.
    Figure 6.1 shows the operation of a forstatement. Note that statementnever executes if
    conditionis false the first time it’s evaluated.


126 Day 6

FIGURE6.1
A schematic represen-
tation of a forstate-
ment.
Evaluate
initial

Evaluate
increment

Start

Evaluate
condition

Done

Execute
statements

for (initial; condition; increment)
statements
TRUE

FALSE

Listing 6.1 presents a simple example by using a forstatement to print the numbers 1
through 20. You can see that the resulting code is much more compact than it would be if
a separate printf()statement were used for each of the 20 values.

LISTING6.1 forstate.c. A simple forstatement
1: /* Demonstrates a simple for statement */
2:
3: #include <stdio.h>
4:
5: int count;
6:
7: int main( void )
8: {
9: /* Print the numbers 1 through 20 */

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

Free download pdf