What is a trace table?
A trace table is a record of what happens inside a program as it runs, line by line. You pretend to be the computer: you execute each statement by hand and write down the value of every variable each time it changes, the result of every condition you test, and anything that is output.
Each row is one moment in time (one line being executed). Each column is one variable, one condition, or the output. Reading down a column shows you how a variable's value evolves; reading across a row shows the whole state of the program at that instant.
A tiny example
Trace this program. There are two variables, a and b, and one output.
Its trace table
| Line | a | b | Output |
|---|---|---|---|
| 1 | 4 | ||
| 2 | 12 | ||
| 3 | 16 | ||
| 4 | 16 |
Notice: on line 2, a has not changed, so its cell is left blank. A blank cell means "same value as the row above".
The rules we use on this page
- One row per line executed that changes a variable, tests a condition, or produces output. Lines like
next i,endwhile,elseandendifdo nothing on their own, so they get no row. - Only write a value when it changes. Leave the cell blank if the variable keeps its value. (Writing the unchanged value again is not wrong — it is just slower.)
- A
forline is where the loop variable gets its value. Each time the loop comes round, recordfor i = 1 to 4as a row with the new value ofi. - Conditions (
while,if) get their own column. WriteTrueorFalseeach time the condition is tested — including the final test that makes awhileloop stop. - Output goes in the last column, exactly as it would appear on screen. Text output is written without quotes.
- Use the current values. In
y = x - y, use the value ofxas it is now — if an earlier line changed it, use the new value.
while loop one iteration too early or too late (always test the condition one last time); using an old value of a variable after it has been reassigned; writing "even" with quotes in the output column; and forgetting that MOD gives the remainder (7 MOD 2 = 1) while DIV gives the whole-number quotient (7 DIV 2 = 3).
Ready? Head to the to see a full loop traced step by step.
Worked example: tracing a loop
Press Next step to execute one line at a time. The yellow pointer shows the line being run; the table fills in as we go, and the box underneath explains the decision being made.
| Line | total | i | Output |
|---|
What to take away
- The
forline appeared three times in the Line column — once for each value ofi. Thenext iline never appeared. totalonly got a cell when line 3 actually changed it.- The output came last and went in its own column, with no quotes.
Now try it yourself:
Tip: type a line number in the Line column and the pointer will jump to that line. Press Tab to move across the row.
Blank cells mean "unchanged from the row above". Write True/False for conditions. Output text goes without quotes.