Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This program should show the sum of the numbers 1 to 4, which is 10. It shows 4.
Say why, with a trace table, and write the right program.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Make a trace table, with a row for each round.
| Round | i | total after total = 0 | total after the addition |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 2 | 0 | 2 |
| 3 | 3 | 0 | 3 |
| 4 | 4 | 0 | 4 |
The line total = 0 is inside the loop, so the total is reset to 0 in every round. At the end only the last number is left, and the program shows 4.
The fix. Move the starting line before the loop, so that it runs only once.
Check. The totals are now 1, 3, 6 and 10, and the program shows 10.
Answer: The program shows 4 because total = 0 is inside the loop. Put it before the loop.
Log in to join the discussion.
Loading…