A girl and a robot thinking together

Think together · Start with a story

A girl stands on the first tile. The robot asks, “How many tiles have you stepped past from the starting point?” The answer is 0, not 1.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. First elementa[0], offset 0
  2. Second elementa[1], offset 1
  3. Third elementa[2], offset 2

A C++ array index tells you the offset from the first element. The first element has an offset of 0.

01Why is the first element not a[1]?

Because an array index counts how far an element is from the first one. The first element is 0 positions away.

02An index is more like an “offset”

a[0]

Offset 0 → still the first element.

a[1]

Offset 1 → the second element.

a[2]

Offset 2 → the third element.

a[3]

Offset 3 → the fourth element.

03How is it related to an address?

Array elements are stored contiguously. Conceptually:

location of a[i] = location of the first element + i elements

That is why the first element naturally has an offset of 0.

04How is a[i] related to a pointer?

For an ordinary array in C++, the expressions:

a[i]

and:

*(a + i)

refer to the same element in the relevant context.

05What are the valid indexes of an array of length n?

If an array has length n, its valid indexes are:

0 through n - 1

For example, for a length of 5:

0, 1, 2, 3, 4

06Why is it easy to get the last position wrong?

People are used to “first, second, …, nth,” while arrays use offsets “0, 1, …, n-1.”

What you have learned

  • The first element of an array has index 0.
  • An index can be understood as an offset from the first element.
  • Contiguous storage makes “starting address + offset” a natural way to locate an element.
  • For an array of length n, valid indexes run from 0 to n-1.
  • The last element is not a[n], but a[n-1].

Next: How Do You Traverse an Array?

Your turn to try

What is the last valid index of an array with length 8?

Ready? Open to see the explanation

7. Valid indexes satisfy 0 ≤ index < 8, which gives eight positions. The largest index is not 8.