If a program doesn't behave correctly, then it's time to learn how to debug your program. Debugging a program is part and parcel of learning how to write a program.
No one writes perfect programs the first time. Your compiler more than likely has a debugger, where you can step through the program one line at a time, watching variables and seeing how the program flows. If you did that, not only would you know what's wrong, you will learn how your program is doing what it's doing, i.e. program flow.
At the very least, you should have output the value of variables or some other statements telling you what your program is doing at certain times.