Year 9 Computing — Loops inside loops
Work out how many times the body of a loop inside another loop runs, and in what order the two counters change.
Name: ________________________
1.Follow this code by hand. How many times does the most deeply indented line run?
for a in range(1, 4): for b in range(1, 5): print(a * b)2.Follow this code by hand. What is count at the end?
count = 0 for a in range(1, 5): for b in range(1, 6): count = count + 13.Follow this code by hand. How many numbers does it print?
for a in range(1, 3): for b in range(1, 3): print(b)4.In this program, which line runs the greatest number of times?
for a in range(1, 6): print(a) for b in range(1, 4): print(b) print(0)- a) The line printing 0
- b) The line printing a
- c) The line printing b
- d) The heading of the inner loop
5.Follow this code by hand. What is total at the end?
total = 0 for a in range(1, 4): for b in range(1, 4): total = total + a * b6.Follow this code by hand. How many numbers does it print altogether?
for a in range(1, 4): print(a) for b in range(1, 3): print(b)7.A loop sits inside another loop. The inner range is made one longer while the outer range is left exactly as it was. What happens to the number of times the deepest line runs?
- a) It goes up by the number of trips the outer loop makes
- b) It goes up by one
- c) It stays exactly the same
- d) It doubles
8.In each of these, one loop sits inside another with a single line at the deepest level. Match each pair of ranges to how many times that line runs.
- range(1, 3) outside, range(1, 6) inside
- range(1, 4) outside, range(1, 8) inside
- range(1, 5) outside, range(1, 3) inside
- range(2, 5) outside, range(1, 5) inside
- range(1, 10) outside, range(1, 3) inside
- 18
- 12
- 10
- 21
- 8
Answer key — Year 9 Computing — Loops inside loops
- 1. 12
- 2. 20
- 3. 4
- 4. c) The line printing b
- 5. 36
- 6. 9
- 7. a) It goes up by the number of trips the outer loop makes
- 8. range(1, 3) outside, range(1, 6) inside → 10; range(1, 4) outside, range(1, 8) inside → 21; range(1, 5) outside, range(1, 3) inside → 8; range(2, 5) outside, range(1, 5) inside → 12; range(1, 10) outside, range(1, 3) inside → 18