Why an Array’s Last Index Is One Less Than Its Length

An array with n elements has positions numbered from 0 through n − 1. The length counts elements; an index names the gap-free position of one element, with the first position labeled zero. So an array of four items has indices 0, 1, 2, and 3—not 1 through 4.

That difference matters when a loop uses its counter as an array index. A loop that runs while `i <= length` reaches `i == length`, even though that number names no element. The safe pattern for visiting every item is usually `i < length`: it stops when the counter reaches the length, just after the final valid index.

The Boundary Is Where the Bug Hides

The error can be easy to miss because the loop works for most of its run. With four items, accesses at indices 0 through 3 succeed; the next attempt, at index 4, is outside the array. Depending on the programming language and situation, the program may report an error, stop, or behave unpredictably.

A related mistake happens when counting backward. Starting at `length` is already one position too high; the last element is at `length - 1`. These bugs cluster around boundaries because people naturally count objects from one, while many programming languages use zero as the first index.

A useful check is to separate the two questions: How many elements are there? That is the length. What is the last valid index? For a nonempty array, it is the length minus one. Keeping those quantities distinct makes loop limits much easier to verify.