Skip to content

Off-by-One Errors#

One of the most common errors with loops are so widespread that there's even a name for it: The dreaded Off-By-One Error (sometimes abbreviated "OBOE"). Your Task is to draw five circles to the screen. You write this:

THERE ARE FOUR CIRCLES

🚫 Anti-Example!
for (int i = 1; i < 5; i++) {
    circle(i * 20, 50, 20);
}

Somehow we ended up with four circles instead of the requested five circles. While it feels natural to have the 1 and the 5 in the head of the for-loop, they create this error. We would either have to start at zero, or we would have to compare with <=. We could also compare until < 6, of course. All three fixes would have slightly different results and differ a little bit in terms of readability.

Check Your Iteration Variables

When you encounter bugs with your loops, checking the exact value of your iteration variable should be among the first things you do.