Topic 3.8: Iteration | AP CSP Big Idea 3 | APCSExamPrep.com

AP CSP Course Big Idea 3 3.8 Iteration
3.8
Big Idea 3 • Algorithms & Programming

Iteration

🕐 ~40 min FREE 📖 6 MCQ questions 🎮 Loop Tracer game 💻 Live Python editor AAP-2.J • AAP-2.K

After this lesson, you will be able to:

  • Distinguish definite iteration (REPEAT n TIMES, for range) from indefinite iteration (REPEAT UNTIL, while)
  • Know that range(n) runs exactly n times with the loop variable going 0 to n minus 1
  • Build counter and accumulator patterns and read their final value after the loop
  • Translate REPEAT UNTIL to a Python while by negating the condition
  • Recognize when a loop body runs zero times and when a loop becomes infinite
  • Describe a meaningful loop with iteration for your Create Performance Task
📈 Exam weight: Iteration is tested constantly in Big Idea 3 tracing and spot-the-bug items, and it is a required ingredient of the Create Task algorithm. Off-by-one errors, the REPEAT UNTIL versus while direction, and infinite loops are favorite trap topics.
💡 Think about this first

A program that greets one user is easy. A program that greets a thousand users, or keeps asking for a password until it is correct, needs to repeat itself. That repetition is iteration. Sometimes you know the exact count ahead of time, like sending five reminder emails. Sometimes you do not, like rolling a die until you get a six. This lesson is about controlling exactly how many times your code runs, and never one time too many or too few.

What Iteration Means

Iteration is the repetition of a portion of an algorithm. Instead of writing the same instruction over and over, you write it once and tell the program how many times, or under what condition, to repeat it. Iteration is one of the three fundamental building blocks of every algorithm, alongside sequencing and selection, and it is exactly what the Create Performance Task rubric looks for.

There are two flavors. Definite iteration repeats a fixed, known number of times. In AP pseudocode this is REPEAT n TIMES, and in Python it is for i in range(n). Indefinite iteration repeats until some condition is met, and you do not know in advance how many passes that will take. That is REPEAT UNTIL(condition) in pseudocode and while in Python.

for i in range(3):
    print("hi")
REPEAT 3 TIMES
{
    DISPLAY("hi")
}

The loop above runs exactly three times because range(3) produces the values 0, 1, and 2. The important idea for definite iteration: range(n) runs the body n times, but the loop variable takes the values 0 through n minus 1, not 1 through n. That gap is the source of the most common loop bug on the exam.

🎯 What the exam expects

The CED (AAP-2.J and AAP-2.K) requires you to read and write both loop types. Memorize the mapping: REPEAT n TIMES equals for i in range(n), and REPEAT UNTIL(cond) equals while not cond. A definite loop always runs a countable number of times; an indefinite loop runs an unknown number of times.

✍ Mini Exercise 1 • Predict the output
How many times does this loop print?
for i in range(4):
    print("x")

Counters and Accumulators

Two patterns power almost every useful loop. A counter is a variable that goes up by one each pass to tally how many times something happened. An accumulator is a variable that keeps a running total, updated on every pass, so that by the end it holds the combined result of the whole loop.

The recipe is always the same: set the variable to a starting value before the loop, update it inside the loop, and read it after the loop. Forgetting the initialization, or putting the final print inside the loop instead of after it, are classic mistakes.

total = 0
for i in range(1, 6):
    total = total + i
print(total)
total <- 0
i <- 1
REPEAT 5 TIMES
{
    total <- total + i
    i <- i + 1
}
DISPLAY(total)

This loop adds 1, then 2, then 3, 4, and 5 into total, so it prints 15. Notice the Python range(1, 6) stops before 6, giving the values 1 through 5. The pseudocode reaches the same result with REPEAT 5 TIMES and its own counter. Both are definite iteration; they run a fixed five times.

🎯 Final value matters

