Debugging CS Thinking Example 1

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

Example 1

medium
This code should print numbers 1 to 5 but has a bug: SET i = 1. WHILE i < 5: OUTPUT i. i = i + 1. Find and fix the bug.

Solution

  1. 1
    Step 1: Trace: i=1 (output 1), i=2 (output 2), i=3 (output 3), i=4 (output 4), i=5 (5 < 5 is false, loop ends).
  2. 2
    Step 2: The loop outputs 1, 2, 3, 4 โ€” it misses 5.
  3. 3
    Step 3: Fix: change `WHILE i < 5` to `WHILE i <= 5`.

Answer

Change `i < 5` to `i <= 5`. Off-by-one error.
Off-by-one errors are among the most common bugs. Careful attention to loop boundaries (< vs <=) prevents them. Tracing helps catch these errors.

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