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:

Press + to interact
public class Example
{
public static void main(String args[])
{
// Purpose: Writes the integers 1, 2, ..., number
// in ascending order, one per line.
// Given: number is an integer > 0.
int counter = 1; // Initialize
int number = 5;
while (counter <= number) // Test
{
System.out.println(counter); // Process
counter = counter + 1; // Update
} // End while
} // End main
} // End Example

If we wrote < instead of <= to compare counter with number, the loop will count from 1 to n – 1. Thus, the loop cycles 1 too few times.

Press + to interact
public class Example
{
public static void main(String args[])
{
int counter = 1; // Initialize
int number = 5;
while (counter < number) // Test
{
System.out.println(counter); // Process
counter = counter + 1; // Update
} // End while
} // End main
} // End Example

✏️ Programming tip

Like we did ...

Access this course and 1400+ top-rated courses and projects.