Summary of for loops
The general structure of a for statement is the following:
for ( <initialization>; <condition>; <update>) {
<code to repeat>
}
- The initialization part is executed only once, when we first
reach the for loop.
- The condition is executed before each iteration, including the first
one.
- The update part is executed after each iteration, before
testing the condition.
When should you use a for loop instead of a while loop:
- Definitely use for loops when counting!
- Initialization, condition, update all are expressed in terms
of the same variable
- The variable is not modified elsewhere in the loop.
- It is correct to do the update command as the last statement
in the body of the loop.
Look over section on common loop errors!