Iteration:
FOR
Aforstatement
works in a very similar way to an whilestatement.
However, forstatements
are particularly useful for concisely
writing counter controlled loops.
The general form of aforstatement
can be illustrated as:
for(
<loop initialise>; <loop condition>; <post loop action>)
{
<actions to perform if loop condition is true>
}
The way aforloop
works is as follows:
-
first the <loop initialise> statement
is executed
-
then the loop condition is tested
-
if the loop condition is true
-
the loop actions are performed
-
the post loop action is performed
-
the loop condition is tested again and
so on
-
once the loop condition is found to be
false, the loop terminates
An example of awhile
loop,
and its equivalent
for
loop
are as follows:
//
a WHILE loop
int
counter = 0;
while(
counter < 10 )
{
<action1>
<action2>
counter = counter + 1;
}
//
an equivalent FOR loop
int
counter;
for(
counter = 0; counter < 10; counter = counter + 1)
{
<action1>
<action2>
}
As can be seen, for counter controlled
loops such as the above, the for loop is neater, since it moves the post
loop action of incrementing the counter inside the loop definition line.
The table below illustrates what happens
when this for loop is executed:
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|