Debugging CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumThis 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.
Solution
- 1 Step 1: Trace: largest=3. i=0: 3>3? No. i=1: 7>3? Yes, largest=7. i=2: 2>7? No. i=3: 9>7? Yes, largest=9. i=4: 4>9? No.
- 2 Step 2: Output: 9. The code is actually correct โ the claim that it outputs 3 is wrong. If it did output 3, the loop might not be executing.
Answer
The algorithm is correct and should output 9. If 3 is output, the loop body is not executing โ check indentation or syntax.
Sometimes debugging means verifying that the logic is correct and the bug lies elsewhere (e.g., indentation in Python, missing braces in JavaScript). Careful tracing is the key tool.
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
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. Fi
Example 2 mediumThis code calculates an average but gives the wrong answer: SET total = 0. FOR each num in [10, 20,
Example 4 mediumA program to sum the numbers 1 through 5 uses `SET total = 1; FOR i = 1 TO 5: total = total + i`. It