Practice Debugging in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick 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.

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.

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.

Example 3

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 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.