Mathematics I / Arrays and Lists
Practice question · Multiple choice

Arrays are indexed from 0, so a list of length 5 has valid indices 0 to 4 and a[5] is an error. Why has this convention survived, given how many off-by-one bugs it causes?

Hints
  1. Ask what a[i] means in terms of memory: how far from the start is element i?
  2. Consider the ranges 0-5 and 5-10. What do they cover, and do they overlap?
Show the answer

C. Because the index is an offset from the start of the array.

Why

The index is a displacement rather than a count, so element i sits at base + i·size with no correction term; index from 1 and every access needs a subtraction. Half-open ranges also compose, [0,5) and [5,10) meet with no overlap and no gap, and the length of [a,b) is b − a. The bugs are concentrated at the human interface and the arithmetic underneath is clean.

Read the lesson: Arrays and Lists →

Practise Arrays and Lists

The app has 5 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.

More questions on Arrays and Lists