AP CSP Day 4: Iteration Patterns
Share
Iteration in AP CSP uses REPEAT n TIMES or REPEAT UNTIL loops to execute a block of code multiple times. REPEAT n TIMES runs exactly n iterations regardless of conditions, while REPEAT UNTIL continues until its condition becomes true. A common exam error is off-by-one mistakes where students miscount iterations. Understanding how a loop counter or accumulated value changes each iteration is critical for tracing algorithm output correctly on the AP exam.
📚 Study the Concept First (Optional) Click to expand ▼
Iteration: REPEAT n TIMES and REPEAT UNTIL
Two Types of Loops
REPEAT n TIMES executes a block exactly n times with no condition check. REPEAT UNTIL keeps looping until a condition becomes true. The body executes first, then the condition is checked, so a REPEAT UNTIL loop always runs at least once.
Real-World Analogy
REPEAT 10 TIMES is like doing exactly 10 push-ups. REPEAT UNTIL is like driving and checking 'Am I at my destination?' after each mile. You always drive at least one mile before checking.
Practice Question
What is displayed after the following code runs?
count ← 0
REPEAT 4 TIMES
{
count ← count + 2
}
DISPLAY(count)The loop body executes exactly 4 times, adding 2 to count each iteration. Starting at 0: after iteration 1 count=2, iteration 2 count=4, iteration 3 count=6, iteration 4 count=8. The final value displayed is 8.
A) 2 is the value after only one iteration. B) 4 is the value after only two iterations or the result of confusing the repeat count with the increment. D) 10 would require 5 iterations or an incorrect starting value.
Students sometimes confuse the number of iterations with the increment value, or start counting from 1 instead of 0, leading to an off-by-one result.
Create a trace table with a column for each variable. Write down the value after every iteration to avoid miscounting.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help