Practice question · Numerical answer
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 reads are out of bounds?
Hints
- Count the accesses the loop makes, then count how many indices are legal.
- Valid indices for seven values are 0 through 6.
Show the answer
1
Why
The loop makes 8 accesses (i = 0..7) but only 0..6 are valid, so exactly one read, b[7], is out of bounds. The loop looks nearly right, which is why off-by-one errors survive casual reading.
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
- 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…
- 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.