TOPIC 2.8 · STUDY
for Loops
A for header has three parts: initialization once, a Boolean expression tested before each body execution, and an update that runs after the body. The loop control variable declared in the header exists for the loop. A for loop can be rewritten as an equivalent while.
2.8.A
for loops
A for loop packs three jobs into its header. Initialization runs once before anything else. A Boolean expression is tested before each body execution; if it is false, the loop ends. An update runs after the body and before the next Boolean test.
Write the three parts in that order inside the parentheses: for (initialization; Boolean; update). The braces hold the body that runs when the Boolean is true. The Boolean is checked before the first body trip, so a false start means the body never runs.
int sum = 0;
for (int n = 2; n <= 5; n++) {
sum += n;
}
System.out.print(sum);
Initialization sets n to 2 once. The body adds 2, then 3, then 4, then 5, so sum becomes 14. After each add, the update n++ runs, then the Boolean n <= 5 is tested again. When n becomes 6, the test fails and the loop stops.
Init runs once. Each true test leads to the body, then the update, then another test. The update is not part of the first check.
When the loop control variable is declared in the for header, it exists for that loop only. Code after the closing brace cannot use that name. If you declare the variable before the for and only assign it in the header, it remains available after the loop, including whatever value the last update left behind.
for (int k = 0; k < 3; k++) {
System.out.print(k);
}
// k is not in scope here
int m;
for (m = 4; m <= 6; m++) {
System.out.print(m);
}
System.out.print(":" + m);
The first loop prints 012. The second prints 456:7 because m was declared outside: after printing 6, the update stores 7, the test fails, and m is still visible.
Any for loop can be rewritten as an equivalent while. Move the initialization before the while, keep the same Boolean in the while condition, put the for body inside, and place the update at the end of the while body so it still runs after the work and before the next test.
for (int t = 1; t <= 4; t++) {
System.out.print(t);
}
int t = 1;
while (t <= 4) {
System.out.print(t);
t++;
}
Both fragments print 1234. Putting t++ before the print, or changing <= to <, would break the match. Nested loops are a separate skill covered later; here the focus is one for header and its while twin.
Key points
- A for header has init once, a Boolean tested before each body, and an update after the body.
- for (int n = 2; n <= 5; n++) runs the body for 2, 3, 4, and 5.
- A variable declared in the for header is not in scope after the loop.
- A matching while puts init before the loop and the update after the body.
- The update never runs before the first Boolean test.
The update runs after the body, not before the first test. Initialization happens once up front; then the Boolean decides whether the body runs at all.