2.2.1 One-Dimensional Arrays

Keep Soccer Round Scores Together

The Wildcats coach records goals for three training rounds: 2, then 0, then 3. Three separate variables could hold those scores, but they would not express that the values belong to one ordered sequence.

A one-dimensional array groups elements of the same type. Each element has a numbered position called an index. This lets the application identify a score by its position in the sequence.

Start with the Soccer Record
A sequence of three rounds
Round represented Position index Goals stored
Round 1 0 2
Round 2 1 0
Round 3 2 3

Indexes start at zero in C#. In this model, the first round is stored at index 0, the second at index 1, and the third at index 2. The index and the score are different numbers with different meanings.

The first array position stores 2, the second stores 0, and the third stores 3. Indexes are zero-based.
Three ordered scores
  • New
  • Changed
  • Removed

The array box shows three indexed positions, not three unrelated objects. The middle zero is a score in an existing position. It does not mean that the second round is absent.

Create the Same Sequence in Code

This statement belongs inside an existing method. It defines a local reference, creates an array containing the listed values, and assigns the array reference to that local.

Create three soccer scores
int[] roundGoals = { 2, 0, 3 };

Read the type and name separately

The type int[] means an array whose elements are ints. The name roundGoals identifies the local used to reach the array. The square brackets are part of the array type; they distinguish it from a single int.

The listed values establish the element order

The initializer lists 2, 0, and 3 from left to right, so they occupy positions 0, 1, and 2. There are three values and therefore three positions in this instance.

The array preserves that order; it does not sort the scores or attach round labels automatically. The program must use the same position-to-round mapping whenever it interprets the data.

Check the Representation

If a fourth listed score is 1, which index identifies it? What happens to the earlier three positions?

Solution

The fourth value occupies index 3. The earlier positions still hold 2, 0, and 3 in that order. An initializer with four values creates a four-element array; the first index is still zero.