Computer Science

Off-by-One Loop Error

Students write a loop that runs one time too many or one time too few when counting array indices.

Quick check

Why students make it

They mix up the number of items with the last valid index. In zero-based arrays, an array with n items has last index n - 1.

The rule done right

For an array of length n with zero-based indexing, valid indices are 0≤i<n0 \le i < n. To visit every element once, start at 0 and continue while i < n.