Class 7 Computer Science — 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 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
2.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) Nothing is wrong — 3 is right
- b) The total starts again from nothing each time round
- c) The total keeps everything added before it, so it comes to 12
- d) The loop only ever runs once
3.A program says: set total to 0; repeat 7 times: add 3 to total. What does total hold at the end?
4.A program says: set total to 1; repeat 4 times: double total. What does total hold at the end?
5.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 5 times: add 4 to total
- repeat 3 times: add 5 to total
- repeat 7 times: add 6 to total
- repeat 2 times: add 8 to total
- repeat 4 times: add 9 to total
- repeat 8 times: add 5 to total
6.Put these lines in the order that adds 5 to a total three times over and then shows the result.
- repeat 3 times
- print total
- add 5 to total
- set total to 0
7.A program says: set total to 100; repeat 5 times: take 8 away from total. What does total hold at the end?
8.A program says: set total to 2; repeat 5 times: add 6 to total. What does total hold at the end?
Answer key — Class 7 Computer Science — Tracing a loop with a total
- 1. d) One
- 2. c) The total keeps everything added before it, so it comes to 12
- 3. 21
- 4. 16
- 5. 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
- 6. 1. set total to 0 2. repeat 3 times 3. add 5 to total 4. print total
- 7. 60
- 8. 32