CSPIQ · AP Computer Science Principles · Lesson 11 of 25
CSPIQ · AP Computer Science Principles

Lesson 11: Iteration

Big Idea 3 (AAP) · Phase 3

Objectives

Warm-Up

How many times does each loop display "hi"?

Loop 1:                    Loop 2:
REPEAT 4 TIMES             i ← 1
{                          REPEAT UNTIL (i > 4)
    DISPLAY ("hi")         {
}                              DISPLAY ("hi")
                               i ← i + 1
                           }

Loop 1: four times — the count is right there. Loop 2: trace i = 1, 2, 3, 4 → each time i > 4 is false so the body runs; when i becomes 5, 5 > 4 is true → stop. Also four times.

Same behavior, opposite mindsets: REPEAT n TIMES counts down a quota; REPEAT UNTIL runs while the condition is FALSE and stops when it turns TRUE. That word — until — reads like "while" to rushed students, and the exam knows it.


Core Concept

REPEAT n TIMES: the quota loop

REPEAT n TIMES
{
    <body>
}

Runs the body exactly n times. No loop variable is provided automatically — if you need a counter, you maintain it yourself:

sum ← 0
count ← 1
REPEAT 3 TIMES
{
    sum ← sum + count
    count ← count + 1
}
Iteration count (entering) sum after count after
1 1 1 2
2 2 3 3
3 3 6 4

Final: sum = 6, count = 4. Notice count ends at 4, not 3 — it increments after the last use. "What is count after the loop?" is a beloved off-by-one question.

REPEAT UNTIL: the condition loop

REPEAT UNTIL (condition)
{
    <body>
}

Rules that decide exam points:

  1. The condition is checked before each iteration. Body runs only when the condition is false.
  2. The loop stops when the condition becomes true.
  3. If the condition is true at the start, the body runs zero times.
  4. If the condition never becomes true, the loop runs forever — an infinite loop.

REPEAT UNTIL is a stopping condition, the opposite polarity from most languages' while (which runs while true). Translating in your head from Python? Flip the condition: Python's while i <= 4 is pseudocode's REPEAT UNTIL (i > 4).

Infinite-loop detectors: does the body change anything the condition tests? If not — infinite. Does it change it in the right direction? REPEAT UNTIL (x < 0) with x ← x + 1 inside — x grows away from stopping — infinite. The exam asks "which loop fails to terminate" in exactly these costumes.

FOR EACH: the list loop

FOR EACH score IN scores
{
    <body uses score>
}

The variable takes each list element in order, once each; the body runs LENGTH(scores) times. No indexes needed — score is the current element. Modifying score inside the body does not change the list; it's a copy (Lesson 7's rule wearing a loop costume).

The accumulator pattern, now complete:

total ← 0
FOR EACH price IN cart
{
    total ← total + price
}

After the loop, total holds the sum. Swap the body line to count matches (IF (price > 20) { count ← count + 1 }), find a max, build a string — one skeleton, many algorithms (Lesson 12 catalogs them).

Loops + everything: the integration zone

Real exam items combine loops with Lessons 7–10. The technique never changes: trace table, one row per iteration.

L ← [3, 8, 5]
x ← 0
FOR EACH n IN L
{
    IF (n MOD 2 = 1)
    {
        x ← x + n
    }
}
DISPLAY (x)
n n MOD 2 = 1? x
3 T 3
8 F 3
5 T 8

Displays 8 (sum of the odd values). Three rows, zero doubt.

And the robot, upgraded — this is the wall-follower from Lesson 10 with a loop around it:

REPEAT UNTIL (GoalReached())
{
    IF (CAN_MOVE(forward))
    {
        MOVE_FORWARD()
    }
    ELSE
    {
        ROTATE_LEFT()
    }
}

Behavior rule: "walk forward; at a wall, turn left; repeat until at goal." Apply the rule square by square on the diagram, updating the facing arrow each rotation. Robot-loop questions are long but mechanical — every point is earned with patience, none with brilliance.


Worked Examples

Example 1 (easy): Count the iterations

Problem: How many times does the body run?

i ← 10
REPEAT UNTIL (i < 3)
{
    i ← i − 2
}

Solution: Check-then-run, tracking i: 10 (run, →8), 8 (run, →6), 6 (run, →4), 4 (run, →2), then check: 2 < 3 true → stop. Body ran 4 times.

