4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (C#)

4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (C#)

Choose a structure that fits a problem, represent vectors and matrices with arrays, and use indexes to process their elements in C#. This route is incomplete: runnable support pending; its code examples and questions are written practice with no Run.

Choosing a data structure

A program needs an organised way to hold related values so that it can find and change the right value.

Data structure

A data structure organises data and supports operations on it, such as accessing, adding, removing or searching for an item.

A single variable can hold today's temperature. To store one temperature for each hour, twenty-four separately named variables would make processing awkward. An array gives the values one name and distinguishes them by an integer index. A loop can then process every hour with the same instruction. An address book may instead need a mapping from names to phone numbers; a dictionary fits that access pattern better. Choice depends on the required operations and relationships, not just how much data there is.

A C# array has one element type and a length fixed when that array object is created. int[] scores = { 12, 9, 15 }; creates three integer elements. Their indexes are 0, 1 and 2: scores[1] is 9. Assigning scores[1] = 11; replaces that element; it does not add a fourth element. scores.Length is 3, so the last valid index is scores.Length - 1. An index of 3 is outside this array.

Vectors and matrices as arrays

The number of indexes needed to locate an element is the array's number of dimensions.

A one-dimensional array represents an ordered vector, such as three coordinates. A two-dimensional array represents a matrix, such as one row per shop and one column per day. In C#, a rectangular two-dimensional array uses a comma between indexes:

C#
int[,] sales = { { 4, 7, 2 }, { 6, 1, 5 } };
Console.WriteLine(sales[1, 2]);
Console.WriteLine(sales.GetLength(0));
Console.WriteLine(sales.GetLength(1));

The output is 5, then 2, then 3 on separate lines. GetLength(0) gives the number of rows and GetLength(1) the number of columns; sales.Length gives all six elements. The index tuple (1, 2) means second row, third column. Order matters: (2, 1) is outside the two-row array.

Continue this lesson.

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

Create free account