Tracing Method

Pseudocode Tracing Method

Do not solve pseudocode by intuition. Use trace tables.

Standard trace table

Use this layout:

Step | i | j | x | y | condition | output

Only track variables that change.

Method

  1. Read full code once.
  2. Identify variables and initial values.
  3. Identify loop condition.
  4. Trace each iteration.
  5. Stop exactly when condition fails.
  6. Write final output.

Example 1: Simple loop

SET x = 1
SET sum = 0
WHILE x <= 5
    SET sum = sum + x
    SET x = x + 1
END WHILE
DISPLAY sum

Trace:

Iteration x before sum after x after
1 1 1 2
2 2 3 3
3 3 6 4
4 4 10 5
5 5 15 6

Output: 15

Example 2: Update order

SET a = 2
SET b = 3
SET a = a + b
SET b = a - b
DISPLAY a, b

Trace:

  • initially a=2, b=3
  • a = 2+3 = 5
  • b = 5-3 = 2

Output: 5, 2

Common mistake: using old value of a after it has changed.

Example 3: Integer division

SET x = 17
SET y = x / 5
SET z = x % 5
DISPLAY y, z

If integer division is used:

  • 17 / 5 = 3
  • 17 % 5 = 2

Output: 3, 2

Example 4: WHILE vs REPEAT UNTIL

SET x = 10
WHILE x < 5
    DISPLAY x
END WHILE

Output: nothing.

SET x = 10
REPEAT
    DISPLAY x
UNTIL x < 5

Output: 10 once, because repeat-until executes before checking.

Fast error checklist

Before selecting answer:

  • Did the loop include last value?
  • Was division integer?
  • Was variable updated before display?
  • Did AND/OR change the condition?
  • Did array index start at 0 or 1?
  • Was the recursive base case reached?