Trace tables and finding errors in algorithms
A trace table records the values of the variables and the output as you work through an algorithm by hand, one step at a time. This is called a dry run. It shows what an algorithm does, and where it goes wrong.
Filling in a trace table
- Give each variable its own column, plus one column for output.
- Work through the algorithm one line at a time, exactly as written, not as you think it was meant to work.
- Write a variable’s new value in its column whenever it changes, moving down a row as the algorithm moves on, usually each time round a loop.
- Only write in a column when that value changes. Leave the other cells empty.
- Write down every OUTPUT, in the order it happens.
Working out what an algorithm does
After a trace, describe the purpose in terms of the problem, not the code. “It outputs the largest of the numbers entered” earns more than “it compares Number with Max”. Look for the standard patterns: a total, a count, a maximum, a search.
Finding and fixing errors
Questions often give an algorithm with a few errors and ask you to find and correct them. Trace it with simple data and compare what happens with what should happen. The usual errors are:
- a variable not set to its starting value, or set inside the loop instead of before it;
- the wrong comparison, such as > instead of >=, or < instead of >;
- a loop that runs one time too many or too few;
- the wrong variable being updated or output;
- something done inside the loop that belongs after it.
Where marks go
- Filling in values you expect instead of what the algorithm actually does.
- Repeating unchanged values in every row, which makes the table hard to follow and easy to get wrong.
- Missing an OUTPUT, or writing outputs in the wrong order.
- Stating an error without giving the corrected line of code.
- Describing the purpose line by line instead of saying what the algorithm is for.
Try a question
6 MARKS · MARKED ON THIS PAGEA darts club uses the algorithm shown to find the best score in a session. The value -1 is entered to stop. Complete the trace table using the input data 34, 51, 47, 60, -1. The first row shows the starting value of Highest. Each later row shows the value of Score just read by INPUT and the value of Highest after that score has been dealt with; on the last row (Score -1) write the value of Highest when the loop ends. Write a value in every blank Highest cell, even if it has not changed. Write the output exactly as it would be displayed.
01 Highest <- 0 02 INPUT Score 03 WHILE Score <> -1 DO 04 IF Score > Highest 05 THEN 06 Highest <- Score 07 ENDIF 08 INPUT Score 09 ENDWHILE 10 OUTPUT "Best: ", Highest
Fill in your answer first.