APrep Open the app

AP Computer Science A · Unit 2: Selection & Iteration

2.9 For Loops

Anatomy of a for loop

A for loop packs initialization, condition, and update into one line: `for (int i = 0; i < n; i++) { ... }`. The initialization runs once, the boolean condition is checked before each iteration, and the update runs after each loop body execution. It's ideal when you know how many times to repeat.

Execution order matters

Order of operations: init → check condition → run body → update → check condition again → repeat. If the condition is false initially, the body never executes. The loop variable is typically scoped only inside the loop, so it can't be used after it ends unless declared outside.

Common patterns

For loops often traverse arrays using indices: `for (int i = 0; i < arr.length; i++)`. Counting up uses `i++`; counting down uses `i--` with a decreasing condition like `i >= 0`. Off-by-one errors are common — double-check whether the condition should use `<` or `<=`.

Key terms

For loop syntax
for (initialization; condition; update) { body } — combines setup, test, and increment in one header.
Order of for loop execution
Initialization once → check condition → run body → update → check condition again → repeat until false.
When to use a for loop
When the number of iterations is known or countable in advance, such as traversing an array by index.
Off-by-one error
A bug caused by an incorrect boundary condition (e.g., using <= instead of <), causing one extra or missing iteration.
Loop variable scope
A variable declared in the for loop's initialization (e.g., int i) is typically only accessible inside the loop's body.

Try an AP-style question

Code

for (int i = 0; i < 10; i += 3)
    System.out.print(i + " ");

What is printed?

  1. 0 3 6 9 12
  2. 3 6 9
  3. 0 3 6
  4. 0 3 6 9
Show the answer

D. Stops when i reaches 12.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 2.9 free in APrep