Courses / Computer Science I
Programming I

Debugging Logic and State

Computer Science I 294 words Free to read

Hunting the Bug

Every programmer writes bugs; the skill is finding them efficiently. A bug is a mismatch between what a program does and what it should do. Debugging is the disciplined process of locating and fixing that mismatch — and like machine-level debugging, it is a search through the program's state (the current values of its variables) for the point where things first go wrong.

A reliable routine:

  1. Reproduce the bug consistently — find an input that triggers it every time. A bug you cannot reproduce, you cannot reliably fix.
  2. Localize it — narrow down where the state first becomes wrong. Confirm the state is correct early, wrong later, and squeeze the gap.
  3. Understand the cause — why does that line produce the wrong value? Do not fix blindly.
  4. Fix and verify — change the code and re-run the reproducing case (and the rest of the test suite) to confirm it is fixed and nothing else broke.

The everyday tools are print debugging (inserting statements that show variable values at chosen points — crude but effective) and a debugger (setting breakpoints and stepping through, inspecting state precisely). Both serve the same goal: make the invisible state visible so you can see where it diverges from what you expect.

The golden rule is to reason from evidence, not assumption: observe what the variables actually hold, rather than what you believe the code does. The mismatch between belief and reality is exactly where the bug lives.

Common pitfall: changing code randomly, hoping the bug disappears ("shotgun debugging"). Without reproducing the bug and observing the actual state, you cannot know whether a change fixed the real cause or just hid a symptom. Reproduce first, then narrow down using observed values.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes
Start Computer Science I free

Programming I