Mistakes in Loops
In this lesson, we will discuss some common mistakes programmers make when writing loops.
The typical mistakes that one makes when writing a loop affect the number of times that it iterates. Often a loop will cycle one too many times or one too few times. Another common slip-up causes a loop that never ends. We consider these kinds of errors next.
Off-by-one errors
A common mistake in loop design involves an incorrect condition that is tested. Maybe the condition uses a “less than” comparison when “less than or equals” is needed. Such mistakes cause the loop to cycle an incorrect number of times. Often this number is off by one, so we call such errors off-by-one errors.
For example, the following loop—like the one we saw in an earlier lesson—counts from 1 to n, where n is in the variable number
:
Get hands-on with 1200+ tech skills courses.