Trace tables and correcting algorithms

Computer Science · Algorithm design and problem-solving. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

A trace table records a dry run: you work through an algorithm by hand, one line at a time, and write down every change. The table has one column for each variable and one for the output. A new value is written only when a variable changes.

Tracing shows what an algorithm really does, so it is also the way to find errors. Most errors in exam algorithms are small: a variable set to its starting value in the wrong place, a wrong comparison such as < where <= is needed, AND mixed up with OR, or a loop that runs one time too many or too few.

Do not guess the result from what the algorithm looks like it should do. Follow the lines exactly.

In simpler words

A trace table helps you follow an algorithm by hand, one line at a time. Each variable gets a column. You write a new value only when it changes. This shows what the algorithm really does, so it helps you find mistakes. Common mistakes are a wrong comparison sign, mixing up AND and OR, or a loop that runs once too often.

An everyday comparison

A trace table is like following a recipe step by step and writing down the contents of each bowl after every step, rather than guessing what the cake will look like. If the cake is wrong, your notes show exactly which step caused it. The comparison stops working because a computer follows the instructions with total precision, with no common sense to fix small errors.

Rules to remember

Common mistake

Students stop tracing one pass too early or too late. Test the loop condition with the new values every time, and remember that the variable may change once more after the value you expected.

In the exam

Set up one column per variable and one for output, in the order they appear. Follow each line exactly, writing values only when they change, and test the loop condition with the new values every time. When correcting an algorithm, identify the line number, state the error, and write the corrected line in full, such as changing < to <=. Do not rewrite the whole algorithm.

Worked example

What is output by this algorithm?
N ← 13
Count ← 0
WHILE N > 1 DO
    N ← DIV(N, 2)
    Count ← Count + 1
ENDWHILE
OUTPUT Count

  1. Start: N = 13, Count = 0. 13 > 1 is true, so N = DIV(13, 2) = 6 and Count = 1.
  2. 6 > 1 is true, so N = DIV(6, 2) = 3 and Count = 2.
  3. 3 > 1 is true, so N = DIV(3, 2) = 1 and Count = 3.
  4. 1 > 1 is false, so the loop stops.

Answer: The output is 3.

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Validation, verification and test dataVariables, data types and operators →Take a Computer Science test