You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers how trace tables are used as a debugging tool, as required by OCR J277 Section 2.4. While trace tables were introduced in the Algorithms section for following algorithm execution, this lesson focuses specifically on using trace tables to find and fix bugs — particularly logic errors — in programs.
Logic errors do not cause error messages — the program runs but produces the wrong output. Trace tables allow you to systematically track variable values at each step, making it possible to pinpoint exactly where the logic goes wrong.
The debugging process with trace tables:
OCR Exam Tip: Trace table questions for debugging will typically show code with a logic error and ask you to complete the trace table, identify the error, and suggest a fix. These questions are worth 4–6 marks and test multiple skills at once.
Buggy code — supposed to calculate the sum of numbers from 1 to 5:
total = 0
for i = 1 to 4
total = total + i
next i
print(total)
Trace table:
| Step | i | total | Output |
|---|---|---|---|
| Init | - | 0 | |
| 1 | 1 | 1 | |
| 2 | 2 | 3 | |
| 3 | 3 | 6 | |
| 4 | 4 | 10 | 10 |
Expected output: 15 (1+2+3+4+5=15) Actual output: 10
The bug: The loop goes from 1 to 4 instead of 1 to 5. The number 5 is never added.
The fix: Change for i = 1 to 4 to for i = 1 to 5.
Buggy code — supposed to calculate the average of three scores:
score1 = 80
score2 = 70
score3 = 90
total = score1 + score2 + score3
average = total * 3
print("Average: " + str(average))
Trace table:
| Step | score1 | score2 | score3 | total | average | Output |
|---|---|---|---|---|---|---|
| Init | 80 | 70 | 90 | - | - | |
| 1 | 80 | 70 | 90 | 240 | - | |
| 2 | 80 | 70 | 90 | 240 | 720 | "Average: 720" |
Expected output: "Average: 80" Actual output: "Average: 720"
The bug: average = total * 3 should be average = total / 3. Multiplication instead of division.
The fix: Change * to /.
Buggy code — linear search that should find and count occurrences:
data = [3, 7, 3, 5, 3, 8]
target = 3
count = 1
for i = 0 to data.length - 1
if data[i] == target then
count = count + 1
endif
next i
print("Found " + str(count) + " times")
Trace table:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.