Debugging Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Debugging.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

The systematic process of finding, diagnosing, and correcting errors (bugs) in a program.

Detective work—observe the wrong output, form a hypothesis, test it, then fix what's wrong.

Read the full concept explanation →

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Debugging is systematic: reproduce the bug, isolate the cause, apply a fix, then verify it works.

Common stuck point: The bug might not be where the error appears—trace backward.

Worked Examples

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.

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.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
This code should output the largest number in [3, 7, 2, 9, 4] but outputs 3: SET largest = nums[0]. FOR i = 0 TO LENGTH(nums)-1: IF nums[i] > largest THEN largest = nums[i]. OUTPUT largest. Trace and verify if it is correct, or find the bug.

Example 2

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.

Related Concepts

Background Knowledge

These ideas may be useful before you work through the harder examples.

algorithm