AP CSP Day 34: Iteration Patterns | Cycle 2

Key Concepts

Loop termination errors occur when a REPEAT UNTIL condition is written incorrectly, causing infinite loops or premature exits. An off-by-one error in iteration count produces a result that is consistently one step short or long of the correct answer. AP CSP Cycle 2 iteration questions often show pseudocode with a subtle termination condition error and ask students to identify the incorrect output produced. Tracing the loop counter and accumulated value through the first two and last two iterations reveals whether the loop terminates correctly.

📚 Study the Concept First (Optional) Click to expand ▼

Iteration Bugs: Wrong Termination

Infinite Loop

An infinite loop occurs when the REPEAT UNTIL condition can never become true given the loop's logic. If the loop body never moves the relevant variable toward satisfying the condition, the loop runs forever.

Early Termination

A loop that terminates one iteration too early produces a result that is one step short of correct. This often happens when the condition checks the variable before updating it instead of after, or when the count starts at 1 instead of 0.

Common Trap: Assuming a loop that terminates is correct. A loop can terminate at the wrong time and produce an incorrect but plausible-looking result.
Exam Tip: Trace the first iteration and the last iteration carefully. For the last iteration, verify that the condition check and the final variable update happen in the correct order.
Big Idea 3: Algorithms & Programming
Cycle 2 • Day 34 Practice • Hard Difficulty
Focus: Iteration Patterns

Practice Question

What is displayed after the following code runs?

n ← 64
count ← 0
REPEAT UNTIL n < 2
{
   n ← n / 2
   count ← count + 1
}
DISPLAY(count)
Why This Answer?

Trace: n=64→2=32(count=1), 32→2=16(count=2), 16→2=8(count=3), 8→2=4(count=4), 4→2=2(count=5), 2→2=1(count=6). Now n=1 < 2 is true, loop stops. count = 6.

Why Not the Others?

A) 5 stops one iteration too early, when n=2 instead of halving once more. B) 7 counts one extra iteration that doesn't occur. D) 32 confuses 64/2 with the iteration count.

Common Mistake
Watch Out!

Students miscalculate the stopping point. The loop continues while n ≥ 2, so n=2 still triggers another iteration (n becomes 1, count becomes 6). The condition n < 2 is only checked before each iteration.

AP Exam Tip

For REPEAT UNTIL loops, the condition is checked BEFORE each iteration. If the condition is false, the body executes. Trace carefully until the condition becomes true.

Keep Practicing!

Consistent daily practice is the key to AP CSP success.

AP CSP Resources Get 1-on-1 Help
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.