< Previous | Contents | Next >
The first for loop counts from 0 to 9. The loop begins:
for (int i = 0; i < 10; ++i)
The initialization statement, int i = 0, declares i and initializes it to 0. The expression i < 10 says that the loop will continue as long as i is less than 10. Lastly, the action statement, ++i, says i is to be incremented each time the loop body finishes. As a result, the loop iterates 10 times—once for each of the values 0 through 9. And during each iteration, the loop body displays the value of i.
The next for loop counts from 9 down to 0. The loop begins:
for (int i = 9; i >= 0; --i)
Here, i is initialized to 9, and the loop continues as long as i is greater than or equal to 0. Each time the loop body finishes, i is decremented. As a result, the loop displays the values 9 through 0.
The next loop counts from 0 to 50, by fives. The loop begins:
for (int i = 0; i <= 50; i += 5)
Here, i is initialized to 0, and the loop continues as long as i is less than or equal to 50. But notice the action statement, i += 5. This statement increases i by five each time the loop body finishes. As a result, the loop displays the values 0, 5, 10, 15, and so on. The expression i <= 50 says to execute the loop body as long as i is less than or equal to 50.
You can initialize a counter variable, create a test condition, and update the counter variable with any values you want. However, the most common thing to do is to start the counter at 0 and increment it by 1 after each loop iteration.
Finally, the caveats regarding infinite loops that you learned about while studying while loops apply equally well to for loops. Make sure you create loops that can end; otherwise, you’ll have a very unhappy gamer on your hands.