Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Computational Thinking · Grade 6-8

Iteration

Repeating a block of instructions multiple times until a stopping condition is satisfied.


Quick Answer

Repeating a block of instructions multiple times until a stopping condition is satisfied. Use it whenever the same action must happen many times: adding up 100 numbers, checking every item in a list, or asking for a password until it is correct. A for loop repeats a set number of times or once per item; a while loop repeats for as long as its condition stays true. Every loop needs something that changes on each pass, so that it eventually stops.

Why This Matters

Loops let a few lines of code do work that would otherwise take thousands: one loop can total a year of daily rainfall or move every enemy in a game on each frame. Knowing exactly how many times a loop runs, and what each variable holds after each pass, lets you fix the two most common loop bugs: a loop that never stops, and a loop that runs one time too many or too few.

Intuitive Explanation

Suppose you want 1 + 2 + 3 + 4 + 5. Without a loop you write five additions. With one: total = 0; for i from 1 to 5: total = total + i. The body, total = total + i, is written once but runs five times, with i taking the values 1, 2, 3, 4, 5. A trace shows total going 1, 3, 6, 10, 15. Change the 5 to 1000 and the same three lines add up every number from 1 to 1000.

A while loop is controlled by a condition instead of a count: n = 1; while n < 50: n = n * 2. Before each pass it checks the condition. n goes 1, 2, 4, 8, 16, 32, 64; when n reaches 64, the test 64 < 50 is false and the loop stops after 6 passes. Something inside the body has to move the values toward making the condition false. If the body were n = n * 1, n would stay 1 forever: an infinite loop.

Iteration is not the same as selection, although both test conditions. An if checks once and runs its block at most once; a while checks again after every pass. Iteration also differs from writing the same line several times in sequence, because the number of repeats can depend on the data, such as the length of a list the programmer has never seen.

Think of it like this. A loop is like running laps with a coach holding a clipboard. Before each lap the coach checks the rule, say 'fewer than 4 laps done?', and you run again only if the answer is yes. Each lap adds a tick to the clipboard. Forget the tick and the coach will keep you running forever.

Core idea. Loops let you do repetitive tasks without writing repetitive code.


When to Use

Use iteration when the same steps must run many times, for each item in a list, or until something happens: totals, counts, searches, repeated input. Count the passes and track the variables after each one. If a block should run at most once depending on a condition, use Selection; if steps run once each in order, it is plain Sequence; if a function solves a problem by calling itself on a smaller input, that is Recursion.

Tip. Ask: Does a block of steps run again and again until a count or condition says stop?

How to Recognize It

Before calling something iteration, look for a block that repeats and for the thing that will make it stop.

  1. Does the same block of steps run more than once?

    Yes is the sign of iteration. If every step runs just once in the order written, it is Sequence.

  2. Is the condition checked again after every pass, rather than only once?

    Yes means a loop. If the condition is checked one time to pick a path, it is Selection.

  3. Do you know in advance how many passes there will be, or is there one pass per item in a list?

    Yes points to a For Loop, the counting kind of iteration. No, because it repeats until something happens, suggests a while loop.

  4. Does a function repeat the work by calling itself on a smaller input?

    Yes points to Recursion, which repeats through self-calls rather than through a loop block.

Iteration vs Selection vs Recursion vs For Loop

Loops, choices and self-calling functions all control which lines run, so they get confused. Ask whether a block runs many times, and if so, whether a loop or a self-call is doing the repeating.

Iteration

Meaning
Iteration repeats a block of instructions until a count runs out or a stopping condition is met.
Key test
A loop block runs many times, with something changing each pass.
Formula
WHILE B DO S
Example
Keep asking for a password until the user types the right one.

Selection

Meaning
Selection checks a condition once and runs one block or another.
Key test
The condition picks a path once, and nothing repeats.
Example
if it is raining: take an umbrella.

Recursion

Meaning
Recursion repeats work by having a function call itself on a smaller version of the problem.
Key test
No loop block; the function calls itself until a base case.
Example
countdown(n): print n, then call countdown(n - 1), stopping when n reaches 0.

For Loop

Meaning
A for loop is the kind of iteration that runs a set number of times or once for each item in a collection.
Key test
The number of passes is fixed before the loop starts.
Example
for each name in the class list: print the name.

Formula & Notation

Worked Examples

Example 1 — Trace a for loop pass by pass

Easy

What does this program print? total = 0; for i in 1, 2, 3, 4: total = total + i * i; print(total)
Show the steps and the answer
  1. Before the loop: total = 0.

    A running total must start at 0, or the first addition would build on a leftover value.

  2. i = 1: total = 0 + 1 = 1. i = 2: total = 1 + 4 = 5.

    The body runs once per value of i, starting from the total left by the previous pass.

  3. i = 3: total = 5 + 9 = 14. i = 4: total = 14 + 16 = 30.

    Each pass adds i * i for the current i.

  4. The values of i are used up, so the loop ends and print shows 30.

    print sits after the loop, so it runs once, after all four passes.

Answer: 30

Takeaway: Trace a loop one pass at a time, writing down the loop variable and every changed value after each pass.

Example 2 — if versus while with the same body

Standard

