The for Loop
For loop is the controlled form of loop. The general format of this :
for( initialize ; test ; update)
{
statements;
:
:
}
The initialize part is implemented only once, before entering the loop. If test evaluates to false then the next statement after for loop is implemented. If the test evaluates to true then the updating takes place.
e.g.
for( int i = 0; i< 10; i++) // In C++ you can declare a
variable here.
{
cout << i;
}
This will print from 0 to 10.
The expressions in the for loop are optional but the semi-colons are essential, i.e.,
for( ; ; )
{
cout<<"hello";
}
This is an infinite loop, with no expression.
e.g.
int i = 0
for(; i< 10; )
{
cout << i;
i++;
}
This is equivalent to our example, which printed from 0 to 9. More than one expression can also be inside the for loop by separating them using commas.
e.g.
for( int i = 0, int j=10; i< 10 && y>0 ; i++, y--)
{
cout << i;
}