for statement and its general form is
![]()
for( expression 1; expression 2; expression 3 ) statement
![]()
![[For loop flow chart]](images/fig4-4.1.gif)
From the flow chart, we can see that the statement is equivalent to a while that's set up like this:
![]()
expression 1 ;
while( expression 2 ) {
statement
expression 3 ;
}
![]()
for and the "equivalent" while will
behave differently under the continue statement that
we'll see a little later.)
By way of example, we could print out the numbers from 0 to 9
using a for statement like this:
![]()
for( i = 0; i < 10; i++ ) printf( "%d\n", i ) ;
![]()
{}).
The for is much like the counted loop statement
discussed earlier, but it is more
flexible.
Instead of just counting by one, we can do any form of updating we
want in expression 3.
For example, to print out just the even numbers we could do something
like this:
![]()
for( i = 0; i < 10; i += 2 ) printf( "%d\n", i ) ;
![]()
for statement which counts the variable x
down from 10 to (but not including) 0.
![]()