for Statement
for( [init-expr]; [cond-expr]; [loop-expr] )
statement
The for keyword executes statement repeatedly.
First, the initialization (init-expr) is evaluated. Then, while the conditional expression (cond-expr) evaluates to a nonzero value, statement is executed and the loop expression (loop-expr) is evaluated. When cond-expr becomes 0, control passes to the statement following the for loop.
For more information, see while, break, and continue.
Example
// Example of the for statement
for ( i = space = tab = 0; i < MAX; i++ )
{
if ( line[i] == ' ' )
space++;
if ( line[i] == '\t' )
{
tab++;
line[i] = ' ';
}
}
This example counts space (' '
) and tab ('\t'
) characters in the array of characters named line
and replaces each tab character with a space. First i
, space
, and tab
are initialized to 0. Then i
is compared with the constant MAX
; if i
is less than MAX
, the statement body is executed. Depending on the value of line[i]
, the body of one or neither of the if statements is executed. Then i
is incremented and tested against MAX
; the statement body is executed repeatedly as long as i
is less than MAX
.