Debugging Loops

  1. Debugging loops and nasty nested loops can be challenging. It helps to keep in mind some of the common mistakes involving loops.

    • Variables not initialized properly before entering a loop.

    • Off-by-one error, i.e. loops that iterate one too many or one too few times. This may be due to improper initialization of loop control variables, or an incorrect loop controlling condition (for example, choice of less than or less than or equal to condition).

    • A loop may or may not iterate zero number of times.

    • Watch out for infinite loops.

  2. The following hints and suggestions may help you debug your loop.

    • Do not only check to ensure that your loop perform for a general iteration cycle, check the first 2 iterations and the last 2 iterations very carefully .

    • Print out to watch loop control variables as well as some key intermediate results. You can certainly use the debugger to help you out.

    • Avoid checking for equality especially with float or double numerical types in a loop condition. (The same applies also to conditions of an if and if-else statement.)