Year 8 Computing — Tracing a loop with a total
Trace a loop that keeps a running total, and say what the total holds once the loop has finished.
Name: ________________________
1.A program says: set total to 1; repeat 4 times: double total. What does total hold at the end?
2.A program says: set total to 0; repeat 5 times: add 2 to total. After the loop has finished, it prints total once. How many numbers appear on the screen?
- a) None
- b) Five
- c) Ten
- d) One
3.A program says: set total to 0; repeat 4 times: add 3 to total. Someone answers 3, because 3 was the last thing added. What is wrong with that?
- a) The total keeps everything added before it, so it comes to 12
- b) Nothing is wrong — 3 is right
- c) The loop only ever runs once
- d) The total starts again from nothing each time round
4.A program says: set total to 0; repeat 5 times: add 2 to total and then print total. How many numbers appear on the screen?
5.Each of these programs starts with total holding 0. Match each loop to the total it finishes with.
- repeat 3 times: add 4 to total
- repeat 5 times: add 4 to total
- repeat 4 times: add 9 to total
- repeat 6 times: add 5 to total
- repeat 2 times: add 25 to total
- 50
- 36
- 12
- 20
- 30
6.A program says: set total to 2; repeat 5 times: add 6 to total. What does total hold at the end?
7.A program says: set total to 100; repeat 5 times: take 8 away from total. What does total hold at the end?
8.Each of these programs starts with total holding 0. Sort each loop by whether it finishes with total above 30.
Groups: Above 30 · 30 or below
- repeat 2 times: add 8 to total
- repeat 5 times: add 4 to total
- repeat 4 times: add 9 to total
- repeat 3 times: add 5 to total
- repeat 8 times: add 5 to total
- repeat 7 times: add 6 to total
Answer key — Year 8 Computing — Tracing a loop with a total
- 1. 16
- 2. d) One
- 3. a) The total keeps everything added before it, so it comes to 12
- 4. 5
- 5. repeat 3 times: add 4 to total → 12; repeat 5 times: add 4 to total → 20; repeat 4 times: add 9 to total → 36; repeat 6 times: add 5 to total → 30; repeat 2 times: add 25 to total → 50
- 6. 32
- 7. 60
- 8. repeat 4 times: add 9 to total → Above 30; repeat 3 times: add 5 to total → 30 or below; repeat 8 times: add 5 to total → Above 30; repeat 2 times: add 8 to total → 30 or below; repeat 7 times: add 6 to total → Above 30; repeat 5 times: add 4 to total → 30 or below