Computer Science
Dry-Running

Trace tables are used by programmers to track the values of variables as they change throughout the program. This is useful when a program is not producing the desired result.

Look at the following program extract. The program is supposed to calculate the sum of the squares of a series of numbers entered by the user. The user enters -1 when they have reached the end of their list of numbers.

n:= 0;
total:= 0;
while n<>-1 do
begin
   write('Please enter a number');
   readln(n);
   total:= total + n * n;
end;
writeln('Total= ', n:8:2);

Assume that the following order of input is used - 2, 5, 3, 1, -1.

To find out why this program is not working, first work out what the expected result should be.

To make a trace table, we write out the variables used in the program and any expressions that are evaluated by ifs or whiles. We read the program, line by line, writing in the values as they are set and only write information into the table when it changes.

Copy and complete the table to show what this code actually produces. Explain the nature of the problem.

n n * n total n <> -1
0 0 True
2 4 4 True

Another Algorithm

x ← 4
y ← 3
Result
Repeat
   Result ← Result * x
   y ← y - 1
Until y = 0
x y Result
4 3 1