Debugging CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

medium
This code calculates an average but gives the wrong answer: SET total = 0. FOR each num in [10, 20, 30]: total = total + num. SET average = total / 2. OUTPUT average. The input has 3 numbers. Find the bug.

Solution

  1. 1
    Step 1: total = 10+20+30 = 60. average = 60/2 = 30.
  2. 2
    Step 2: The correct average should be 60/3 = 20.
  3. 3
    Step 3: Bug: dividing by 2 instead of the number of elements (3). Fix: average = total / LENGTH(list).

Answer

Change `total / 2` to `total / LENGTH(list)`. Hard-coded divisor instead of using list length.
Hard-coding values (like the divisor) instead of computing them dynamically is a common source of bugs. Using LENGTH(list) makes the code correct for any list size.

About Debugging

The systematic process of finding, diagnosing, and correcting errors (bugs) in a program. Debugging involves reproducing the problem, isolating its cause through testing and inspection, applying a targeted fix, and verifying the fix resolves the issue without introducing new problems.

Learn more about Debugging โ†’

More Debugging Examples