Debugging CS Thinking Example 3

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

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.

Solution

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