AP Computer Science Principles · Unit 1 lecture · Part 10 of 11 · 8 min

1.4 Finding and fixing errorsTracing, extra output, and other bug-hunting tools

Mr. Thompkins
A test tells you a bug exists. It doesn't tell you where. For that you need tools, and the best one costs nothing: a pencil.

The course lists five effective ways to find and correct errors: test cases, hand tracing, visualizations, debuggers, and adding extra output statements. Test cases show that something is wrong. The others help you find exactly where the program goes off course.

TechniqueWhat you doBest for
Test casesRun chosen inputs, compare expected and actualFinding that a bug exists
Hand tracingFollow the code on paper, one row per stepSeeing exactly where values go wrong
Extra output statementsAdd DISPLAY lines to show values as it runsWatching a loop from inside
VisualizationsDraw or chart what the program producesSpotting odd patterns at a glance
DebuggersPause the program and step line by lineBig programs and tricky loops
Five bug-hunting techniques, and what each is best for.
?Wait, what's a trace table?
A trace table is how you hand trace: one column per variable (plus columns for conditions or output), and one row per step or loop pass. You fill it in exactly as the computer would, without guessing. It turns "I think it does this" into "here is what it does."

Let's hunt a real bug. This procedure is supposed to return the average of only the positive numbers in a list. For [4, -2, 8], the positives are 4 and 8, so the answer should be 12 ÷ 2 = 6. It returns 4. Something is off, and a test case has told us so. Now we trace.

1PROCEDURE avgPositive(nums)2{3  total ← 04  count ← 05  FOR EACH n IN nums6  {7    IF (n > 0)18    {9      total ← total + n110    }11    count ← count + 1212  }13  RETURN(total / count)14}15DISPLAY(avgPositive([4, -2, 8]))
  1. line 7-9 Only positive numbers are added
  2. line 11 But every number is counted
output › 4 (it should be 6)
Supposed to average only the positive numbers.
?Wait, what does FOR EACH do?
FOR EACH n IN nums runs the code in its braces once for every element of the list, in order, with n set to that element. For [4, -2, 8], the body runs three times: with n = 4, then -2, then 8.
nn > 0?totalcount
start00
4true41
-2false42
8true123
The trace table. Look at the -2 row: total stays 4, but count still goes up.

The trace shows it immediately. When n is -2, the IF correctly skips the addition, but count ← count + 1 sits outside the IF, so it runs for every number. The procedure divides the sum of the positives, 12, by the count of all the numbers, 3. The fix is to move count ← count + 1 inside the IF, so it only counts the numbers it adds.

If you couldn't trace on paper, extra output statements would find it too: put DISPLAY(total) and DISPLAY(count) inside the loop, run it, and you'd see "4 1, 4 2, 12 3" scroll by. As soon as count reads 2 while total is still 4, you know where to look. Delete those extra lines once the bug is fixed. A debugger does the same thing more comfortably: it pauses the program and lets you step through it one line at a time, watching every variable.

Pause and think
After the fix, what does avgPositive return for [-1, -3]?
I thought about it. Show me
Neither number is positive, so total and count both stay 0, and the procedure would compute 0 ÷ 0. That's a run-time error. Fixing one bug and then testing an unusual input revealed a second one.
Trace, fix, and retest
Fix avgPositive completely: (a) make it return 6 for [4, -2, 8], (b) make it safe for a list with no positive numbers, (c) choose three test cases that show the fixed procedure works.
1PROCEDURE avgPositive(nums)2{3  total ← 04  count ← 05  FOR EACH n IN nums6  {7    IF (n > 0)8    {9      total ← total + n10      count ← count + 1111    }12  }13  IF (count = 0)214  {215    RETURN(0)216  }217  RETURN(total / count)18}
  1. line 10 Moved inside the IF: count only positives
  2. line 13-16 No positives at all? Do not divide by 0
The fixed procedure. Both changes are marked.
  1. (a) Move count ← count + 1 inside the IF, right after total ← total + n. Retrace [4, -2, 8]: total 4, count 1; skip -2; total 12, count 2. It returns 12 ÷ 2 = 6.
    Why?
    Now count only counts the numbers that were added.
  2. (b) Before dividing, check: IF (count = 0) { RETURN(0) }. With no positives, it returns 0 instead of dividing by zero.
    Why?
    This guard handles the unusual input. The program's requirements decide what to return; 0 is a reasonable choice.
  3. (c) Tests: [4, -2, 8] expects 6 (mixed signs). [5] expects 5 (one element). [-1, -3] expects 0 (no positives). Each shows a different outcome, and the last is an extreme case.
    Why?
    Good tests cover each kind of outcome and the unusual inputs.

Answer: Move count inside the IF and add a count = 0 guard before dividing. Tests: [4, -2, 8] gives 6, [5] gives 5, [-1, -3] gives 0.

Stuck? Get a hint
  1. Which line runs for every element, even the ones the IF skips?
  2. What happens to total ÷ count when count is 0?
  3. Pick tests with different outcomes: mixed, single element, no positives.
Check yourself
This code segment is intended to count how many values in temps are at least 90. It displays 3 for temps ← [85, 92, 90, 71]. Which change fixes it?
count ← 1
FOR EACH t IN temps
{
  IF (t ≥ 90)
  {
    count ← count + 1
  }
}
DISPLAY(count)
  1. AChange t ≥ 90 to t > 90
  2. BChange count ← 1 to count ← 0
  3. CMove DISPLAY(count) inside the loop
  4. DChange count ← count + 1 to count ← count + t
Show the answer

B. Two values, 92 and 90, are at least 90, so the answer should be 2. The count starts at 1 instead of 0, so every answer is one too high. Changing ≥ to > would make it display 2 for this list, but only by accident: it would then wrongly skip 90. Tracing shows the real cause.

Check yourself
A programmer adds DISPLAY statements inside a loop to show a variable's value on each pass, then removes them once the bug is found. This technique is
  1. Aadding extra output statements
  2. Bpair programming
  3. Cdata compression
  4. Devent-driven programming
Show the answer

A. Temporarily displaying values while a program runs is the "adding extra output statements" technique for finding errors. It works like a trace table that the computer fills in for you.

  • Ways to find and fix errors: test cases, hand tracing, visualizations, debuggers, extra output statements.
  • A trace table has one column per variable and one row per step. Fill it in exactly; never guess.
  • Fixing one bug can reveal another. Retest after every fix, including unusual inputs.
  • Remove temporary output statements once the bug is found.