Interpretation: Count runs, not values seen. Final i = 2 — also a likely question.

Example 2 (medium): The zero-iterations trap

Problem: What is displayed?

count ← 0
x ← 5
REPEAT UNTIL (x ≥ 5)
{
    count ← count + 1
    x ← x + 1
}
DISPLAY (count)

Solution: First check: 5 ≥ 5 true → loop exits immediately. Body never runs. Displays 0.

Interpretation: REPEAT UNTIL checks before the first iteration. When the stopping condition starts true, the answer is zero — and "1" will be sitting right there among the choices.

Example 3 (medium): FOR EACH accumulator

Problem: What does this display?

words ← ["go", "stop", "wait"]
result ← ""
FOR EACH w IN words
{
    result ← w + result
}
DISPLAY (result)

Strategy: Careful — w + result puts the new word in front.

Solution:

w result after
"go" "go"
"stop" "stopgo"
"wait" "waitstopgo"

Displays "waitstopgo" — the list reversed by prepending.

Interpretation: result ← result + w builds "gostopwait" (order preserved); flipping the operands reverses. Concatenation order inside loops is a repeat exam offender.

Example 4 (AP-style): Which loop is infinite?

Problem: Which code segment does NOT terminate?

(A)

x ← 1
REPEAT UNTIL (x > 5)
{
    x ← x + 2
}

(B)

x ← 8
REPEAT UNTIL (x > 5)
{
    x ← x + 2
}

(C)

x ← 1
REPEAT UNTIL (x = 6)
{
    x ← x + 2
}

(D)

x ← 1
REPEAT UNTIL (x ≥ 6)
{
    x ← x + 2
}

Solution: Trace each. (A): 1→3→5→7; 7 > 5 → stops. (B): starts at 8; 8 > 5 already true → 0 iterations, stops instantly. (C): x takes 1, 3, 5, 7, 9... — never equals 6 (always odd) → infinite. (C). (D): 1→3→5→7; 7 ≥ 6 → stops.

Interpretation: Equality stopping conditions are fragile — if the variable steps over the target, the loop never stops. Inequalities (≥, >) are step-proof. When you see UNTIL (x = k), check the step size divides the distance.


Common Mistakes

  1. Reading UNTIL as WHILE. The body runs while the condition is false. Stop when TRUE. Flip your Python instincts.
  2. Missing the zero-iteration case. Condition true at entry → body never runs. Always evaluate the condition before iteration 1.
  3. Off-by-one on counters. A counter incremented in the body ends one step past its last used value (Example in section b: count = 4 after 3 iterations).
  4. Assuming FOR EACH provides indexes or modifies the list. The loop variable is a copy of each element; assigning to it changes nothing in the list.
  5. Equality-based stopping conditions with mismatched steps. UNTIL (x = 6) stepping by 2 from 1 → infinite. Check parity/divisibility before trusting equality stops.

Practice Problems

Question 1

How many times does this loop display "tick"?

REPEAT 6 TIMES
{
    DISPLAY ("tick")
}
Question 2

What is the value of total after this runs?

total ← 0
REPEAT 4 TIMES
{
    total ← total + 5
}
Question 3

How many times does the body run?

n ← 1
REPEAT UNTIL (n > 8)
{
    n ← n * 2
}
Question 4

What is displayed?

x ← 12
REPEAT UNTIL (x < 10)
{
    x ← x − 3
}
DISPLAY (x)
Question 5

What is displayed?

count ← 0
FOR EACH item IN [4, 9, 2, 9]
{
    IF (item = 9)
    {
        count ← count + 1
    }
}
DISPLAY (count)
Question 6
Which loop never terminates?
Question 7

What is the value of s after this runs?

s ← ""
FOR EACH c IN ["a", "b", "c"]
{
    s ← s + c + c
}
Question 8
A loop should process every element of a list L. Which header guarantees exactly LENGTH(L) iterations with no index management?
Question 9

What is displayed?

i ← 3
total ← 0
REPEAT UNTIL (i = 0)
{
    total ← total + i
    i ← i − 1
}
DISPLAY (total)
Question 10

(Select two answers.) Which changes would fix this infinite loop?

x ← 7
REPEAT UNTIL (x = 20)
{
    x ← x + 2
}
Question 11
The robot faces east on a 1×5 strip of open squares, standing on square 1:

