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.
while n<>-1 do
write('Please enter a number');
total:= total + n * n;
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|
x ← 4
y ← 3
Result ← Result * x
y ← y - 1
Until y = 0