Topic 2.8 — for Loops

Goal: write and trace for loops (including common counting patterns), and understand how they compare to while loops.

The big idea

A for loop is the go-to loop when you know how many times you want to repeat (or you’re counting through a range). It bundles the loop’s initialization, condition, and update in one line.

Structure

for (initialization; condition; update) {
  // repeat while condition is true
}
  • Initialization happens once.
  • Condition is checked before each iteration.
  • Update happens after each iteration.

Counting up (most common)

for (int i = 0; i < 5; i++) {
  sum = sum + i;
}

Runs with i = 0, 1, 2, 3, 4 (5 iterations).

Counting down

for (int i = 10; i >= 1; i--) {
  // countdown
}

Great for reverse traversals.

for vs while (when to use which?)

Use this… When…
for you’re counting / you know (or can compute) the number of iterations
while you loop until something happens (sentinel/unknown number of repeats)

Tracing order (exam favorite)

The loop follows this exact cycle:

  1. Initialization (once)
  2. Check condition
  3. Run body
  4. Run update
  5. Repeat from step 2
for (int i = 1; i <= 3; i++) {
  x++;
}
// body runs 3 times

Common mistakes

  • Off-by-one errors: < vs <= changes the number of iterations.
  • Wrong update direction: using i++ when counting down (infinite loop risk).
  • Changing the loop variable in the body accidentally.
// Risky: i changes twice per loop
for (int i = 0; i < 10; i++) {
  i++; // extra change
}

Exam mindset

  • Identify start value, end condition, and step.
  • List the exact sequence of i values the loop will take.
  • Watch for off-by-one errors.
  • Remember: update happens after the body.

Quick self-check

  1. How many times does this run? for(int i=0;i<4;i++)
  2. What are the values of i for for(int i=2;i<=6;i+=2)?
  3. What happens if your update never changes the condition?
  4. When is a for loop usually better than a while loop?
  5. Where does the update run: before or after the loop body?

← Back to Unit 2 topics