for Loops
The for loop's three-part header, the exact order in which the initialization, Boolean expression, body, and update run, how to count passes, and how every for loop corresponds to an equivalent while loop.
A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update. The initialization runs only once, before the first evaluation of the Boolean expression; the variable it creates is the loop control variable. The Boolean expression is evaluated immediately after the initialization and then after each update, until it is false, and each update runs after the entire loop body. A for loop can be rewritten into an equivalent while loop, and vice versa.
1The for Loop Header
Counting loops are so common that Java gives them a compact form. In for (int i = 1; i <= 5; i++), the header holds the three parts of a counting loop, separated by semicolons. int i = 1 is the initialization, i <= 5 is the Boolean expression, and i++ is the update. The body in braces follows the header, exactly as in a while loop.
The variable created in the initialization is the loop control variable. By convention it is often named i, j, or k when it simply counts, but a descriptive name such as day or row is clearer when the value means something. Gathering the start, stopping test, and step into one line makes a loop's range visible at a glance.
The update is usually written with the increment or decrement operator, i++ or i--, or with a compound assignment such as i += 2. Each of these is a complete statement that changes the loop control variable by a fixed amount. The update does not end with a semicolon, because the closing parenthesis of the header ends it.
for loop header: the initialization, the Boolean expression, and the update.| Part of the header | Example | When it runs |
|---|---|---|
| Initialization | int i = 1 | Once, before the first evaluation of the Boolean expression |
| Boolean expression | i <= 5 | Immediately after the initialization, then after each update, until false |
| Update | i++ | After the entire loop body, before the expression is evaluated again |
Counting From 1 to 5
Predict the output.
for (int i = 1; i <= 5; i++)
{
System.out.println("pass " + i);
}
System.out.println("done");
pass 1
pass 2
pass 3
pass 4
pass 5
done
- 1Initialization.
int i = 1runs once. - 2Check, body, update.
1 <= 5istrue, the body prints "pass 1", theni++makesi2, and the check repeats. - 3The end. After the body prints "pass 5", the update makes
i6, the check6 <= 5isfalse, and the loop ends.
The three parts of a for header are separated by semicolons: for (int i = 0; i < 5; i++). Writing for (int i = 0, i < 5, i++) does not compile. There is no semicolon after the update.
2The Order of Execution
A for loop runs its parts in a fixed order. In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the update, until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
So the sequence is: initialize; check; body; update; check; body; update; … ; check (false). As with a while loop, the body may run zero times if the first check is false, and there is always one more check than there are passes. Because the update comes after the body, the body sees the loop control variable's value before each update.
| Event | i | Check | Output |
|---|---|---|---|
| initialization | 1 | ||
| check | 1 | 1 <= 5 true | |
| body | 1 | pass 1 | |
| update | 2 | ||
| check | 2 | 2 <= 5 true | |
| … | … | … | … |
| update | 6 | ||
| check | 6 | 6 <= 5 false | loop ends |
Changing the Control Variable Inside the Body
This loop also changes i in its body, which is confusing style but shows exactly when the update runs. Predict the output.
for (int i = 0; i < 10; i++)
{
System.out.println(i);
i = i + 2;
}
0
3
6
9
- 1Pass 1. Prints 0; the body adds 2 (i = 2); then the update adds 1 (i = 3).
- 2Pass 2. Prints 3; i becomes 5, then 6.
- 3Passes 3 and 4. Print 6 and 9; after pass 4, i becomes 11, then 12, and
12 < 10isfalse.
On the first pass, the body sees the initial value: in for (int i = 1; ...; i++), the first value used in the body is 1, not 2. The update runs only after the body finishes.
3Steps and Ranges
The header controls the sequence of values the loop control variable takes. Changing the initialization moves the start, changing the Boolean expression moves the end, and changing the update changes the step. Loops can count up by 1 with i++, down with i--, by larger steps with i += 3 or i -= 2, or even multiply with i *= 3.
Whatever the step, the Boolean expression must eventually become false. A loop that counts down needs a condition such as i >= 0, not i <= 10, which would always be true while i decreases. Matching the direction of the update to the direction of the condition is the key to ending the loop.
Counting Down by Twos
Predict the output.
for (int i = 10; i >= 0; i -= 2)
{
System.out.println(i);
}
10
8
6
4
2
0
- 1Start at 10, and continue while
i >= 0. - 2The update
i -= 2subtracts 2 after each pass: 10, 8, 6, 4, 2, 0. - 3Stopping. After printing 0,
ibecomes −2 and-2 >= 0isfalse.
Multiplying 1 Through 5
Compute 5! = 1 × 2 × 3 × 4 × 5.
int product = 1;
for (int k = 1; k <= 5; k++)
{
product = product * k;
}
System.out.println(product);
120
- 1Start the product at 1, the multiplicative identity, before the loop.
- 2Each pass multiplies by the current
k: 1, 2, 6, 24, 120.
for loop is ideal for accumulating over a known range of values.4Counting Passes
The most reliable way to find the number of passes is to list the values of the loop control variable that pass the check. For for (int i = 3; i < 12; i += 3), the values 3, 6, and 9 pass and 12 fails, so the body runs 3 times. For a step of 1 from a to b inclusive, the count is b - a + 1; with a strict < it is b - a.
Off by one errors in for loops come from the same sources as in while loops: the starting value and the boundary of the Boolean expression. for (int i = 0; i < 5; i++) and for (int i = 1; i <= 5; i++) both run 5 times, but with different values of i; choose the one whose values the body actually needs.
When a loop is meant to run exactly n times and the values themselves do not matter, the conventional header is for (int i = 0; i < n; i++). Starting at 0 with a strict < makes the count equal to n with no arithmetic, and this pattern will appear constantly once loops are used to visit positions in strings and arrays, whose indices also start at 0.
How Many Times Does It Run?
How many times does each loop body run?
int a = 0;
for (int i = 3; i < 12; i += 3)
{
a++;
}
int b = 0;
for (int i = 1; i < 100; i *= 3)
{
b++;
}
int c = 0;
for (int i = 5; i < 5; i++)
{
c++;
}
System.out.println(a + " " + b + " " + c);
3 5 0
- 1First loop.
itakes 3, 6, 9; at 12 the check fails: 3 passes. - 2Second loop.
itakes 1, 3, 9, 27, 81; 243 fails: 5 passes. - 3Third loop.
5 < 5isfalseimmediately: 0 passes.
for (int i = 10; i <= 20; i--) starts at 10 and moves down, so i <= 20 is always true and the loop never ends. A decreasing update needs a lower-bound test such as i >= 0.
5for and while: Equivalent Forms
A for loop can be rewritten into an equivalent while loop, and vice versa. To turn a for loop into a while loop, move the initialization before the loop, use the Boolean expression as the while condition, and place the update as the last statement of the body. Reversing those steps turns a counting while loop into a for loop.
The two forms behave identically, so the choice is about clarity. A for loop suits a known count or range, because the header shows the whole range at once. A while loop suits repetition until a condition changes, when there is no natural counter, such as repeating until a balance reaches a target.
for loop can be rewritten into an equivalent while loop, and vice versa.| for loop | Equivalent while loop |
|---|---|
for (int i = 0; i < n; i++) { body } | int i = 0; while (i < n) { body i++; } |
for (int k = 10; k > 0; k -= 3) { body } | int k = 10; while (k > 0) { body k -= 3; } |
| When to prefer it: a known count or range | When to prefer it: repeat until a condition changes |
The Same Loop as while
Rewrite for (int i = 2; i <= 8; i += 3) { System.out.println(i); } as a while loop and confirm the output is the same.
for (int i = 2; i <= 8; i += 3)
{
System.out.println(i);
}
2
5
8
int i = 2;
while (i <= 8)
{
System.out.println(i);
i += 3;
}
2
5
8
- 1Initialization moves before the loop:
int i = 2;. - 2The Boolean expression becomes the
whilecondition. - 3The update becomes the last statement of the body, so it still runs after the rest of the body.
for loop can be rewritten into an equivalent while loop, and vice versa, by moving the three parts of the header.6The Loop Control Variable
A loop control variable declared in the header, as in for (int i = 0; ...), exists only within the loop. Using it after the loop does not compile. If the final value is needed afterward, declare the variable before the loop and leave the type out of the initialization: int i; for (i = 0; i < 3; i++).
Changing the loop control variable inside the body is legal but makes the number of passes hard to predict, because the body's change and the header's update both apply. Keep all changes to the control variable in the header so that the header alone describes the loop's range; this is the main reason for loops are easy to read.
Using i After the Loop
Explain the compile error.
for (int i = 0; i < 3; i++)
{
System.out.println(i);
}
System.out.println("last: " + i);
- 1Declared in the header.
iis declared in the initialization, so it belongs to the loop. - 2After the loop the name
irefers to nothing. - 3Fix. If the final value is needed, declare
int i;before the loop and writefor (i = 0; i < 3; i++).
for header can be used only inside the loop.A variable declared in a for header is not available after the loop. If code after the loop needs the final count, declare the variable before the loop instead.
Four Habits for for Loops
1. Init, Check, Body, Update
Initialization once; update after the whole body.
2. List the Values
Count passes by listing values that pass the check.
3. Match Direction
Decreasing updates need lower-bound conditions.
4. Header Owns the Variable
Change it only in the update; it ends with the loop.
A for loop is a type of iterative statement with three parts in its header: the initialization, the Boolean expression, and the update. The initialization statement is only executed once before the first Boolean expression evaluation, and the variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the update statement until it is false; in each iteration, the update is executed after the entire loop body and before the Boolean expression is evaluated again. A for loop can be rewritten into an equivalent while loop, and vice versa.