AP CSP Day 26: Iteration Patterns

Key Concepts

Nested loops occur when one loop appears inside another, multiplying the total number of iterations. For a nested loop with an outer loop running m times and an inner loop running n times, the inner body executes m times n total iterations. AP CSP review questions on iteration often involve loops that modify a list or accumulate a value, requiring students to trace each iteration step by step. Understanding REPEAT UNTIL termination conditions is especially important because the loop continues as long as the condition is false.

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

Iteration Review: Loop Tracing

Tracking Loop State

To trace a loop accurately, track all variables that change each iteration: the loop counter, any accumulators, and any lists being modified. Updating one variable can affect the next iteration's condition or computation.

Nested Loop Counts

In nested loops, the inner loop completes all its iterations for each single iteration of the outer loop. An outer loop running 4 times and an inner loop running 3 times produces 12 total inner body executions.

Common Trap: Losing track of which iteration you are on during a trace. Writing out a table with the iteration number and each variable's value prevents this error.
Exam Tip: For complex loops, only trace the first 2-3 iterations and the final iteration to establish the pattern. You do not need to trace every step for a 100-iteration loop.
Big Idea 3: Algorithms & Programming
Cycle 1 • Day 26 Practice • Medium Difficulty
Focus: Iteration Patterns

Practice Question

What is displayed after the following code runs?

i ← 1
REPEAT UNTIL i > 5
{
   IF i MOD 2 = 0
   {
      DISPLAY(i)
   }
   i ← i + 1
}
Why This Answer?

The loop runs for i = 1, 2, 3, 4, 5 (stops when i > 5). The IF condition checks whether i is even (i MOD 2 = 0). Even values are 2 and 4, so those are displayed.

Why Not the Others?

A) 1, 3, 5 are odd numbers where MOD 2 = 1, not 0. They fail the condition. B) Not all values are displayed — only those passing the MOD 2 = 0 filter. D) The loop stops when i exceeds 5, so i = 6 is never processed inside the loop body.

Common Mistake
Watch Out!

Students confuse MOD 2 = 0 (even numbers) with MOD 2 = 1 (odd numbers), or they forget that the loop condition is checked before each iteration.

AP Exam Tip

MOD 2 = 0 means even. MOD 2 = 1 means odd. Write this down as a reference during the exam to avoid mixing them up.

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.