Logic errors can be difficult to solve. Sometimes they are difficult to find, too. The code compiles and runs, but it behaves in a way you didn't expect.
One way to track down a logic error is to walk line-by-line through your code. Explain what each statement does as if you are talking to someone who knows nothing about programming. As you explain the logic, you might see a disconnect between what you want to happen and what the code is actually doing. By changing your perspective (from writing code to explaining what it does) the error can become obvious.
"A very simple but particularly useful technique for finding the cause of a problem is simply to explain it to someone else. The other person should look over your shoulder at the screen, and nod his or her head constantly (like a rubber duck bobbing up and down in a bathtub). They do not need to say a word; the simple act of explaining, step by step, what the code is supposed to do often causes the problem to leap off the screen and announce itself." (The Pragmatic Programmer 2nd Edition, p 94)
Alternatively, you can explain the code to yourself, or use an inanimate object like a rubber duck.
"Explain to the duck using simple words why each line ... in your program is obviously correct. At some point you will be unable to do so, either because you don’t understand [what] you wrote, or because it’s wrong, or both. Concentrate your efforts [there]; that’s probably where the bug is." - How to Debug Small Programs
Learn More
Resources
- Rubber duck debugging
- The Pragmatic Programmer book (publisher's site)
- How to Debug Small Programs
- Problem Solving in Programming
- Debugging Code: Poem Generator
Make a Debugging Buddy
If you want a low cost debugging buddy, here are some resources.
- Colored paper animal models (duck, owl, turtle, frog, salamander, and more) from Ducks Unlimited Canada
- Video: Origami Duckling
- Origami animals at Paper Kawaii
Or you can download the debugging buddy graphic!