Unit 2 · 18 min
2.8 for Loops
A for loop packs the setup, the test and the step of a counting loop into one header line.
Summary, objectives and course and exam description (CED) codes
A for loop is an iterative statement whose header has three parts: the initialization, the Boolean expression and the update. The initialization runs once and sets up the loop control variable; the Boolean expression is checked before every iteration; the update runs after the whole body and before the next check. Any for loop can be rewritten as an equivalent while loop, and the reverse.
By the end of this session you can
- 2.8.A Develop code to represent iterative processes using for loops and determine the result of these processes.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. The three parts of the header
A for loop is a type of iterative statement. Its header has three parts, separated by semicolons: the initialization, the Boolean expression and the update 2.8.A.1.
for (int lap = 1; lap <= 4; lap++) {
System.out.println("Lap " + lap);
}
Output:
Lap 1
Lap 2
Lap 3
Lap 4
| Part | In the example | Job |
|---|---|---|
| Initialization | int lap = 1 |
Create and set the loop control variable |
| Boolean expression | lap <= 4 |
Decide whether to run the body again |
| Update | lap++ |
Change the loop control variable after each iteration |
2. The exact order of execution
The initialization statement runs only once, before the Boolean expression is evaluated for the first time. The variable it initializes is called the loop control variable. The Boolean expression is evaluated right after the initialization and then after each update, until it is false. In each iteration, the update runs after the entire loop body and before the Boolean expression is evaluated again 2.8.A.2.
for (int i = 0; i < 3; i++) {
System.out.println("body sees i = " + i);
}
Output:
body sees i = 0
body sees i = 1
body sees i = 2
| Step | Action | i | Result |
|---|---|---|---|
| 1 | initialization | 0 | |
| 2 | check i < 3 |
0 | true |
| 3 | body | 0 | prints 0 |
| 4 | update i++ |
1 | |
| 5 | check i < 3 |
1 | true |
| 6 | body | 1 | prints 1 |
| 7 | update i++ |
2 | |
| 8 | check i < 3 |
2 | true |
| 9 | body | 2 | prints 2 |
| 10 | update i++ |
3 | |
| 11 | check i < 3 |
3 | false, loop ends |
Count from the table: the initialization ran 1 time, the Boolean expression 4 times, the body 3 times and the update 3 times.
A loop control variable declared in the header exists only inside the loop:
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
System.out.println(i);
error: cannot find symbol
3. Counting iterations and other updates
You can count iterations without tracing every step:
| Header | Values of the loop control variable | Iterations |
|---|---|---|
for (int i = 0; i < 10; i++) |
0 to 9 | 10 |
for (int i = 1; i <= 10; i++) |
1 to 10 | 10 |
for (int i = 1; i < 10; i++) |
1 to 9 | 9 |
for (int i = 0; i <= 10; i += 2) |
0, 2, 4, 6, 8, 10 | 6 |
for (int i = 10; i > 0; i--) |
10 down to 1 | 10 |
for (int i = 1; i < 100; i *= 3) |
1, 3, 9, 27, 81 | 5 |
The update does not have to be i++. This loop counts down by 5:
for (int seconds = 20; seconds >= 0; seconds -= 5) {
System.out.print(seconds + " ");
}
Output:
20 15 10 5 0
A for loop is a good fit for an accumulator, such as the sum of the even numbers from 2 to 10:
int sum = 0;
for (int n = 2; n <= 10; n += 2) {
sum += n;
}
System.out.println("Sum: " + sum);
Output:
Sum: 30
4. for and while are interchangeable
A for loop can be rewritten as an equivalent while loop, and the other way around 2.8.A.3. Move the initialization above the loop, keep the Boolean expression, and make the update the last statement of the body.
for (int day = 1; day <= 3; day++) {
System.out.println("Day " + day);
}
int day = 1;
while (day <= 3) {
System.out.println("Day " + day);
day++;
}
Both print the same three lines:
Output:
Day 1
Day 2
Day 3
One difference: in the while version, day is declared before the loop, so it still exists after the loop, with the value 4.
Going the other way, a while loop that halves a value becomes a for loop:
int steps = 0;
for (int size = 64; size > 1; size /= 2) {
steps++;
}
System.out.println(steps);
Output:
6
5. Common for loop errors
A semicolon after the header gives the loop an empty body. The empty body runs 5 times, then the block runs once:
int total = 0;
for (int i = 0; i < 5; i++); {
total++;
}
System.out.println(total);
Output:
1
Changing the loop control variable in the body as well as in the header skips values:
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
i++;
}
Output:
0 2 4 6 8
Each iteration adds 2 to i: once in the body and once in the update. Keep all changes to the loop control variable in the header.
Lock it in: memory hooks
- Header orderInit once; then check, body, update; check, body, update... until the check is false.
- Counting iterationsfor (int i = a; i < b; i++) runs b - a times. Add one more for <=.
- for to whileLift the init above the loop, keep the check, drop the update to the bottom of the body.
Common misconceptions
"The update runs before the body, at the top of each iteration."
Not quite. The update runs after the entire body, just before the Boolean expression is checked again. In the first iteration the body uses the initial value.
"The initialization runs every time the loop repeats."
Not quite. It runs exactly once, before the first Boolean expression evaluation.
"You can use the loop control variable after the loop ends."
Not quite. A variable declared in the for loop header only exists inside the loop. Using it after the loop is a compile error (cannot find symbol).
Exam traps
- for (int i = 0; i < 5; i++); with a semicolon runs an empty body 5 times, then the block below runs once.
- Off by one: for (int i = 1; i < 10; i++) runs 9 times, not 10.
- Changing the loop control variable inside the body as well as in the update skips values.
- After for (int k = 0; k < 3; k++) ends, k does not exist. If k is declared before the loop, its value after the loop is 3, the first value that failed the check.
2PracticeRecall it, then check yourself
In 30 seconds
- A for loop header has three parts, separated by semicolons: initialization; Boolean expression; update.
- The initialization runs once. The variable it sets up is the loop control variable.
- Order: initialize, check, body, update, check, body, update, ... until the check is false.
- for (int i = a; i < b; i++) runs b - a times; with <= it runs b - a + 1 times (when a <= b).
- Every for loop can be rewritten as an equivalent while loop, and every while loop as a for loop.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 6 questions
Checkpoint: for Loops
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Parts of a for loop header three parts CED 2.8.A.1
- How often each part runs in a loop with n iterations three parts CED 2.8.A.2
- initializationonce
- Boolean expressionn + 1 times
- updaten times
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
for looptap to flip
An iterative statement whose header has three parts: the initialization (runs once), the Boolean expression (checked before each iteration) and the update (after each iteration).
Example and CED codes -
Loop control variabletap to flip
The variable that controls how many times a loop runs. In a for loop it is the variable set up by the initialization in the header.
Example and CED codes -
while looptap to flip
An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.
Example and CED codes -
Off by one errortap to flip
An error in which a loop runs one time too many or one time too few, often from < versus <= or a wrong starting value.
Example and CED codes -
Infinite looptap to flip
A loop whose Boolean expression always evaluates to true, so it never stops. It compiles; it is a logic error.
Example and CED codes
Questions students ask
What are the three parts of a for loop in Java?
The initialization, which sets up the loop control variable; the Boolean expression, which is checked before each iteration; and the update, which runs after each iteration of the body.
In what order does a for loop run?
The initialization runs once. Then Java checks the Boolean expression, runs the body if it is true, runs the update, and checks again, until the Boolean expression is false.
How many times does a for loop run?
For for (int i = a; i < b; i++), b - a times. For i <= b, b - a + 1 times. Trace the first and last values when the update is not i++.
Can every for loop be written as a while loop?
Yes. Put the initialization before the while loop, use the Boolean expression as the while condition, and put the update as the last statement of the body.