1 2 3 4
|
for(int i = 0; i < 3; ++i)
{
std::cout << "This will print 3 times" << std::endl;
}
| |
The short explanation:
'i' is a counter that counts up every time the loop body is performed. Once the counter reaches the specified value (in this example: that value is 3) the loop exits. So this for loop basically says "run this body 3 times".
The detailed explanation of what's actually happening:
- The initialization step is performed:
i = 0
. This sets our counter to zero.
- The condition is checked:
i < 3
. Since i=0, the condition is true, so the loop continues.
- Loop body is performed (text printed)
- The iteration step is prformed:
++i
. Our loop counter 'i' is incremented. Now, i=1
- Condition is checked again. Since i=1, it is still true, so the loop continues
- Body perfomed again... text is printed a second time.
- Iteration performed again. Now i=2
- Condition checked again. i=2, which is still less than 3. So it's true. So loop continues.
- Body performed again... text is printed a 3rd time.
- Iteration performed again. Now i=3
- Condition checked again. i=3, which is NOT less than 3... so the condition is FALSE and the loop exits.