Lesson 2.8: for Loops

Unit 2 · Lesson 2.8 · Code Mechanics

Lesson 2.8: for Loops

🕑 30–35 min · 8 Practice Questions · 4 Mastery Questions · Output Predictor + Bug Hunt + Count

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 < n gives n iterations (0 to n-1); i <= n gives n+1 iterations.
Tier 2 · AP Practice

Practice Questions

MCQ 1
How many times does the loop body execute?

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
A 4
B 5
C 6
D Infinite
B. i goes 0,1,2,3,4. At i=5: 5<5 is false. Body runs 5 times.
MCQ 2
What is the value of sum after this loop?

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i * i;
}
A 15
B 25
C 55
D 35
C. sum = 1+4+9+16+25 = 55. Each iteration adds i²: 1,4,9,16,25.
MCQ 3
What is printed?

for (int i = 10; i >= 1; i -= 3) {
    System.out.print(i + " ");
}
A 10 7 4 1
B 10 7 4
C 10 8 6 4 2
D 9 6 3
A. i goes 10,7,4,1. All satisfy i>=1. Next: i=1-3=-2, -2>=1 is false. Output: 10 7 4 1.
MCQ 4
Which while loop is equivalent to the for loop?

for (int k = 2; k <= 10; k += 2) {
    System.out.println(k);
}
Predict the answer before reading the options.
A
int k = 2;
while (k < 10) {
    System.out.println(k);
    k += 2;
}
B
int k = 2;
while (k <= 10) {
    System.out.println(k);
    k += 2;
}
C
int k = 0;
while (k <= 10) {
    System.out.println(k);
    k += 2;
}
D
int k = 2;
while (k <= 10) {
    k += 2;
    System.out.println(k);
}
B. Equivalent while: same init (k=2), same condition (k<=10), same update (k+=2), update after body. A uses k<10 (misses 10). C starts at 0. D updates before printing (wrong values).
MCQ 5
A student writes this to count from 1 to 5, but gets wrong output. What is actually printed?

for (int i = 1; i <= 5; i++) {
    System.out.print(i + " ");
    i++;
}
Predict the answer before reading the options.
A 1 2 3 4 5
B 1 3 5
C 2 4
D 1 2 3 4
B. i increments twice per iteration: once in body (i++), once in header (i++). So i goes 1→2→2 then check: 2<=5 true, print 3, i becomes 3→4, check: 4<=5 true, print 5, i becomes 5→6, check: 6<=5 false. Output: 1 3 5.
MCQ 6
How many times does the body of the inner loop execute in total?

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        System.out.println(i + j);
    }
}
A 7
B 12
C 9
D 16
B. Outer runs 3 times, inner runs 4 times per outer iteration. Total: 3 × 4 = 12.
MCQ 7
What does result contain after this loop?

String result = "";
for (int i = 0; i < 5; i++) {
    result += i;
}
A "01234"
B "1234"
C 10
D "0123456789"
A. String concatenation with int: result becomes "0", "01", "012", "0123", "01234". The int i is converted to its string representation before concatenation.
MCQ 8
Which loop executes its body the MOST times?
Predict the answer before reading the options.
A
for (int i = 0; i < 10; i++)
B
for (int i = 1; i <= 10; i++)
C
for (int i = 0; i <= 10; i++)
D
for (int i = 10; i > 0; i--)
C. i goes 0,1,...,10 — that is 11 iterations. A and B both run 10 times. D runs 10 times (10,9,...,1). Only C includes both 0 and 10.
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor — for Loops
Trace the for loop and type the exact output.
Question 1 of 3  ·  Score: 0

Done!
You got 0 of 3 correct.
Bug Hunt — for Loops
Click the line with the bug, or click 'No bug' if the code is correct.
Question 1 of 4  ·  Score: 0
No bug — code is correct
Done!
You got 0 of 4 correct.
Predict the Count — for Loops
Count how many times the loop body executes.
Question 1 of 3  ·  Score: 0

How many times does the loop body execute?

Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: for Loops

MCQ 1
What does this method return for n = 5?

public static int mystery(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}
A 5
B 10
C 120
D 25
C. result starts at 1, multiplies by 2,3,4,5. Result = 1×2×3×4×5 = 120. This is n!.
MCQ 2
A for loop runs from i=1 to i<=n. If n=100, the body executes 100 times. If n doubles to 200, how many times does the body execute?
A 200
B 400
C 10000
D 150
A. Single loop: count = n. Doubling n doubles count. 200 times.
MCQ 3
What is the output?

int total = 0;
for (int i = 1; i <= 4; i++) {
    for (int j = i; j <= 4; j++) {
        total++;
    }
}
System.out.println(total);
Predict the answer before reading the options.
A 16
B 10
C 8
D 12
B. i=1: j runs 1,2,3,4 (4 times). i=2: j runs 2,3,4 (3 times). i=3: j runs 3,4 (2 times). i=4: j runs 4 (1 time). Total = 4+3+2+1 = 10.
MCQ 4
A for loop and its equivalent while loop always produce the same output.

Under what condition is this FALSE?
Predict the answer before reading the options.
A When the loop body contains a return statement
B When the for loop modifies the loop variable inside the body
C When n is 0
D Never — they always produce identical output
B. When the loop variable is modified inside the body of a for loop, the behavior differs from the equivalent while loop because the for header update still runs after each body execution. This can produce different variable values. (EK 2.8.A.3 — equivalence holds only when the loop variable is not modified in the body)

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.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]