3.2.6 - One-dimensional arrays (C#)

3.2.6 - One-dimensional arrays (C#)

Use an indexed collection to store and process related values without a separate variable for every item. Required written code is native C#; execution is unavailable here, with an optional Python demonstration for exploration.

Indexed collections

A data structure organises related data so a program can access and process it conveniently.

Array

A collection of elements accessed by index. A C# array has a fixed length and stores elements of the same declared type.

Six daily temperatures belong in one collection rather than six unrelated variables. An index tells the program which day's value to use.

C#
int[] temperatures = { 12, 14, 13, 16, 11, 15 };
int[] counts = new int[6];
Index012345
Temperature121413161115

temperatures[0] is the first value, 12. temperatures[5] is the sixth, 15. temperatures.Length is 6, and index 6 is outside the array. In native C#, new int[6] creates six elements indexed 0–5, initially zero; its bracket number is a length, not a highest index. Do not confuse it with VB.NET's upper-bound declaration convention.

To associate die faces 1–6 with six counters, use counts[face - 1]. Face 6 then maps to index 5. Another possible design allocates seven counters and uses indexes 1–6, leaving index 0 unused; it must genuinely allocate seven elements. The index mapping and allocation must agree.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account