← Back to course
Intro to CS 9-10 / Week 08 / Wednesday
3/6
Week 08 · Test, Debug, Document

Wednesday

Beacon Lab: Debug the average
// Test plans, four kinds of errors, and guides that help others fix problems
⏱ about 20 min

Wednesday: Beacon Lab: Debug the Average

Mission control sends a friendly note. "Beacon says today's average water level is 30. The tomatoes look happy. Can you check?"

Comet pulls up the three readings: 30, 60 and 90. "The average should be 60," she says. "Beacon is wrong by a lot."

Comet winces. "I copied out the average procedure again last night, with new names. Something must have slipped."

Wren opens it. "No error message. It runs every time."

"So it is a logic error," Comet says. "The worst kind to find."

Nova projects an empty table with three columns: reading, total and count. "Would you like a hint?" she asks. "Trace it one pass at a time."

Wren hands you a pencil.

Your mission

You will hand trace Beacon's average procedure, find the line with the bug, fix it, and test the fix.

  • Paper and a pencil
  • A ruler for drawing your trace table
  • A second color for marking the fix
PROCEDURE average(readings)
{
   total ← 0
   count ← 0
   FOR EACH reading IN readings
   {
      total ← reading
      count ← count + 1
   }
   RETURN(total / count)
}
  1. Copy the procedure onto your paper.
  2. Draw a trace table with columns for reading, total and count.
  3. Call average with the list 30, 60, 90. Fill in one row for each pass of the loop.
  4. Write the value the procedure returns.
  5. Compare it with the expected outcome, 60.
  6. Circle the line that makes the trace go wrong.
  7. In your second color, write the fixed line, then trace again.
Momentreadingtotalcount
Before the loopnone yet00
After pass 130301
After pass 260??
After pass 390??
FIND THE BUG
  • Read the question.
  • Tap your answer.
What does the buggy procedure return for 30, 60, 90?
Which line is the bug?
What should that line say?
You add an extra output line, DISPLAY(total), inside the loop of the buggy version. What does it show?

Retest the fix

Now run the test set on both versions. Some tests pass even with the bug. That is why one test is never enough.

Test readingsExpectedBuggy versionFixed version
30, 60, 90603060
0, 0, 0 (minimum)000
100, 100, 100 (maximum)100about 33100
50 (one reading)505050
READ THE RETEST TABLE
  • Read the question.
  • Tap your answer.
Which test readings catch the bug?
Why does the test 0, 0, 0 pass, even with the bug?
What the lab showsTrue or false?
The test with one reading, 50, would have caught the bug.?
The test at the maximum, 100, 100, 100, catches the bug.?
After the fix, DISPLAY(total) inside the loop would show 30, 90, 180.?
A test that passes proves the procedure has no bugs.?
WHY THIS EXERCISEHand tracing found the bug, and a varied test set proves the fix works.

Excellent debugging. Tomorrow you will write it all down so others can fix bugs too.

← Tuesday