AP CSA Lesson 2.9: For Loops

AP CSA • Unit 2: Selection and Iteration • Lesson 2.9

For Loops: Counter-Controlled Iteration

When you know how many times to repeat, one header holds the start, the stop, and the step. Master the for loop and the counting never drifts.

Design Code Develop Code Analyze Code Document Code Use Computers Responsibly
Loading the interactive lesson. If this note stays visible, this preview is blocking JavaScript. Download the file and open it in a browser (Chrome), or view it on the live page, to use the editor, game, and quiz.
Learn
Practice
Assess
Scenario

The problem this code solves

A ticket kiosk prints boarding passes numbered 1 through N, a countdown timer ticks from 10 down to 0, and a scoreboard totals points across a fixed number of rounds. Each is the same idea: repeat an action a known number of times. That is exactly what a for loop is built for. When the count is known up front, the for loop puts the start, the stop, and the step in one place so the counting cannot drift.

Skill focus: today you Design the loop (choose start, stop, and step), Develop it (write the header and body), and Analyze it (predict how many times it runs).
Learn

For loops: counting made into one line

A for loop packs the three parts of counting into one header: where to start, when to stop, and how to step. Read it left to right, then watch it run: initialize once, then test, body, update, test, body, update, until the test fails.

The anatomy of a for loop

for (int i = 0; i < 3; i++) {
    System.out.println(i);
}
Each pass
i i < 3? prints
0 true 0
1 true 1
2 true 2
3 false stop

The update i++ runs after the body each pass, and then the condition is retested. When the condition is false the loop ends and the counter is discarded.

The four steps, in order

  • 1. Initialize once: int i = 0
  • 2. Test the condition; if it is false, stop
  • 3. Body runs
  • 4. Update (i++), then back to step 2

A for loop is a while loop in disguise

// for: the count lives in the header
for (int i = 0; i < n; i++) {
    total += i;
}

// exactly the same work
int i = 0;
while (i < n) {
    total += i;
    i++;
}
When to use which
for you know the count
while you loop until a condition

Three counting patterns

  • Count up: for (int i = 0; i < n; i++)
  • Count down: for (int i = n; i > 0; i--)
  • Step by k: for (int i = 0; i < n; i += 2)
Watch out, off-by-one: i <= n runs one more time than i < n. When you traverse a 0-indexed array of length n, the last valid index is n - 1, so the condition is i < n, never i <= n.
Watch out, the stray semicolon: for (int i = 0; i < 5; i++); ends the loop with an empty body. Whatever you meant as the body then runs exactly once, after the loop finishes. A for header never ends with a semicolon.
Watch out, do not touch the counter: changing i inside the body (on top of the update clause) causes skipped values or an infinite loop. Let the header own the counter.

Vocabulary

Term Meaning
Loop control variable The counter the loop initializes, tests, and updates (often named i).
Initialization The one-time setup of the control variable, the first part of the header.
Condition The boolean test checked before each pass; when it is false, the loop ends.
Update The step applied after each body run, usually i++ or i += k.
Iteration One pass through the loop body.
Off-by-one error A loop that runs one too many or too few times, usually from <= vs <.

Predict first, then check

1. How many times does the body run? for (int i = 0; i < 5; i++)
2. What is the last value of i that the body sees? for (int i = 2; i <= 8; i += 2)
3. How many iterations? for (int i = 10; i > 0; i -= 3) (i = 10, 7, 4, 1)
See it run

See the loop run

This is the accumulator from Problem 1, traced. Each pass adds i to sum. When i reaches 6, the condition i <= 5 is false and the loop stops. Press Play to watch it build.

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
sum0
i i <= 5 ? body sum
1 true sum += 1 1
2 true sum += 2 3
3 true sum += 3 6
4 true sum += 4 10
5 true sum += 5 15
6 false stop 15
Original interactive trace. i climbs, the condition is checked each pass, and sum accumulates to 15.
Practice • write and run real Java

Live code editor

Eight problems, six scaffolded and two open-ended. Write Java, press Run to execute it, and Check to test against the expected output. Hints and the solution are here if you need them, but using them is tracked, so try first.

Practice • fluency

For Loop Arcade

Six quick rounds. Read the loop, then type the value it produces or the number of times the body runs. This builds the trace-in-your-head speed the timed exam rewards.

Assess • six questions at AP difficulty

Multiple choice

Predict your answer before reading the options. Watch for the qualifier words. After you answer, the rationale explains every distractor.

Assess • free-response connection

FRQ 1 connection: Methods and Control Structures

FRQ 1 always asks you to implement a method with a loop and a conditional. Here it is in miniature: a for loop over an array with an if inside. Write it, run it, and check it.

Every student challenged

Choose your lane

Support

  • Reread the Code and Memory panels
  • Editor problems 1 to 3 with hints on
  • Retry the quiz until 80%
  • Use the FRQ method shell

Core

  • All 8 editor problems
  • Full game run
  • The 6-question quiz once
  • The FRQ connection

Challenge

  • Open-ended problems 7 and 8 with no hints
  • Rewrite one loop a different way
  • Extend the FRQ
  • Lead a class trace
This lesson reports to the gradebook: lesson (completion), exercise-1 (code editor), exercise-2 (game), quiz (MCQ), and exercise-3 (FRQ). Live usage is tracked in window.LESSON_USAGE.

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]