Iteration
Loops in Action
Master the power of repeating instructions with loops: from counting through lists to running code until a condition is met.
What Is Iteration?
Iteration is the process of repeating a set of instructions multiple times. Instead of writing the same code over and over, a loop lets you execute a block of code as many times as needed: a fixed number of times, once for each item in a list, or until a condition changes.
Why Iteration Matters
Anatomy of a Loop
Two Core Types of Loops
REPEAT n TIMES
When you know exactly how many times to repeat, use REPEAT n TIMES. The loop body executes \( n \) times, then stops.
FOR EACH Item in a List
When you want to process every element of a list, use FOR EACH. The loop variable takes on each value in turn.
REPEAT UNTIL (Condition)
When you don't know in advance how many repetitions are needed, use REPEAT UNTIL. The loop checks its condition before each iteration and stops when the condition becomes true.
REPEAT n TIMES vs REPEAT UNTIL
| REPEAT n TIMES | REPEAT UNTIL | |
|---|---|---|
| Iterations known? | Yes: fixed count | No: depends on data |
| Controlled by | A counter \( n \) | A Boolean condition |
| Stops when | Counter reaches \( n \) | Condition becomes true |
| Risk of infinite loop? | No | Yes: if condition never becomes true |
| Example use | Draw 5 shapes | Search until found |
How to Trace a Loop
Example 1: Counting with a Loop
| Iteration | i (before) | sum (after) | i (after) |
|---|---|---|---|
| 1st | 1 | 1 | 2 |
| 2nd | 2 | 3 | 3 |
| 3rd | 3 | 6 | 4 |
| 4th | 4 | 10 | 5 |
Example 2: Filtering a List
Example 3: REPEAT UNTIL Search
Nested Loops
A loop inside another loop is called a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.
Common Mistakes
Iteration Summary
| Construct | Syntax | When to Use |
|---|---|---|
| Fixed count | REPEAT n TIMES | Known number of repetitions |
| List traversal | FOR EACH item IN list | Process every element |
| Condition-based | REPEAT UNTIL(cond) | Unknown iterations, stop on event |
| Nested loops | Loop inside a loop | 2D patterns, all pairs, grids |
Question 1 of 5
What is the value of x after this code runs?
Question 2 of 5
What does this code display?
Question 3 of 5
Which of the following will cause an infinite loop?
Question 4 of 5
What is the value of result after this code?
Question 5 of 5
How many times does DISPLAY execute in this nested loop?