REPEAT 3 TIMES
{
    MOVE_FORWARD()
    ROTATE_LEFT()
    ROTATE_LEFT()
    ROTATE_LEFT()
    ROTATE_LEFT()
}

Where does it end?

Question 12

After this code, what is displayed?

nums ← [6, 1, 8]
big ← nums[1]
FOR EACH n IN nums
{
    IF (n > big)
    {
        big ← n
    }
}
DISPLAY (big)

Create PT Connection

Iteration is the third required ingredient of your PT procedure (with sequencing and selection — the set is now complete). The canonical PT algorithm is exactly this lesson's accumulator:

PROCEDURE countMatches(list, target)
{
    count ← 0
    FOR EACH item IN list
    {
        IF (item = target)
        {
            count ← count + 1
        }
    }
    RETURN (count)
}

Sequencing (the ordered statements), selection (the IF), iteration (the FOR EACH) — one compact procedure satisfying the rubric's algorithm requirements, and you can explain every line, which is what the written responses actually grade.

Mini practice (WR 2(a) style): "Describe what your procedure's iteration does and what would happen if it were removed." Model: The FOR EACH loop examines every element of list exactly once, so the count reflects the entire dataset. Without the loop, the procedure could check only one hard-coded element, and the result would be wrong whenever the list holds more than that one item.


Show answer key & explanations

(g) Answer Key

1. (B). Six, per the quota. (Yes, some points are free — collect them calmly.)

2. (C). 0 + 5×4 = 20. Trace confirms: 5, 10, 15, 20.

3. (B). n: 1→2→4→8→16, checking before each run: 1,2,4,8 all fail > 8 → 4 runs; 16 passes → stop. 4 iterations. (A) forgets that 8 itself fails the strict > 8 and earns one more run.

4. (A). x: 12→9; check 9 < 10 true → stop. Displays 9. (C) runs one iteration too many; (B) runs zero.

5. (C). Matches at the two 9s. FOR EACH visits all four; the IF filters.

6. (B). Steps of 4 from 0 give x = 4, 8, 12, 16, ... — the sequence skips straight over 10, so x = 10 never becomes true → infinite. (A) terminates: steps of 5 from 0 hit exactly 10. (C) starts already ≥ 10 → zero iterations, immediate stop. (D) overshoots 10 (0→4→8→12) but the catches the overshoot at 12.

7. (B). Each character appended twice, in order: "aa", then "aabb", then "aabbcc".

8. (C). FOR EACH is built for exactly this. (A) over-counts (and still needs indexing); (B) never empties the list (the loop body isn't removing elements — and even then, don't destroy data to count it); (D) is not valid — L is a list, not a number.

9. (A). i: 3 (total 3), 2 (total 5), 1 (total 6), then i = 0 → condition true → stop. 6. (D) = 5 comes from stopping when i reaches 1; the run with i = 1 still happens because the check 1 = 0 was false.

10. (A) and (B). The bug: stepping by 2 from 7 produces only odd values (7, 9, 11, ...), which never equal the even target 20 — infinite. (A) fixes it by replacing fragile equality with an overshoot-proof (stops at 21). (B) fixes it by starting on an even value: 8 → 10 → ... → 20 lands exactly. (D) does not fix it — steps of 20 from 7 give 27, 47, 67, ... and still never equal 20. (C) makes the condition true at entry, so the loop runs zero times — it "terminates" only by never doing its job.

11. (A). Four ROTATE_LEFTs = 360° = no net rotation. So each iteration is just MOVE_FORWARD: 1→2→3→4, facing east throughout. The rotation spam is theater.

12. (C). Max-finder: big starts 6; 1 doesn't beat it; 8 does → big = 8. (D) adds instead of comparing.

Answer letter distribution check: B, C, B, A, C, B, B, C, A, A+B, A, C — singles: A×3, B×4, C×4, D×0 + multi (A,B). D absent again (L9 and L11) — mocks and L12 will rebalance; flagged for the final sweep.


Exam tip: For every loop question, your first pencil stroke is the trace-table header, and your second is evaluating the condition before iteration 1 (zero-run check). Then iterate. The exam's loop distractors are, in order of popularity: the zero-run miss, the off-by-one, and the flipped UNTIL. The table defeats all three.

← All lessons
Lesson 12 ›
Score: 0/0 correct