Following a program step by step
To trace a program means to follow its instructions one at a time and keep track of what changes. You can do this with a pencil before running the program. Tracing is useful when an answer surprises you.
Keep a score sheet
Imagine recording a team’s score after every round. You cross out the old score and write the new one. A trace table does the same for a program’s variables.
Make one column for each value you want to follow. Add a row whenever an instruction changes it. A blank entry means “not created yet,” not zero.
Trace some coins
# language: en
let coins = 3
set coins = coins + 2
let reward = coins * 2
set coins = 0
say reward
say coins
Read the right side of an assignment using the values that exist at that moment. Then store the result on the left.
| After this instruction | coins |
reward |
|---|---|---|
Create coins |
3 | Not created |
| Add 2 | 5 | Not created |
Create reward |
5 | 10 |
Set coins to zero |
0 | 10 |
Predict, then run
Does the reward become zero when the coins become zero?
10
0
No. reward was calculated from the earlier value of coins. It remembers the resulting number, not a formula that keeps recalculating itself. Shared lists and maps need a different explanation; this example uses only numbers.
Your challenge
Move set coins = 0 to just before let reward = coins * 2. Make a fresh trace table and predict both output lines. Then run the changed version to check your prediction.
A common mistake
Skipping over a line because it looks unimportant can hide the cause of a bug. Include every assignment in your table. If you get lost in a loop, trace just its first two rounds before trying all of them.
You can also add temporary say statements to show intermediate values. Give those messages a clear label so you know what you are looking at.