Exam questions love to ask for the value of the accumulator or the loop counter after the loop ends, not during it. Trace every pass, then report the value once the loop has finished. Do not stop tracing one pass too early.

REPEAT UNTIL Is the Opposite of while

This is the single most tested idea in this topic, and it trips up students every year. A Python while loop keeps going while its condition is true and stops when the condition becomes false. An AP REPEAT UNTIL loop is the mirror image: it keeps going until its condition becomes true, checking after nothing and stopping the moment the condition is true.

Because they are opposites, translating between them means negating the condition. A loop that should continue while count < 3 in Python becomes REPEAT UNTIL (count >= 3) in pseudocode. Same behavior, flipped condition.

count = 0
while count < 3:
    print(count)
    count = count + 1
count <- 0
REPEAT UNTIL (count >= 3)
{
    DISPLAY(count)
    count <- count + 1
}

Both loops above print 0, 1, 2 and then stop. The Python version continues while count < 3 is true. The pseudocode version repeats until count >= 3 is true. Read the two conditions and confirm they are logical opposites of each other. If you ever see a REPEAT UNTIL and want to think in Python, mentally rewrite it as while not (condition).

⚠ The direction trap

If a question gives you a REPEAT UNTIL (x > 10) and you read it as if it were a Python while x > 10, you will get the loop backwards and pick the wrong answer every time. UNTIL means stop when true. WHILE means continue when true. They are not the same word.

✍ Mini Exercise 2 • Spot the flaw
Why does this loop never stop?
x = 0
while x < 5:
    print(x)

Zero Passes and Infinite Loops

Two boundary cases show up again and again. First, a loop can run its body zero times. If a REPEAT UNTIL condition is already true when the loop is first reached, the body never runs at all. The same happens in Python when a while condition is false from the start.

x = 10
while x < 5:
    print("run")
    x = x + 1
print("done")
x <- 10
REPEAT UNTIL (x >= 5)
{
    DISPLAY("run")
    x <- x + 1
}
DISPLAY("done")

Here x is 10, so the Python condition x < 5 is false immediately and the body is skipped; the program prints only done. The pseudocode REPEAT UNTIL (x >= 5) is already true (10 is at least 5), so it also skips the body. A loop running zero times is not an error, it is a legal and common outcome.

Second, an infinite loop happens when the stopping condition never becomes true. In a counter loop this almost always means you forgot to update the counter, so the condition is stuck. Every indefinite loop must contain something that eventually makes it stop.

⚠ Off-by-one

range(1, 5) gives 1, 2, 3, 4. It stops before the second number. To include 5, you need range(1, 6). Whenever a loop prints or sums the wrong count of items by exactly one, suspect the range bounds first.

✍ Mini Exercise 3 • Fill in the blank
Type the exact number this prints.
total = 0
for i in range(1, 5):
    total = total + i
print(total)
prints:

Key Vocabulary

Term Definition Example
Iteration Repeating a portion of an algorithm a loop
Definite iteration Repeats a fixed, known number of times REPEAT n TIMES / for i in range(n)
Indefinite iteration Repeats until a condition is met, count unknown REPEAT UNTIL(c) / while
Counter A variable increased by one each pass to tally events count = count + 1
Accumulator A variable holding a running total across passes total = total + i
Infinite loop A loop whose stopping condition never becomes true counter never updated
📋 Create Performance Task • Iteration earns a required rubric point

The Create Task rubric awards a point for an algorithm that includes sequencing, selection, AND iteration working together. A loop is not optional decoration; it is one of the three ingredients the readers must be able to point to. Iteration is also how your program processes a whole collection of input instead of a single value.

A point-earning example

Imagine a program that adds up the numbers 1 through n to produce a running total:

sum <- 0 count <- 1 REPEAT UNTIL (count > n) { sum <- sum + count count <- count + 1 } DISPLAY(sum)

