AP CSP topic 3.8
Iteration
Iteration repeats a set of steps. REPEAT n TIMES runs a block a fixed number of times. REPEAT UNTIL (condition) keeps running until the condition becomes true, so it might run zero times or many times. If the condition never becomes true, the loop never stops: an infinite loop. Loops let short programs do huge amounts of work.
Iteration vocabulary
- Iteration: Repeating part of an algorithm a set number of times or until a condition is met.
- REPEAT n TIMES: An AP pseudocode loop that runs its block exactly n times.
- REPEAT UNTIL: An AP pseudocode loop that stops once its condition becomes true.
- Infinite loop: A loop whose ending condition is never met, so it never stops.
AP-style practice questions
Try each one, then open the answer. To save your progress, take this quiz in the interactive course.
Skill: Code Analysis
total ← 0
REPEAT 4 TIMES
{
total ← total + 3
}
DISPLAY(total)
1. What is displayed?
- (A) 3
- (B) 4
- (C) 7
- (D) 12
Show answer
(D) 12 3 is added four times: 3 × 4 = 12.
Skill: Code Analysis
n ← 1
REPEAT UNTIL (n > 20)
{
n ← n * 2
}
DISPLAY(n)
2. What is displayed?
- (A) 16
- (B) 20
- (C) 32
- (D) 64
Show answer
(C) 32 n goes 2, 4, 8, 16, 32. The loop stops once n is greater than 20.
Skill: Code Analysis
x ← 10
REPEAT UNTIL (x = 0)
{
x ← x - 3
}
3. Which of the following best describes what happens?
- (A) The loop runs 3 times
- (B) The loop runs 4 times and x ends at -2
- (C) The loop never ends because x skips over 0
- (D) The loop never runs
Show answer
(C) The loop never ends because x skips over 0 x goes 7, 4, 1, -2, ... and never equals 0, so it is an infinite loop.
Skill: Algorithms and Program Development
count ← 0
REPEAT UNTIL (count = 5)
{
DISPLAY("Hi")
count ← count + 1
}
4. How many times is "Hi" displayed?
- (A) 4
- (B) 5
- (C) 6
- (D) Infinitely many
Show answer
(B) 5 count goes 0 to 4 inside the loop, 5 iterations, and stops when it reaches 5.