The for loop
Three expressions, any of which may be empty.
for (int i = 0; i < n; i++) {
// body
}
Three parts, separated by semicolons:
- Initialisation — runs once, before anything else. Usually declares the counter.
- Condition — tested before every pass. While true, the body runs.
- Update — runs after every pass, before the condition is tested again.
The counter declared in part one exists only inside the loop, which is the main reason to declare it there rather than outside.
Counting correctly
The idiom for “n times” is:
for (int i = 0; i < n; i++)
Start at zero, stop before n. That gives exactly n passes and matches array indexing, where valid indices are 0 to length - 1.
The classic error is <=:
for (int i = 0; i <= values.length; i++) // one pass too many
which throws ArrayIndexOutOfBoundsException on the last iteration. If you find yourself writing <=, check twice.
Counting down
for (int i = n - 1; i >= 0; i--)
Needed when you remove elements as you go, since removing shifts everything after the current position and a forward loop then skips items.
Other steps
The update does not have to be ++:
for (int i = 0; i < n; i += 2) // every other element
for (int i = 1; i < n; i *= 2) // 1, 2, 4, 8 …
Empty parts
All three parts are optional. for (;;) is an infinite loop, equivalent to while (true). It needs a break somewhere, and if the exit condition is simple, while usually reads better.
Several variables
The comma lets you run two counters:
for (int i = 0, j = n - 1; i < j; i++, j--)
That is the standard shape for reversing an array or checking a palindrome. Both must be the same type, because it is one declaration.
Which loop to use
| Situation | Loop |
|---|---|
| Every element, index not needed | for-each |
| Need the index | for |
| Need to write back into an array | for |
| Condition not about counting | while |
| Body must run at least once | do…while |