Although we are required to write our own algorithms, an important part of learning programming is to be able to read and understand code that other people have written.
Trace tables allow us to run an algorithm before it is coded by recording the value of each variable into a table each time it changes. This process is often called dry running or finger tracing an algorithm.
In the example below, we have been given an algorithm, a trace table, and a question asking is to identify the purpose. By completing the trace table we are able to spot patterns in what is happening to the variables.
For more complex algorithms that include iteration and outputs it’s important to remember that we record the data held by variables in the table from left to right. If a variable’s value doesn’t change, then there is no need to record it again in the table. If a variable in the column to the left changes, then we would move down onto the next line of the table.
In the example below, a FOR loop is used to change the value of the variables in the algorithm. The count controller in this case is called i, and the value of that variable is recorded in the column with the heading of i.
You can see that the values of low and high don’t change in every row so where they are not changed we simply leave that cell of the column blank.
Try for yourself using the question below:
Design and complete a trace table for the algorithm shown below using the input of 47:
total = 128
s = ""
num = INPUT
WHILE total >= 1 DO
IF num >= total THEN
s = s + "1"
num = num - total
s = s + "0"
total = total / 2
Describe the purpose of the algorithm above.
The algorithm calculates an a bit binary number using the number input by the user.