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
- Ask what a[i] means in terms of memory: how far from the start is element i?
- 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.
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
- A list has length 5 and uses zero-based indexing. Sort each access.
- Appending to a dynamic array is described as O(1) amortised, even though some appends copy the entire array.…
- Let a be the list 3, 1, 4, 1, 5 with zero-based indexing. Select every TRUE statement.
- Match each array operation to what it does.
- A list b holds seven values. A loop runs i from 0 to 7 inclusive and reads b[i] each time. How many of those…