An important part of coding is learning how to debug and fix your errors.
Try stepping through the program with a debugger and check to make sure all values are what you think they should be. By doing this you should be able to figure out where the problem lies.
I know this is going to be a difficult question, but I want you to think really hard about it. Don't rush into an answer - take your time and think about it. We'll be patient.
Here it comes...
Can you think of any information that you could give us, that might make it easier for us to find the problem in your code?