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 average of the even numbers in the list. For [3, 8, 4, 7, 6] the expected answer is 6.0. It shows 3.6. Find the fault with a trace table.
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. The expected answer: the even numbers are 8, 4 and 6, with total 18 and count 3. So 18 divided by 3 is 6.0.
Follow the program.
n | even? | total | count |
|---|---|---|---|
| 3 | no | 0 | 1 |
| 8 | yes | 8 | 2 |
| 4 | yes | 12 | 3 |
| 7 | no | 12 | 4 |
| 6 | yes | 18 | 5 |
At the end, total is 18 (correct), but count is 5. The line count = count + 1 is outside the if, so it counts every number and not only the even ones. The program shows 18 divided by 5, which is 3.6, the wrong answer that was reported.
The fix. Indent count = count + 1 so that it is inside the if.
Check. Now count is 3, and the average is 6.0.
Answer: The counter must be inside the if. Then the average is 6.0.
Log in to join the discussion.
Loading…