AQA GCSE Computer Science (8525), section 3.2.2 (Programming concepts)
What nesting means
Nesting is putting one structure inside another. You can nest selection inside selection, iteration inside iteration, or selection and iteration in each other.
Nested selection
An IF inside another IF. The inner one is only reached if the outer condition is true.
IF gameWon THEN
OUTPUT "You won!"
IF score > highScore THEN
highScore ← score
OUTPUT "New high score"
ENDIF
ENDIF
Nested iteration
A loop inside another loop. The inner loop runs fully for each repeat of the outer loop.
FOR row ← 1 TO 3
FOR column ← 1 TO 4
OUTPUT row * column
ENDFOR
ENDFOR
The inner statement runs times.
for row in range(1, 4):
line = ""
for column in range(1, 5):
line = line + str(row * column) + " "
print(line)
# 1 2 3 4
# 2 4 6 8
# 3 6 9 12
Selection inside iteration
A very common pattern: loop through items and test each one.
count ← 0
FOR i ← 1 TO 10
number ← USERINPUT
IF number MOD 2 = 0 THEN
count ← count + 1
ENDIF
ENDFOR
OUTPUT count
Iteration inside selection
IF choice = "play" THEN
WHILE lives > 0
... play a turn ...
ENDWHILE
ENDIF
Tips
- Indent each level more, so you can see which
ENDIForENDFORcloses which structure. - When tracing nested loops, keep a column for each loop variable.
- Give each structure its own matching end keyword.
Common mistake: losing track of which end keyword belongs to which structure. Indent each level and match every IF with an ENDIF, and every FOR with an ENDFOR. Also, remember the inner loop starts again from the beginning each time the outer loop repeats.
Exam tip: for nested loop questions, count the repeats by multiplying (outer times inner). In a trace table, give each loop variable its own column.
Check yourself
How many times does the inner statement run in: FOR a ← 1 TO 5, FOR b ← 1 TO 2?
10 times.
What does the inner loop do each time the outer loop repeats?
It runs through all of its repeats again from the start.
Why should nested structures be indented?
So it is clear which statements belong to which structure, making the code easier to read.