2.2.12 Accessing Array Elements by Index

Overview

An index expression selects one array position. The expression inside square brackets can be a number or an integer variable. Check that its value is at least zero and less than the array length before reading.

string[] names = { "Ana", "Bo", "Cy" };
int position = 1;
string selected = names[position];
Read a Chosen Position
Object diagram for accessing array elements by index: read a chosen position.
Read a Chosen Position
  • New
  • Changed
  • Removed

Position is 1, so selected becomes Bo. Changing position to 2 selects Cy. Changing it to 3 attempts to access beyond the last element. The index is a location, while selected is the value read from that location.

Reading an element does not remove or replace it. The array still contains the same values after these assignments; a later update lesson changes values deliberately.

Trace the Outcome

Predict selected for positions 0, 1, and 2. Then state what happens for -1 and 3. Draw arrows from each valid index to its stored value.