Class 8 Computer Science — 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. What is total at the end?
total = 0 for a in range(1, 4): for b in range(1, 4): total = total + a * b2.Follow this code by hand. What is the second number it prints?
for a in range(1, 4): for b in range(1, 4): print(a * 10 + b)3.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 b
- b) The line printing a
- c) The line printing 0
- d) The heading of the inner loop
4.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
- 21
- 18
- 8
- 10
- 12
5.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 stays exactly the same
- b) It goes up by one
- c) It doubles
- d) It goes up by the number of trips the outer loop makes
6.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)7.Follow this code by hand. What is count at the end? Notice that the inner range depends on the outer counter.
count = 0 for row in range(1, 5): for star in range(1, row + 1): count = count + 18.In each of these, one loop sits inside another with a single line at the deepest level. Sort each one by how many times that line runs.
Groups: Eight times · Fifteen times
- range(0, 5) outside, range(0, 3) inside
- range(1, 3) outside, range(1, 5) inside
- range(3, 8) outside, range(4, 7) inside
- range(2, 6) outside, range(3, 5) inside
- range(1, 6) outside, range(2, 5) inside
- range(4, 8) outside, range(1, 3) inside
Answer key — Class 8 Computer Science — Loops inside loops
- 1. 36
- 2. 12
- 3. a) The line printing b
- 4. 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
- 5. d) It goes up by the number of trips the outer loop makes
- 6. 12
- 7. 10
- 8. range(2, 6) outside, range(3, 5) inside → Eight times; range(1, 6) outside, range(2, 5) inside → Fifteen times; range(1, 3) outside, range(1, 5) inside → Eight times; range(0, 5) outside, range(0, 3) inside → Fifteen times; range(4, 8) outside, range(1, 3) inside → Eight times; range(3, 8) outside, range(4, 7) inside → Fifteen times