Look at this example:
Code:
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i<10; i++)
{
cout<<i<<" ";
}
cout<<endl;
return 0;
};
Output:
0 1 2 3 4 5 6 7 8 9
The first thing that happens in that for-loop is that the variable i is created and assigned the value 0:
Code:
for(int i = 0; i<10; i++)
That assignment only executes the first time through the for loop.
Next, the conditional is tested to see whether the statements inside the body of the for-loop should be executed:
Code:
for(int i = 0; i<10; i++)
If the conditional evaluates to true, then the statements inside the body of the for-loop are executed:
Code:
for(int i = 0; i<10; i++)
{
cout<<i<<" ";
}
If the conditional evaluates to false, then the statements inside the for-loop are skipped, and execution continues with the next statement after the for loop:
Code:
for(int i = 0; i<10; i++)
{
cout<<i<<" ";
}
cout<<endl;
The conditional is tested every time through the for-loop.
After the statements inside the for loop execute, the third piece of code in the for-loop header is executed:
Code:
for(int i = 0; i<10; i++)
That says to increment the variable 'i' by one. That executes at the end of every loop.
So, the first time through the loop, i is set equal to 0. Then the conditional is evaluated: since 0 is less than 10, the statements inside the body of the for loop are executed. After all the statements inside the for-loop execute, i is incremented by 1, so i is then equal to 1. Thereafter, execution jumps up to the for-loop header again. The assignment where i is set equal to 0 is skipped(remember that only executes the first time through the loop), so the conditional is evaluated. Since 1 is less than 10, the statements inside the for loop execute again. At the end of the loop, i is incremented by 1 again, so i is then equal to 2. Once again execution jumps up to the for-loop header, and the conditional is evaluated. Since i is equal to 2 and 2 is less than 10, the statements inside the for loop execute again...etc., etc.
See if you can guess the output of this code:
Code:
#include <iostream>
using namespace std;
int main()
{
for(int i = 5; i<10; i=i+2)
{
cout<<i<<" ";
}
cout<<endl;
return 0;
};