Author avatar

Gaurav Singhal

Declare and Consume Multidimensional and Jagged Arrays

Gaurav Singhal

  • Jul 12, 2019
  • 7 Min read
  • 3,153 Views
  • Jul 12, 2019
  • 7 Min read
  • 3,153 Views
Programming Languages
C#

Introduction

Arrays are useful for storing items in contiguous memory locations. But what if we need to store items in the form of rows and columns? Well, that's where multidimensional arrays come into the picture.

Multidimensional Array

Array Declaration

The general syntax for declaring a multidimensional array is:

1type [,,...] arrayName = new type [n1,n2,...];
csharp

Here, type is the data-type of the array, arrayName is the name of the array, and n1,n2 are the dimensions.

The most common type of multidimensional array is a two-dimensional array.

1int [,] myArray = new int [6, 3];
csharp

Similarly, we can declare a three-dimensional array.

1int [,,] myArray = new int [3, 3, 3];
csharp

Array Initialization

We can initialize a multidimensional array as follows:

1string [,] tasks = new string [3,2] {
2            { "Task00", "Task01" },
3            { "Task10", "Task11" },
4            { "Task20", "Task21" }
5        };
csharp
1int [,,] nums = new int [3, 2, 2] {
2            { { 1, 2 }, { 3, 4 } },
3            { { 5, 6 }, { 7, 8 } },
4            { { 9, 10 }, { 11, 12 } },
5        };
csharp

We can also initialize an array without specifying its dimensions.

1int[,] myArray = {
2            { 3, 4 },
3            { 5, 6 }
4        };
csharp

To access the elements of a multidimensional array we can specify the index values as follows:

1myArray[1,2];
csharp

A multidimensional array is also called a rectangular array. You'll most probably be using 2-dimensional arrays in your program or, if you are working on a modeling software that requires 3D objects, you might require 3-dimensional arrays as well, but it's highly unlikely that you'll be using an array with more than 3 dimensions.

Let's take a look at an example, where we need to store the coordinates of five locations.

We can store the coordinates in an array as follows:

1int [,] coords = new int [5, 2] {
2            { 43, 29 },
3            { 48, 12 },
4            { 145, 54 },
5            { 123, 612 },
6            { 12, 78 }
7        };
csharp

We can also initialize using the shorthand syntax.

1int [,] coords = {
2            { 43, 29 },
3            { 48, 12 },
4            { 145, 54 },
5            { 123, 612 },
6            { 12, 78 }
7        };
csharp

Example

To access all the coordinates we will have to loop through the array. Take a look at the complete code.

1using System;
2
3namespace multidarray
4{
5    class Program
6    {
7        static void Main(string[] args)
8        {
9            int [,] coords = {
10                { 43, 29 },
11                { 48, 12 },
12                { 145, 54 },
13                { 123, 612 },
14                { 12, 78 }
15            };
16
17            for (int i = 0; i < 5; i++) {
18                for (int j = 0; j < 2; j++) {
19                    Console.Write(coords[i,j] + " ");
20                }
21                Console.WriteLine();
22            }
23        }
24    }
25}
csharp

Results:

143 29
248 12
3145 54
4123 612
512 78
console

Let's make it even more interesting. Consider: we have to draw lines on the map joining the coordinates, for that we will need a 3-dimensional array which will store a pair of coordinates.

1using System;
2
3namespace multidarray
4{
5    class Program
6    {
7        static void Main(string[] args)
8        {
9            int [,,] lines = {
10                { { 43, 29 }, { 34, 67 } },
11                { { 56, 95 }, { 48, 12 } },
12                { { 145, 54 }, { 26, 69 } },
13                { { 56, 21 }, { 123, 612 } },
14                { { 12, 78 }, { 111, 37 } }
15            };
16
17            for(int i = 0; i < 5; i++) {
18                for (int j = 0; j < 2; j++) {
19                    for (int k = 0; k < 2; k++)
20                        Console.Write(lines[i,j,k] + " ");
21                    Console.Write("\t");
22                }
23                Console.WriteLine();
24            }
25        }
26    }
27}
csharp

Results:

143 29   34 67
256 95   48 12
3145 54  26 69
456 21   123 612
512 78   111 37
console

Multidimensional arrays are great when we know the length of each element. For instance, in the previous examples, we knew that the length of each coordinate would be 2. But what if we need to store elements of variable length. Don't worry C# has got you covered for that as well.

Jagged Array

C# allows us to keep track of arrays inside another array called a Jagged Array. Each element of a jagged array is an array that can have different length.

Jagged Array Declaration

To declare a jagged array we need to specify the data type followed by two square brackets.

1type [][] arrayName = new type [n][];
csharp

Here, type is the data-type of the array, arrayName is the name of the array, and n is the length of the jagged array. Note that we cannot specify another dimension in the second set of brackets, the compiler isn't cool with that.

So what's happening here is that the jagged array is referencing a single-dimensional array and each element in this array is referencing other arrays.

Let's take a look at an example,

1int [][] shoppingCarts = new int [3][];
2shoppingCarts[0] = new int [] { 1, 2, 3, 4 };
3shoppingCarts[1] = new int [] { 45, 65, 12, 45, 56, 78 };
4shoppingCarts[2] = new int [] { 52, 74, 10, 98, 12 };
csharp

The shoppingCarts jagged array is storing the shopping carts of three users which contain the item number of the items present in the cart. Each cart is of variable length and independent of each other.

Jagged Array Initialization

There is also a shorthand version to declare and initialize a jagged array.

1int [][] shoppingCarts = {
2        new int [] { 1, 2, 3, 4 },
3        new int [] { 45, 65, 12, 45, 56, 78 },
4        new int [] { 52, 74, 10, 98, 12 }
5    };
csharp

Jagged Array Example

Complete program to access the elements of a jagged array.

1using System;
2
3namespace jaggedarray
4{
5    class Program
6    {
7        static void Main(string[] args)
8        {
9            int [][] shoppingCarts = {
10                new int [] { 1, 2, 3, 4 },
11                new int [] { 45, 65, 12, 45, 56, 78 },
12                new int [] { 52, 74, 10, 98, 12 }
13            };
14
15            for (int i = 0; i < shoppingCarts.Length; i++) {
16                for (int j = 0; j < shoppingCarts[i].Length; j++) {
17                    Console.Write(shoppingCarts[i][j] + " ");
18                }
19                Console.WriteLine();
20            }
21        }
22    }
23}
csharp

Results:

11 2 3 4
245 65 12 45 56 78
352 74 10 98 12
console

Conclusion

I hope you got to learn something new today, keep hustling and coding. Cheers.