Debugging CS Thinking Example 4

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

Example 4

medium
A program to sum the numbers 1 through 5 uses `SET total = 1; FOR i = 1 TO 5: total = total + i`. It outputs 16 instead of 15. Identify the bug and fix it.

Solution

  1. 1
    Step 1: The bug is the initial value. total starts at 1, so the algorithm adds an extra 1 before the loop even begins.
  2. 2
    Step 2: Fix it by starting with total = 0. Then the loop adds 1 + 2 + 3 + 4 + 5 = 15.

Answer

Initialize total to 0, not 1. Then the program outputs 15.
Debugging often comes down to checking assumptions about initial values and state. A small setup error can make the whole program wrong even when the loop logic is correct.

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