Lesson 2.8: for Loops
Lesson 2.8: for Loops
What You'll Learn
- 2.8.A: Develop code using for loops and determine results.
- Identify the three parts of the for loop header: init, condition, update. (EK 2.8.A.1)
- Trace for loop execution, including exact order of header part evaluation. (EK 2.8.A.2)
- Convert between for loops and equivalent while loops. (EK 2.8.A.3)
- Identify off-by-one errors in for loop bounds.
Key Vocabulary
| Term | Definition |
|---|---|
| for loop | An iteration statement with three parts in the header: initialization, boolean condition, and update. Used when the number of iterations is known in advance. (EK 2.8.A.1) |
| initialization | The first part of the for header. Executes exactly once before the first condition check. Typically declares and sets the loop control variable. (EK 2.8.A.2) |
| loop control variable | The variable declared in the initialization. Controls how many times the loop runs. Its scope is limited to the for loop by convention. |
| boolean expression | The second part of the for header. Evaluated before each iteration. When false, the loop terminates. |
| update statement | The third part of the for header. Executes after the entire loop body, before the condition is re-evaluated. (EK 2.8.A.2) |
| for-while equivalence | Every for loop can be rewritten as an equivalent while loop and vice versa, using the same initialization, condition, and update. (EK 2.8.A.3) |
The for Loop (EK 2.8.A.1)
A for loop packages all three loop-control elements into a single header, making it the preferred choice when the number of iterations is known before the loop begins. The CED defines three mandatory parts: initialization, boolean expression, and update.
CED Connection (EK 2.8.A.1 & 2.8.A.2)
"There are three parts in a for loop header: the initialization, the Boolean expression, and the update." and "The initialization statement is only executed once before the first Boolean expression evaluation... In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again."
Syntax
for (initialization; booleanExpression; update) {
// body: executes each time condition is true
}
// execution continues here when condition becomes false
// Most common form:
for (int i = 0; i < n; i++) {
// executes n times, i goes 0, 1, 2, ..., n-1
}
Execution order — every iteration
| Step | What happens & when |
|---|---|
| 1. Initialization | Runs once before anything else. Declares and sets loop control variable. |
| 2. Evaluate condition | Runs before each iteration. If false, loop ends. |
| 3. Execute body | Runs when condition is true. All statements top to bottom. |
| 4. Execute update | Runs after body, before re-evaluating condition. Typically increments/decrements. |
| 5. Go to step 2 | Repeat until condition is false. |
Worked Example — Full Trace (sum 1 to 5)
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println(sum); // 15
// Trace:
// i=1: sum=1 | i=2: sum=3 | i=3: sum=6 | i=4: sum=10 | i=5: sum=15
// i=6: 6<=5 false → loop ends, sum=15
Worked Example — Counting Down
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1
// i starts at 10, decrements each iteration, stops when i < 1
Worked Example — Step by 2
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " ");
}
// Output: 0 2 4 6 8 10
// Update of i+=2 means only even values
for-while Equivalence (EK 2.8.A.3)
Every for loop can be mechanically rewritten as an equivalent while loop by moving the initialization before the loop, keeping the condition, and moving the update to the end of the body. The AP exam tests this equivalence directly.
Worked Example — for Converted to while
// for loop version
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Exact equivalent while loop
int i = 0; // initialization moved before loop
while (i < 5) { // same condition
System.out.println(i);
i++; // update moved to end of body
}
Both produce identical output: 0 1 2 3 4. The key difference is that in the for loop, i is scoped to the loop; in the while version, i is accessible after the loop ends.
Choosing while vs. for
Use for when |
Use while when |
|---|---|
| Number of iterations known in advance | Number of iterations depends on runtime conditions |
| Counting over a range (0 to n) | Waiting for a sentinel value or user input |
| Iterating over String indices | Repeating until a file ends or network disconnects |
| Standard accumulator/counter pattern | Game loops, server loops, retry logic |
AP Trap: Update Runs After Body, Not Before
The update in the for header runs after the body, not before. So if i starts at 0 and the body uses i, the first iteration uses i=0, not i=1. This matters for counting questions.
AP Trap: Modifying the Loop Variable Inside the Body
for (int i = 0; i < 5; i++) {
System.out.println(i);
i++; // BAD: modifies i again, prints only 0 2 4 (not 0 1 2 3 4)
}
The loop variable is updated twice per iteration: once in the body, once in the header update. This produces unexpected output and is a common spot-the-error question on the AP exam.
AP Trap: Off-By-One with 0-Based Indexing
To iterate n times starting at 0: use i < n, not i <= n. With i <= n you get n+1 iterations. This is the most common for-loop off-by-one error on the AP exam. Pattern to memorize: for (int i = 0; i < n; i++) gives exactly n iterations with i values 0 through n-1.
Real-World Connection
For loops appear wherever a program processes a fixed-size collection: checking every character in a String, scanning every pixel in an image row, computing each month in a 12-month interest calculation, rendering each frame in a 60fps animation. The pattern is always the same — initialize a counter, check a bound, process, increment. Mastering the for loop unlocks all of Unit 4 (arrays and ArrayLists), where traversal is the foundational skill.
Summary
- Three parts: initialization (once), boolean expression (before each iteration), update (after each body execution). (EK 2.8.A.1, 2.8.A.2)
- Initialization runs exactly once before the first condition check.
- Update runs after the body, before the condition is re-evaluated.
- for ⇔ while: any for loop can be rewritten as a while loop and vice versa. (EK 2.8.A.3)
- Use for when iteration count is known; use while when it depends on runtime conditions.
-
Off-by-one:
i < ngives n iterations (0 to n-1);i <= ngives n+1 iterations.
Practice Questions
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
sum after this loop?int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i * i;
}
for (int i = 10; i >= 1; i -= 3) {
System.out.print(i + " ");
}
10 7 4 1
10 7 4
10 8 6 4 2
9 6 3
10 7 4 1.for (int k = 2; k <= 10; k += 2) {
System.out.println(k);
}
int k = 2;
while (k < 10) {
System.out.println(k);
k += 2;
}
int k = 2;
while (k <= 10) {
System.out.println(k);
k += 2;
}
int k = 0;
while (k <= 10) {
System.out.println(k);
k += 2;
}
int k = 2;
while (k <= 10) {
k += 2;
System.out.println(k);
}
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
i++;
}
1 2 3 4 5
1 3 5
2 4
1 2 3 4
1 3 5.for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.println(i + j);
}
}
result contain after this loop?String result = "";
for (int i = 0; i < 5; i++) {
result += i;
}
"01234"
"1234"
10
"0123456789"
for (int i = 0; i < 10; i++)
for (int i = 1; i <= 10; i++)
for (int i = 0; i <= 10; i++)
for (int i = 10; i > 0; i--)
How many times does the loop body execute?
Mastery: for Loops
n = 5?public static int mystery(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int total = 0;
for (int i = 1; i <= 4; i++) {
for (int j = i; j <= 4; j++) {
total++;
}
}
System.out.println(total);
Under what condition is this FALSE?
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]