Exam-style question
Try this first
Consider this pseudocode: number <- 2 total <- 0 WHILE number <= 8 total <- total + number number <- number + 2 END WHILE OUTPUT total Hand-trace the algorithm, state its output, and convert it into Python. Then give one test input or test case and explain how logical reasoning and user feedback could be used when arguing that the resulting program is correct and efficient.
Model answer
What a good answer should say
- Trace: | Iteration | number before iteration | total after addition | number after increment | |---|---:|---:|---:| | 1 | 2 | 2 | 4 | | 2 | 4 | 6 | 6 | | 3 | 6 | 12 | 8 | | 4 | 8 | 20 | 10 | When number is 10, the condition number <= 8 is false, so the output is 20.
- Python conversion: number = 2 total = 0 while number <= 8: total = total + number number = number + 2 print(total) A suitable test case is the given starting values, which should produce 20.
- The trace provides logical evidence that the values 2, 4, 6 and 8 are each added once and that the loop stops afterwards.
- The algorithm is efficient for this task because it performs one loop iteration for each value that must be added and does not repeat an iteration unnecessarily.
Explanation
Why this works
A hand trace records changing values after each step and exposes the final output. The Python version preserves the sequence, assignments, selection condition in the while loop, and iteration.
Correctness can be supported by tracing and suitable test data, while user feedback can check whether the program's behaviour and output meet the user's expectations.
Common mistake
No common mistake is linked to this question yet.
