Trace a Program
Tracing means running code on paper: follow each line and write variable values in a table until the program stops.
- Build a trace table with columns for each variable
- Update values line by line without skipping
- Find the line where output first goes wrong
Finish first
Topic contents
Lesson 1 of 3
Paper computer
When a program misbehaves, guessing is slow. Tracing is pretending you are the computer. You read one line, change variables, then move to the next line.
A trace table has a row per line and columns for each variable plus any output. Write the starting values before line one runs.
Open the trace table lab. Step through a short program and watch the table fill automatically. Then try predicting the next row before you click.
Trace table
Step through a short program and watch variables update row by row. Predict the next state before you advance.
Trace the program
Variables on paper, line by line| Line | Code | x | y |
|---|---|---|---|
| 1 | x = 3 | 0 | 0 |
| 2 | y = 5 | 0 | 0 |
| 3 | x = x + y | 0 | 0 |
| 4 | y = x - 2 | 0 | 0 |
| 5 | print x | 0 | 0 |
Start
Tracing means running the program on paper. Write the value of each variable after every line. Computers do exactly this, just faster.
Lesson 2 of 3
Loops and choices in a table
When a loop runs, you may visit the same line many times. Add a new row each time that line executes, even if the line number repeats.
For an if statement, check the condition first. Only follow the branch that is true. Cross out the branch you skip so you do not drift.
The first row where reality diverges from your expectation is near the bug. Fix the plan there, not at the final wrong print.
Lesson 3 of 3
Tracing before coding
Experienced programmers still trace tricky parts on paper or in a debugger. The habit saves hours of random edits on homework and projects.
Start with tiny programs: ten lines, two variables. Master those before tracing nested loops in homework.
Next you will solve mazes by trying a path, backing up when blocked, and trying another. That is backtracking.
Practice
Work these out yourself
No answer key here on purpose: these are the questions worth thinking through before you move on. Open one and work it out.
0/3 attemptedAssessment
Check your understanding
Answer each question, then read the explanation. That is where the learning is.
Finished this topic?
0 of 3 lessons marked done. Marking the topic complete ticks the rest.
