GCSE Computer Science, Unit 1, Lesson 6 of 7
Brainlag Plus

More trace tables: nested loops, arrays and subroutines

GCSE Computer Science, Algorithms, 30 minutes

Have Plus? Sign in

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 t
t = 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.

ijt
111
123
136
217
229
2312

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