AP CSP
AP Computer Science Principles / All lessons / Big Idea 3: Algorithms and Programming
3Big Idea 3: Algorithms and Programming
AP CSP topic 3.8

Iteration

×3

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.

Picture itREPEAT 3 TIMES MOVE_FORWARD() ×3 123 pass 1, pass 2, pass 3
REPEAT n TIMES runs the loop body n times. REPEAT UNTIL checks a condition before each pass and stops when it is true.

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?

  1. (A) 3
  2. (B) 4
  3. (C) 7
  4. (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?

  1. (A) 16
  2. (B) 20
  3. (C) 32
  4. (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?

  1. (A) The loop runs 3 times
  2. (B) The loop runs 4 times and x ends at -2
  3. (C) The loop never ends because x skips over 0
  4. (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?

  1. (A) 4
  2. (B) 5
  3. (C) 6
  4. (D) Infinitely many
Show answer

(B) 5 count goes 0 to 4 inside the loop, 5 iterations, and stops when it reaches 5.

Open 3.8 in the interactive course