This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: Debugging your code

Debugging unexpected outputs

face Josiah Wang

Of course, debugging gets harder when your program does not give an error, but is producing the wrong output. This indicates that there is either a problem with your implementation, or a problem with your algorithm itself (so you will have to rethink and redesign your algorithm rather than just patching up the bug!)

Again, the first thing to do is to find out where the problem starts. For example, if the output of a variable x is not what you expect, you could start from where x is last changed, and check the value of x there, and go up your code until you spot the problem.

If you have larger programs, then perhaps you can use the debugging by bisection strategy. In this strategy, you start by checking the value of some potential problematic variable somewhere in the middle of the code. If the value is correct, then you know that the problem is likely at the bottom half of the code, and not the top half. Then go to the middle of the bottom half, repeat, until you find the problem.