Unit 11.1B · Term 1

Trace Tables

A trace table is a technique for tracking the values of variables as a program executes, line by line. It is the most reliable way to verify an algorithm works correctly — or to find bugs.

Learning Objectives

  • 11.5.1.4 Use trace tables to verify algorithms and predict outputs

Lesson Presentation

11.1B-trace-tables.pdf · Slides for classroom use

Conceptual Anchor

The Detective Analogy

A trace table is like a detective's evidence log. For every step the suspect (program) takes, you record what changed. At the end, you can see the full journey and verify if the outcome matches expectations — or find where things went wrong.

Rules & Theory

How to Build a Trace Table

Step Action
1 Create a column for each variable + one for output
2 Add a row for each line that changes a variable
3 Execute each line mentally, recording new values
4 Leave cells empty if a variable doesn't change
5 For loops, add a new row for each iteration

Worked Examples

1 Trace: Find the Sum of 1 to 5

// Pseudocode: sum ← 0 FOR i ← 1 TO 5 sum ← sum + i ENDFOR OUTPUT sum Trace Table: Step │ i │ sum │ Output ──────┼─────┼─────┼──────── 1 │ — │ 0 │ — 2 │ 1 │ 1 │ — 3 │ 2 │ 3 │ — 4 │ 3 │ 6 │ — 5 │ 4 │ 10 │ — 6 │ 5 │ 15 │ — 7 │ — │ — │ 15

2 Trace: Swap Two Variables

// Pseudocode: a ← 7 b ← 3 temp ← a a ← b b ← temp OUTPUT a, b Trace Table: Step │ a │ b │ temp │ Output ──────┼─────┼─────┼──────┼──────── 1 │ 7 │ — │ — │ — 2 │ 7 │ 3 │ — │ — 3 │ 7 │ 3 │ 7 │ — 4 │ 3 │ 3 │ 7 │ — 5 │ 3 │ 7 │ 7 │ — 6 │ — │ — │ — │ 3, 7

3 Trace: Find Maximum in Array [4, 9, 2, 7]

// Pseudocode: arr ← [4, 9, 2, 7] max ← arr[0] FOR i ← 1 TO 3 IF arr[i] > max THEN max ← arr[i] ENDIF ENDFOR OUTPUT max Trace Table: Step │ i │ arr[i] │ max │ Output ──────┼─────┼────────┼─────┼──────── 1 │ — │ — │ 4 │ — 2 │ 1 │ 9 │ 9 │ — (9>4 ✓) 3 │ 2 │ 2 │ 9 │ — (2>9 ✗) 4 │ 3 │ 7 │ 9 │ — (7>9 ✗) 5 │ — │ — │ — │ 9

Common Pitfalls

Skipping Iterations

Every loop iteration needs its own row — even if no variable changes. If an IF condition is false, you still need to show that the step was checked.

Overwriting Old Values

Each row shows the new value of a variable. The old value is in the previous row. Never erase previous rows — the history is the whole point!

Tasks

Apply

Create a trace table for: x ← 10, WHILE x > 0: OUTPUT x, x ← x - 3.

Apply

Trace the following and find the output: a ← 1, FOR i ← 1 TO 4: a ← a * 2.

Analyze

A student claims this code finds the minimum of an array. Use a trace table with [5, 2, 8, 1] to verify or disprove their claim.

Self-Check Quiz

Q1: What is the purpose of a trace table?

To track variable values line-by-line to verify an algorithm works correctly or to find bugs.

Q2: What should each column represent?

Each column represents a variable in the program, plus an output column.

Q3: How many rows does a loop with 5 iterations need?

At least 5 rows (one per iteration), plus rows for initialisation and output.