How the for Loop Works
The figure below shows the for loop from the last example sketch, CountTenTimes. It labels the three elements in the for loop’s parentheses that control how it counts.
- Initialization: the starting value for counting. It’s common to declare a local variable for the job as we did here with int i = 1; naming it i for ‘index.’
- Condition: what the for loop checks between each repetition to make sure the condition is still true. If it’s true, the loop repeats again. If not, it allows the code to move on to the next statement that follows the for loop’s code block. In this case, the condition is “if i is less than or equal to 10.”
- Increment: how to change the value of i for the next time through the loop. The expression i++ is equivalent to i = i + 1. It makes a nice shorthand approach for adding 1 to a variable. Notice that ++ comes after i, meaning “use i as-is this time through the function, and then increment it afterward.” This is the post increment use of the operator.
The first time though the loop, the value of i starts at 1. So, Serial.println(i) displays the value 1 in the Serial Monitor. The next time through the loop, i++ has made the value of i increase by 1. After a delay (so you can watch the individual values appear in the Serial Monitor), the for statement checks to make sure the condition i <= 10 is still true. Since i now stores 2, it is true since 2 is less than 10, so it allows the code block to repeat again. This keeps repeating, but when i gets to 11, it does not execute the code block because it’s not true according to the i <= 10 condition.