🎯 Syllabus & Goals 3 min
Cambridge 8.1.5 · Nested statements Paper 2 · Algorithms, Programming and Logic
By the end of this lesson you can:
- Write an
IFnested inside anotherIF, and the Pythonelifversion. - Write a loop nested inside another loop, and state how many times the inner body runs.
- Trace a nested algorithm that combines loops, selection, totalling and finding a maximum.
Textbook: Chapter 8, §8.1.5 (pp. 318–321)
Recap / Warm-Up 5 min
So far you have used each construct — sequence, selection, iteration — mostly on its own, or with an IF inside a loop for counting.
Quick starter
A clock shows hours and minutes. For each hour, the minutes go 0 to 59. How many times does the minute value change in 12 hours?
Reveal the answer
12 × 60 = 720. That is a nested loop: the inner (minutes) loop runs completely for every single pass of the outer (hours) loop.
🧠 Key Concept 14 min
Selection and iteration statements can be placed inside each other: an IF inside a loop, a loop inside a loop, or an IF inside an IF. Nesting reduces the amount of code needed and makes a program simpler to test, because each level does one clear job.
1 · IF inside IF
Cambridge pseudocode has no "else if". To test a second condition only when the first is FALSE, put a new IF inside the ELSE. Python shortens this with elif.
Cambridge pseudocode
IF Hours <= 1
THEN
Charge ← 0
ELSE
IF Hours <= 3
THEN
Charge ← 2
ELSE
Charge ← 5
ENDIF
ENDIFThe same in Python
# Car park charge: an IF nested inside an ELSE hours = int(input("Hours parked: ")) if hours <= 1: charge = 0 else: if hours <= 3: charge = 2 else: charge = 5 print("Charge: $", charge)
With elif, lines 5–6 become elif hours <= 3: — same logic, one less level of indentation.
Hours parked: 2 Charge: $ 2
2 · A loop inside a loop
The inner loop runs all its iterations for each iteration of the outer loop.
Worked Example 12 min
Example 1 · Nested FOR loops — a multiplication grid
Cambridge pseudocode
DECLARE Row, Column : INTEGER
FOR Row ← 1 TO 2
FOR Column ← 1 TO 3
OUTPUT Row, " x ", Column, " = ", Row * Column
NEXT Column
NEXT Row
OUTPUT "Finished"The same in Python
# A loop inside a loop: every row is paired with every column for row in range(1, 3): # outer loop: 1, 2 for column in range(1, 4): # inner loop: 1, 2, 3 print(row, "x", column, "=", row * column) print("Finished")
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 Finished
| Row | Column | OUTPUT |
|---|---|---|
| 1 | 1 | 1 x 1 = 1 |
| 2 | 1 x 2 = 2 | |
| 3 | 1 x 3 = 3 | |
| 2 | 1 | 2 x 1 = 2 |
| 2 | 2 x 2 = 4 | |
| 3 | 2 x 3 = 6 | |
| Finished |
Example 2 · Loops, selection and totalling together
A league has 2 teams, and each plays 3 matches. Input the points for every match. For each team output its total and its highest score; then output the team with the most points. Constants make it easy to test with small numbers and scale up later.
- Start with the inner loop: one team's three matches, a total and a highest.build and test the innermost level first, as the textbook advises.
- Wrap it in the outer loop over teams, resetting
TeamTotalandTeamHighat the start of each team.otherwise team 2 would carry on from team 1's figures. - After the inner loop, compare this team with the best so far.the comparison needs the finished team total.
Cambridge pseudocode
CONSTANT NumberOfTeams ← 2
CONSTANT MatchesPerTeam ← 3
DECLARE Team, Match, Points : INTEGER
DECLARE TeamTotal, TeamHigh : INTEGER
DECLARE BestTeam, BestTotal : INTEGER
BestTeam ← 0
BestTotal ← -1
FOR Team ← 1 TO NumberOfTeams
TeamTotal ← 0
TeamHigh ← 0
FOR Match ← 1 TO MatchesPerTeam
OUTPUT "Team ", Team, ", match ", Match, " points: "
INPUT Points
TeamTotal ← TeamTotal + Points
IF Points > TeamHigh
THEN
TeamHigh ← Points
ENDIF
NEXT Match
OUTPUT "Team ", Team, " total: ", TeamTotal, " highest: ", TeamHigh
IF TeamTotal > BestTotal
THEN
BestTotal ← TeamTotal
BestTeam ← Team
ENDIF
NEXT Team
OUTPUT "Best team is ", BestTeam, " with ", BestTotal, " points"The same in Python
# Team points: nested loops with selection inside NUMBER_OF_TEAMS = 2 MATCHES_PER_TEAM = 3 best_team = 0 best_total = -1 for team in range(1, NUMBER_OF_TEAMS + 1): team_total = 0 team_high = 0 for match in range(1, MATCHES_PER_TEAM + 1): points = int(input("Team " + str(team) + ", match " + str(match) + " points: ")) team_total = team_total + points if points > team_high: team_high = points print("Team", team, "total:", team_total, "highest:", team_high) if team_total > best_total: best_total = team_total best_team = team print("Best team is", best_team, "with", best_total, "points")
Output — test data 3, 1, 3, 0, 3, 1
Team 1, match 1 points: 3 Team 1, match 2 points: 1 Team 1, match 3 points: 3 Team 1 total: 7 highest: 3 Team 2, match 1 points: 0 Team 2, match 2 points: 3 Team 2, match 3 points: 1 Team 2 total: 4 highest: 3 Best team is 1 with 7 points
| Team | Match | Points | TeamTotal | TeamHigh | BestTeam | BestTotal | OUTPUT |
|---|---|---|---|---|---|---|---|
| 0 | -1 | ||||||
| 1 | 0 | 0 | |||||
| 1 | 3 | 3 | 3 | ||||
| 2 | 1 | 4 | |||||
| 3 | 3 | 7 | Team 1 total: 7 highest: 3 | ||||
| 1 | 7 | ||||||
| 2 | 0 | 0 | |||||
| 1 | 0 | 0 | |||||
| 2 | 3 | 3 | 3 | ||||
| 3 | 1 | 4 | Team 2 total: 4 highest: 3 | ||||
| Best team is 1 with 7 points |
Notice the third match of team 1: 3 > 3 is FALSE, so TeamHigh is not changed. For team 2, 4 > 7 is FALSE, so the best team stays as team 1.
Try It Yourself 12 min
Goal: How many times is OUTPUT "*" executed? FOR A ← 1 TO 4 / FOR B ← 1 TO 5 / OUTPUT "*" / NEXT B / NEXT A. Then write it in Python and check.
Goal: For one student taking 5 tests, input each mark (0–100) and output the highest, lowest and average. Test with only 2 or 3 marks by changing a constant.
Goal: Extend the medium task to a class of students: for each student output their highest, lowest and average; at the end output the class highest, lowest and average.
Hint
The medium task becomes the inner loop. Set the student's high to 0 and low to 100 at the start of each student; set the class high, low and total once, before the outer loop. Test with 2 students and 2 tests first.
📝 Exam Practice 10 min
Define the term nesting in programming.
Mark scheme
- Placing one construct (selection / iteration) inside another construct (1).
Complete a trace table for this algorithm.
Total ← 0
FOR X ← 1 TO 3
FOR Y ← 1 TO X
Total ← Total + Y
NEXT Y
NEXT X
OUTPUT TotalMark scheme
| X | Y | Total | OUTPUT |
|---|---|---|---|
| 0 | |||
| 1 | 1 | 1 | |
| 2 | 1 | 2 | |
| 2 | 4 | ||
| 3 | 1 | 5 | |
| 2 | 7 | ||
| 3 | 10 | 10 |
- X column 1, 2, 3 (1); Y restarts at 1 for each X and goes up to X (1); Total column 1, 2, 4, 5, 7, 10 (1); output 10 (1).
Explain why the variables TeamTotal and TeamHigh in the worked example are set to 0 inside the outer loop rather than before it.
Mark scheme
- They must be reset at the start of each team (1)…
- …otherwise each team's total / highest would include the previous team's values (1).
Write pseudocode using nested loops to input the rainfall for each of 7 days in each of 4 weeks, and output the total rainfall for each week.
Mark scheme
- Outer loop for 4 weeks (1).
- Weekly total reset to 0 inside the outer loop, before the inner loop (1).
- Inner loop for 7 days with prompt and input (1).
- Totalling inside the inner loop (1).
- Output of the week's total after the inner loop, inside the outer loop (1).
🗝️ Recap & Key Terms 3 min
Nesting puts one construct inside another. The inner loop completes for every pass of the outer loop, so the inner body runs (outer × inner) times. Reset per-group values inside the outer loop, and close each block in the reverse order it was opened.
- Nesting
- The inclusion of one type of code construct inside another.
- Nested loop
- A loop inside another loop; the inner loop runs completely for each iteration of the outer loop.
- Nested selection
- An IF (or CASE) statement placed inside another IF, so a second condition is tested only on one path.
- Initialise
- To give a variable its starting value, e.g.
Total ← 0, before it is used.
Homework 1 min
Task (≤ 15 min): Write pseudocode that outputs this triangle of stars using nested loops. The number of rows (here 4) is input by the user. [4]
* ** *** ****
Model answer
DECLARE Rows, Row, Star : INTEGER
DECLARE Line : STRING
OUTPUT "How many rows? "
INPUT Rows
FOR Row ← 1 TO Rows
Line ← ""
FOR Star ← 1 TO Row
Line ← Line & "*"
NEXT Star
OUTPUT Line
NEXT RowMarks: input of rows (1); outer loop 1 to Rows (1); inner loop 1 to Row building the line (1); line reset and output inside the outer loop (1).