In your written response, identify the loop and explain what it repeats and how it stops:

  • "The iteration repeats the body once for each value from 1 up to n, so it runs a number of times that depends on the input."
  • "On each pass, the accumulator sum is updated by adding the current count, which builds the running total."
  • "The counter count increases every pass, so the stopping condition count > n eventually becomes true and the loop ends."

The trap to avoid

Make sure the loop actually stops. If you forget the count <- count + 1 line, the condition never becomes true and you have an infinite loop, which earns no point and freezes the program. Also confirm your range covers the right values, an off-by-one loop that misses the first or last item is a partial-credit killer. See the full Create Task module →

📈
MCQ Practice
6 questions • Exam difficulty and above • Predict before you peek
Question 1 of 6Trace
Predict first: how many times does the body run, and what is added each time?
What does this code segment display?
n = 0 for i in range(3): n = n + 2 print(n)
Incorrect. That is only two passes. range(3) runs the body three times, adding 2 each time.
Correct. range(3) runs the body three times, so n goes 2, 4, 6. After the loop n is 6.
Incorrect. That would be four passes. range(3) gives the values 0, 1, 2, which is three passes.
Incorrect. 3 is the number of passes, not the total. Each pass adds 2, so the total is 6.
Question 2 of 6Spot the bug
This loop is supposed to print 0, then 1, then 2, and then stop. What is wrong with it?
k = 0 while k < 3: print(k)
Incorrect. Changing to <= would still loop forever, because k never changes at all.
Correct. There is no k = k + 1, so k stays 0, the condition k < 3 stays true, and the loop never stops. It is an infinite loop.
Incorrect. A while loop can count perfectly well. The missing piece is updating k.
Incorrect. print belongs inside the loop to show each value. The real bug is that k is never incremented.
Question 3 of 6Trace
Predict first: rewrite REPEAT UNTIL as while not (condition).
In AP pseudocode, REPEAT UNTIL (x >= 5) repeats its body until the condition becomes true. Which Python while header loops for exactly the same set of values of x?
Incorrect. That continues while x is already 5 or more, which is the reverse. REPEAT UNTIL stops when the condition is true.
Correct. REPEAT UNTIL (x >= 5) continues as long as x is below 5, which is while x < 5. The while condition is the negation of the UNTIL condition.
Incorrect. == 5 only runs when x is exactly 5, not for every value below 5.
Incorrect. != 5 keeps looping for 6, 7, and beyond, which REPEAT UNTIL (x >= 5) would not do.
Question 4 of 6NOT question
Each segment is intended to run its body exactly 4 times. Which one does NOT run its body exactly 4 times?
Incorrect. range(4) gives 0, 1, 2, 3, which is 4 passes.
Incorrect. range(1, 5) gives 1, 2, 3, 4, which is 4 passes.
Incorrect. range(2, 6) gives 2, 3, 4, 5, which is 4 passes.
Correct. range(1, 4) gives 1, 2, 3, which is only 3 passes, not 4. It stops before 4.
Question 5 of 6I, II, III
Before each segment runs, s is set to 0. Which segments leave s equal to 10 after the loop finishes?
  • I. s = 0 ; for i in range(1, 5): s = s + i
  • II. s = 0 ; for i in range(5): s = s + i
  • III. s = 0 ; for i in range(1, 6): s = s + i
