AP CSP Day 26: Iteration Patterns
Share
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.
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
}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.
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.
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.
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