Compare these two programs. A: n = 3; if n > 0: n = n - 1; print(n). B: n = 3; while n > 0: n = n - 1; print(n). What does each print?
Show the steps and the answer
  1. A: 3 > 0 is true, so n = 2, and print shows 2.

    An if checks its condition once and runs its block at most once.

  2. B: 3 > 0 is true, so n = 2; 2 > 0 is true, so n = 1; 1 > 0 is true, so n = 0.

    A while goes back and tests the condition again after every pass.

  3. B: 0 > 0 is false, so the loop stops after 3 passes and print shows 0.

    The update n = n - 1 moved n toward making the test false, so the loop was able to end.

Answer: A prints 2; B prints 0.

Takeaway: With the same condition and body, if runs the body once, while runs it until the condition turns false.

Example 3 — Find the mistake: one pass short

Application

Grace wants to print the numbers 1 to 10. She writes: i = 1; while i < 10: print(i); i = i + 1. Find the mistake and correct it.
Show the steps and the answer
  1. Trace the end of the loop: when i = 9, the test 9 < 10 is true, so it prints 9 and i becomes 10.

    The last passes are where off-by-one errors hide.

  2. Next test: 10 < 10 is false, so the loop ends without printing 10.

    The loop ran for i = 1 to 9, which is 9 passes, not 10.

  3. Fix the condition: while i <= 10 (or while i < 11).

    Now the test is still true when i is 10, so 10 is printed before i becomes 11 and the loop stops.

  4. Count the passes of the fix: i takes the values 1 through 10, which is 10 passes.

    Counting from the first value to the last value that passes the test confirms the fix.

Answer: Use while i <= 10; the loop then prints 1 through 10.

Takeaway: Check the last pass of every loop: decide whether the final value should pass the test, and choose < or <= to match.

Where You'll See It

  • Doing 20 jumping jacks

    You repeat the same action until your counter reaches 20, then stop, which is exactly a loop with a stopping condition.

  • Stamping every page of a worksheet packet

    Instead of describing each stamp separately, you repeat 'stamp the next page' until there are no pages left, the way a loop processes a list.

  • A washing machine spin cycle

    It repeats the spin over and over until the timer runs out, then moves on, just like a loop that runs until its condition is met.

Common Mistakes

  1. The slip: A loop will always stop on its own eventually.

    Why it's tempting: Loops you've seen finish quickly, so stopping feels automatic.

    Instead: A loop only stops when its condition becomes false; if you never update the loop variable toward that condition, it runs forever (an infinite loop).

  2. The slip: A loop from 1 to 10 written as i < 10 runs 10 times.

    Why it's tempting: Seeing the number 10 makes it feel like the loop runs 10 times.

    Instead: With i starting at 1 and condition i < 10, the loop runs for i = 1..9, which is 9 times; off-by-one comes from confusing < with <= and the start value.

  3. The slip: It's fine to add or remove items from a list while looping over it.

    Why it's tempting: You're already touching the list, so changing it in the same loop seems convenient.

    Instead: Modifying a collection while iterating over it can skip or double-count elements; build a new collection or loop a copy instead.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. How many times does this print "hi"? `for i in range(5): print("hi")`

    Hint: List the values `range(5)` produces.

  2. Trace: `total = 0`, then `for i in range(1, 5): total = total + i`, then `print(total)`. What is printed?

    Hint: `range` stops just before its end value.

  3. Trace: `n = 20`, `count = 0`, then `while n > 1: n = n // 2; count = count + 1`. What are `n` and `count` at the end?

    Hint: `//` divides and drops any remainder. Write `n` after each pass.

  4. A loop should print 1, 2, 3, …, 10. Which is correct: `for i in range(10): print(i)` or `for i in range(1, 11): print(i)`?

    Hint: Write the first and last value each loop would print.

  5. You need the total of a list of 30 prices. Should you write 30 addition lines one after another, or use iteration?

    Hint: Is the same step being repeated?

  6. This loop never stops: `i = 0`, then `while i < 3: print(i)`. Explain why, and fix it.

    Hint: Does anything inside the loop change `i`?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

When should I use a for loop and when a while loop?

Use a for loop when you know how many passes you need before you start: 10 times, or once for every item in a list. Use a while loop when you only know the stopping condition, such as 'until the player guesses right' or 'until the tank is full'. Any for loop can be rewritten as a while loop with a counter, but the for loop is harder to get wrong.

Can a loop run zero times?

Yes. A while loop tests its condition before the first pass, so if the condition is already false, the body never runs: with count = 10, the loop while count < 5 does nothing at all. A for loop over an empty list also runs zero times. Some languages have a do-while loop, which tests at the end and so always runs at least once.

What is a nested loop?

A loop inside another loop. The inner loop runs all the way through for every single pass of the outer loop. If the outer loop runs 3 times and the inner loop runs 4 times, the inner block runs 3×4=123 \times 4 = 12 times. Nested loops are how programs go through a grid, such as every row and column of a picture or a times table.

Learning Path

← Before

Sequence
Iteration

You are here

You need Sequence: statements run in order, each using the current values. Iteration adds the ability to send control back to the top of a block and run it again until a condition says stop. Next, While Loop and For Loop look at the two main ways to write that repetition, and Recursion shows a different way to repeat, in which a function calls itself on a smaller problem.

See Also