A program that runs but prints the wrong answer has a logic error. The computer did exactly what you wrote, and what you wrote was not what you meant.
To find it, compare the program with an answer you worked out by hand. Random edits only make it worse.
What is the predict-compare-locate routine?
- Choose a small input and work out the correct output by hand.
- Run the program, or trace it, and compare the two answers.
- Find the first line where a variable’s value differs from your hand working.
- Change that one line and test again.
Step 3 matters most. The wrong result you see on screen is the last symptom, and the cause can sit several lines earlier.
Bug one: an operator precedence slip
The task is to display the average of three marks. A student writes average ← a + b + c / 3.
Take a = 60, b = 70 and c = 80. The correct average is (60 + 70 + 80) ÷ 3 = 70.
The program divides first, because division is done before addition. So it calculates 80 ÷ 3, which is about 26.67, then adds 60 + 70 to get about 156.67.
The first line where the trace differs from the hand working is the average line itself. The fix is brackets: average ← (a + b + c) / 3.
Bug two: an off-by-one loop
The task is to add the prices in a list of 5 items: 4, 6, 3, 8 and 9. The correct total is 30.
The student writes FOR i ← 1 TO 4 and adds price[i] each time. The loop stops one item early, so the total is 4 + 6 + 3 + 8 = 21.
A trace table shows i ending at 4, while the list has 5 items. The missing 9 is the gap between 30 and 21. The fix is FOR i ← 1 TO 5.
| Symptom | Likely cause | First thing to check |
|---|---|---|
| Result is far too large or odd | Order of operations | Brackets around grouped parts |
| Result misses the last item | Loop stops early | Final loop value against list size |
| Totals grow across runs | Variable not reset | Starting value before the loop |
| Decision goes the wrong way | Wrong comparison | Whether > should be >= |
How can you practise this?
Trace a program with a table, then write the expected column next to it. The place where the two columns first differ is the bug. The restricted pseudocode trace trainer gives you programs to trace, and the mistake log records each bug by type so patterns appear.
For the language side, read distinguishing a syntax error from a logically wrong result.
A self-check
A program should output the number of marks above 50 in the list 40, 55, 50, 70. It uses IF mark >= 50 and prints 3. What is the bug, and what should it print?
The test counts 50, which is not above 50. The correct test is mark > 50, and the output should be 2, from 55 and 70.
When is one-to-one tuition worth considering?
When the same kind of slip keeps returning across different programs, a teacher can watch you trace and point to the habit, such as skipping the start row. That pattern is hard to see on your own.
You can try this in the one-hour trial class (from RM50), a taught lesson. See also online one-to-one Computer Science tuition.