Course contentsShow
← C
Lesson 319 of 1,2194. Control FlowFree lesson

The Fencepost problem (off-by-one errors)

The Fencepost problem (off-by-one errors)

What you'll learn: How to recognize and avoid the logical mistake of being off by one when calculating loop iterations or array boundaries.

The analogy: Building a fence

Imagine you want to build a straight fence that is 10 meters long, with a post every 1 meter. How many posts do you need?

If you quickly answered "10," you’ve just encountered the fencepost problem. To support 10 sections of fencing, you actually need 11 posts: one at the very start (0 meters) and one at the end of every meter thereafter. If you only buy 10 posts, the end of your fence will collapse.

In C programming, this is the most common source of "off-by-one" errors. It happens when you confuse the number of items (the posts) with the number of spaces between them (the fence sections).

Seeing it in code

Off-by-one errors usually hide in your loop conditions. In C, arrays start at index 0. If an array has a size of 10, the valid slots are 0 through 9. A common mistake is trying to access index 10.

#include <stdio.h>

int main() {
    int scores[5] = {90, 85, 77, 92, 88};

    // INCORRECT: This loop runs 6 times (0, 1, 2, 3, 4, 5)
    // It will try to read scores[5], which is outside the array!
    for (int i = 0; i <= 5; i++) {
        // printf("%d ", scores[i]); 
    }

    // CORRECT: The "less than" operator ensures we stop at 4
    // This gives us exactly 5 posts (0, 1, 2, 3, 4)
    for (int i = 0; i < 5; i++) {
        printf("%d ", scores[i]);
    }

    return 0;
}

How to avoid it

To keep your logic straight, remember these three tips:

  1. Prefer < over <=: When looping through an array of size N, the standard pattern for (int i = 0; i < N; i++) is your safest bet. It ensures the loop runs exactly N times and stops before it hits the illegal index.
  2. Count the "clicks": If you are printing commas between items (e.g., 1, 2, 3), remember there is one fewer comma than there are numbers.
  3. Test the boundaries: Mentally run your loop for the very first and very last value of i. If the first or last step feels wrong, you likely have a fencepost error.

Key takeaway

Always double-check if your loop needs to count the sections or the posts to avoid crashing into memory you don't own.