Trace nested loops, loops over arrays and programs that call subroutines, then use a trace table to find a bug.
Nested loops
A nested loop is a loop inside another loop.
The inner loop runs all the way through on every pass of the outer loop.
The inner loop runs 3 times for each value of i
t = 0
for i = 1 to 2
for j = 1 to 3
t = t + j
next j
next i
print(t)t ← 0
FOR i ← 1 TO 2
FOR j ← 1 TO 3
t ← t + j
ENDFOR
ENDFOR
OUTPUT tt = 0
for i in range(1, 3):
for j in range(1, 4):
t = t + j
print(t)Start a new row each time the inner loop runs once. i stays the same while j counts, then j starts again from 1 when i changes.
| i | j | t |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 3 |
| 1 | 3 | 6 |
| 2 | 1 | 7 |
| 2 | 2 | 9 |
| 2 | 3 | 12 |
The program prints 12. The line inside both loops runs 2 × 3 = 6 times: the passes multiply, they do not add.
The rest of this lesson and its 12 practice questions are in Plus.
Screen 1 of 5, free to read.
- 12 exam-style questions, marked as you go, each with a worked solution
- Anything you get wrong is saved to your flashcards