Incorrect. I gives 10, but II also gives 10, so I only is too narrow.
Correct. I adds 1+2+3+4 = 10. II adds 0+1+2+3+4 = 10. III adds 1+2+3+4+5 = 15, so III is not 10. Only I and II reach 10.
Incorrect. III sums to 15, not 10, so it cannot be part of the answer.
Incorrect. III sums 1 through 5 to 15, so it does not leave s at 10.
Question 6 of 6Spot the bug
This loop is meant to print the numbers 1 through 5, but it has an off-by-one error. What does it actually print?
for i in range(1, 5): print(i)
Incorrect. range(1, 5) stops before 5, so 5 is never printed. To include 5 you need range(1, 6).
Correct. range(1, 5) produces 1, 2, 3, 4 and stops before 5. The fix is range(1, 6).
Incorrect. The range starts at 1, not 0, so 0 is not printed.
Incorrect. The range stops before 5, so it prints fewer numbers, not more.
🎮 Lesson Game
Loop Tracer
Trace each definite or indefinite loop and predict what it displays. 8 rounds.
0
Correct
1/8
Round
0
Streak 🔥
🐛 Python • how many passes, and what displays?
0/8
correct answers
💻 Live Python Code Editor
Practice Problems
Real Python runs right here in your browser. The first time you press Run, the Python engine loads (a few seconds); after that it is instant. Problems build from guided to Create-Task level. Use Hint if you are stuck, and check your output against the target.
Hints used: 0 • Solutions viewed: 0
Level 1 • Guided
Problem 1 of 8 • sum with an accumulator
n is set. Use a loop to add the numbers 1 through n and print the total. Target output: 15
Level 2 • Counter
Problem 2 of 8 • count with a condition
n is set. Count how many numbers from 1 through n are even, then print the count. Target output: 5
Level 3 • Accumulator
Problem 3 of 8 • running product
n is set. Multiply the numbers 1 through n together (this is n factorial) and print the result. Start the accumulator at 1, not 0. Target output: 24
Level 4 • Fix the bug
Problem 4 of 8 • stop the infinite loop
This should add 1 + 2 + 3 and print 6, but it runs forever because the counter is never updated. Add the missing line so the loop stops. Target output: 6
Level 5 • while loop
Problem 5 of 8 • countdown, one per line
n is set. Use a while loop to print a countdown from n down to 1, each number on its own line. Target output:
  • 5
  • 4
  • 3
  • 2
  • 1
Level 6 • Create Task style
Problem 6 of 8 • iteration plus selection
You are scoring a game. For each round from 1 to n, add the round number to a running total, but only when the round number is odd (only odd rounds score). Print the total. Target output: 9
Level 7 • Challenge
Problem 7 of 8 • you write the whole program
Open ended. Write the entire program yourself. N is given. Print the sum of all the even numbers from 1 to N inclusive. Only the input is provided. Target output: 30
Level 8 • Challenge
Problem 8 of 8 • build a pattern, multi-line
Open ended. Write the entire program yourself. N is given. Print a left-aligned triangle of stars where line 1 has 1 star, line 2 has 2 stars, and so on up to line N. Target output:
  • *
  • **
  • ***
  • ****

Frequently Asked Questions

Definite iteration repeats a fixed, known number of times, like REPEAT n TIMES or for i in range(n). Indefinite iteration repeats until a condition is met and you do not know the count in advance, like REPEAT UNTIL(condition) or a Python while loop.
A while loop continues while its condition is true and stops when it becomes false. A REPEAT UNTIL loop continues until its condition becomes true, so it stops when the condition is true. To translate one to the other you negate the condition: REPEAT UNTIL(c) is the same as while not c.
Exactly n times. The loop variable takes the values 0, 1, 2, up to n minus 1, which is n values total. This is why range(3) runs three times but never uses the value 3, and it is the source of most off-by-one bugs.
An infinite loop happens when the stopping condition never becomes true. In a counter loop this usually means you forgot to update the counter inside the loop, so the condition stays the same on every pass. Every indefinite loop needs something inside it that eventually makes the condition stop the loop.
Yes. If a REPEAT UNTIL condition is already true when the loop is first reached, or a Python while condition is false from the start, the body never runs. Running zero times is a legal, common outcome, not an error.
📦
AP CSP Teacher SuperpackSlides, lesson plans, unit tests for all 5 Big Ideas, $249
Get the Superpack →
🏫
For teachers

The Superpack includes an editable Topic 3.8 slide deck with animated loop traces, a REPEAT UNTIL versus while translation drill, an off-by-one and infinite-loop bug bank, a print-ready counter and accumulator worksheet, and a unit quiz. View what's included →

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]