AP® Computer Science Principles · Big Idea 1 · Topic 1.4
Debugging by Tracing and Isolating a Bug
Debugging by tracing means stepping through code one line at a time, writing down what each variable actually equals, until the value stops matching what you expected.
Staring at code tests whether it looks right. Tracing tests whether it is right, by forcing you to compute what the computer computes, line by line. You write down every variable and update it after each statement, the same way the machine would. The moment a variable holds a value you didn't expect, you've found the line that broke it, not just the symptom you saw at the end.
For long programs, checking every single line is slow, so isolate instead of tracing all of it. Pick the midpoint of the code and display a variable's value there. If it's already wrong, the bug is somewhere in the first half; if it's still right, the bug is in the second half. Repeat inside whichever half is now suspect, checking its midpoint next. Each check cuts the remaining suspect region in half, so a bug among 1000 lines is found in about ten checks instead of 1000.
This connects directly to inputs and outputs: a bug often only appears for certain inputs, so testing with several different inputs, including edge cases like zero or a single-item list, is what reveals it in the first place. Once an input triggers the wrong output, tracing and isolating tell you exactly which line is responsible. Together these are the core loop of real development: run it, notice it's wrong, trace or isolate to find why, fix the line, run it again.
Key terms
- Tracing
- Manually stepping through code line by line and recording the value of each variable as it changes.
- Isolating a bug
- Narrowing down which section of code causes an error by repeatedly checking the midpoint of the remaining suspect region.
- Accumulator
- A variable that starts at an initial value and builds up a running total as a loop repeats.
- Edge case
- An unusual or extreme input, like zero or an empty list, that often reveals bugs other inputs miss.
Watch it explained
- How it worksWalk me through hand tracing a five line program and watching every variable change.
- How it worksHow does cutting a program in half again and again narrow a bug down to a single line?
- Worked exampleTrace a loop meant to sum 1 through 5 that returns 10 instead, and find where it goes wrong.
- Going furtherWhat changes about debugging when the bug shows up for only one specific input?
Check yourself
End of topic.