# Lesson 13 - Multidimensional arrays in C# .NET

In the last lesson, More on C# loops , we strengthened our knowledge of loops with other constructs and keywords that we might come across in foreign source code.

Lesson highlights

Are you looking for a quick reference on multidimensional arrays in C# .NET instead of a thorough-full lesson? Here it is:

Shortened initialization of a 2D array:

```int[,] cinema = new int[,] {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};```

Writing `1` at the position `[1, 0]`:

`cinema[1, 0] = 1;`

Reading the value (now `1`) at the position `[1, 0]`:

``````{CSHARP_CONSOLE}

int[,] cinema = new int[,] {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};
cinema[1, 0] = 1;

Console.WriteLine(cinema[1, 0]);
{/CSHARP_CONSOLE}``````

Printing the whole 2D array:

``````{CSHARP_CONSOLE}

int[,] cinema = new int[,] {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};
cinema[1, 0] = 1;

for (int j = 0; j < cinema.GetLength(0); j++)
{
for (int i = 0; i < cinema.GetLength(1); i++)
{
Console.Write(cinema[j, i]);
}
Console.WriteLine();
}
{/CSHARP_CONSOLE}``````

Declaring an empty 2D array of a given size:

`int[,] cinema = new int [5, 5];`

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, More on C# loops, we learned how to use the `Split()` and `Join()` string methods. Today's tutorial is basically a bonus when it comes to C# basic constructs. We'll discuss what we call multidimensional arrays. Essentially, you could skip directly to the object-oriented programming course; however, I highly recommend that you finish this course first, so you could understand the remaining techniques. After all, this is still just the basics.

We've already worked with a one-dimensional array which we can imagine as a row of boxes in computer memory.

(An array of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional arrays. Especially, when it comes to game applications.

## Two-dimensional array

A good representation of a 2-dimensional array is a grid because technically, it is one. A practical application for 2-dimensional arrays would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to:

(We can see the available seats of a cinema in the picture )

Of course, the cinema would be bigger in real life, but this array is just fine as an example. `0` means the seat is available, `1` stands for one that isn't. Later, we could also add `2` for reserved seats and so on. It would be more appropriate to create our own data type (called enumerable) for these states, but we'll get into that later. For now, we'll work with numbers.

In C# .NET, we declare a 2D array like this:

`int[,] cinema = new int [5, 5];`

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

All numeric arrays in C# .NET are automatically initialized with zeros after the declaration, guaranteed. We've just created a table full of zeros.

### Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use `for` loops to create a row of 1s To access an item of a 2D array we have to enter two coordinates.

```cinema[2, 2] = 1; // center
for (int i = 1; i < 4; i++) // fourth row
{
cinema[i, 3] = 1;
}
for (int i = 0; i < 5; i++) // the last row
{
cinema[i, 4] = 1;
}```

### The output

We'll print the array using a loop as we did before. We'll need 2 loops for the 2d array, the first one will iterate over columns and the second one over rows). As proper programmers, won't specify the number of rows and columns directly into the loop because it may change in the future. C# .NET provides the 2D array `Length` property as it was with the 1D array, but it returns the total number of items in the array, so in our case `25`. We'll use the `GetLength()` method which accepts a dimension, `0` for columns and `1` for rows, as a parameter and returns the number of items in this dimension. The first dimension is the number of columns, the second is the number of rows.

We'll nest the loops in order so the outer loop would iterate over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable:

``````{CSHARP_CONSOLE}

// declaration
int[,] cinema = new int [5, 5];
// filling with data
cinema[2, 2] = 1; // center
for (int i = 1; i < 4; i++) // fourth row
{
cinema[i, 3] = 1;
}
for (int i = 0; i < 5; i++) // the last row
{
cinema[i, 4] = 1;
}

for (int j = 0; j < cinema.GetLength(1); j++)
{
for (int i = 0; i < cinema.GetLength(0); i++)
{
Console.Write(cinema[i, j]);
}
Console.WriteLine();
}
{/CSHARP_CONSOLE}``````

The result:

```Console application
00000
00000
00100
01110
11111```

## N-dimensional arrays

Sometimes, it may be useful to create an array of even more dimensions. We can all at least imagine a 3D array. Adding on the cinema analogy, we'll say ours has multiple floors, or generally more rooms. The visualization could then look like this:

We can create a 3D array the same way we created the 2D array:

`int[, ,] cinemas = new int [5, 5, 3];`

The code above creates the 3D array you saw in the picture. We can access it through the indexer, square brackets, as before, but now we have to enter 3 coordinates.

`cinemas[3, 2, 1] = 1; // the second-floor cinema, the third row, the fourth seat`

If we pass `2` as the parameter of the `GetLength()` method, we'll get the number of "floors".

## An array of arrays

Many programming languages don't support multi-dimensional arrays, C# is an exception. Technically, we could still create multi-dimensional arrays in the one's that don't support them since all a 2D array is nothing more than an array of arrays. We can imagine the situation as creating an array of five items (1st row) and each item of the row would also contain an array representing a column.

Its declaration would look something like this:

`int[][] cinema = new int[5][];`

An advantage to declaring 2D arrays this way is that we can store as large of an array as we want in each row/column. In some cases, we don't even have to "waste" memory for the whole table and we can create a jagged array.

The disadvantage of this approach is that we need to initialize the array ourselves. The first row of five cells exists, but we'd have to insert the individual columns into it ourselves (we'll insert all the columns with 5 items for now):

```for (int i = 0; i < cinema.Length; i++)
{
cinema[i] = new int[5];
}```

C# also doesn't make it any easier to retrieve the number of rows and columns of these arrays. We have to determine the array size like this:

```int cols = cinema.Length;
int rows = 0;
if (cols != 0)
rows = cinema[0].Length;```

Notice how it's necessary to retrieve the number of columns first. If it is `0`, we can't access the first column to determine its length (number of rows in the column).

The values of the array can be accessed using 2 indexers:

`cinema[4][2] = 1; // we occupy a seat at the 5th column and the 3rd row`

(Using a single indexer would return the entire column at the given index)

## Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (the code creates and initializes a crowded cinema room as you can see in the picture):

```int[,] cinema = new int[,] {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};```

(The array in this code is rotated since we define columns which are declared as rows here).

We can use a similar initialization even for jagged arrays (the code below creates the jagged array from the picture):

```int[][] jaggedArray = new int[][] {
new int[] {15, 2, 8, 5, 3},
new int[] {3, 3, 7},
new int[] {9, 1, 16, 13},
new int[] {},
new int[] {5}
};```

In conclusion, I would like to add that some people who can't use objects properly, use 2D arrays to store multiple sets of data of a single entity. e.g. imagine that we want to store the length, width, and height of five cell phones. Although you may think that a 3D array would be best for the situation, it can be pulled off with an ordinary 1D array (specifically a list of objects of the `Phone` type). We'll go over all of that in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Mathematical functions in C# .NET - The Math library, we'll look at basic math functions and finish the basic constructs course.

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.