Author avatar

Gaurav Singhal

Declare and Consume Multidimensional and Jagged Arrays

Gaurav Singhal

  • Jul 12, 2019
  • 7 Min read
  • 50 Views
  • Jul 12, 2019
  • 7 Min read
  • 50 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:

1
type [,,...] 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.

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

Similarly, we can declare a three-dimensional array.

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

Array Initialization

We can initialize a multidimensional array as follows:

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

We can also initialize an array without specifying its dimensions.

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

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

1
myArray[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:

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

We can also initialize using the shorthand syntax.

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

Example

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;

namespace multidarray
{
    class Program
    {
        static void Main(string[] args)
        {
            int [,] coords = {
                { 43, 29 },
                { 48, 12 },
                { 145, 54 },
                { 123, 612 },
                { 12, 78 }
            };

            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < 2; j++) {
                    Console.Write(coords[i,j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}
csharp

Results:

1
2
3
4
5
43 29
48 12
145 54
123 612
12 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace multidarray
{
    class Program
    {
        static void Main(string[] args)
        {
            int [,,] lines = {
                { { 43, 29 }, { 34, 67 } },
                { { 56, 95 }, { 48, 12 } },
                { { 145, 54 }, { 26, 69 } },
                { { 56, 21 }, { 123, 612 } },
                { { 12, 78 }, { 111, 37 } }
            };

            for(int i = 0; i < 5; i++) {
                for (int j = 0; j < 2; j++) {
                    for (int k = 0; k < 2; k++)
                        Console.Write(lines[i,j,k] + " ");
                    Console.Write("\t");
                }
                Console.WriteLine();
            }
        }
    }
}
csharp

Results:

1
2
3
4
5
43 29   34 67
56 95   48 12
145 54  26 69
56 21   123 612
12 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.

1
type [][] 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,

1
2
3
4
int [][] shoppingCarts = new int [3][];
shoppingCarts[0] = new int [] { 1, 2, 3, 4 };
shoppingCarts[1] = new int [] { 45, 65, 12, 45, 56, 78 };
shoppingCarts[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.

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

Jagged Array Example

Complete program to access the elements of a jagged array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

namespace jaggedarray
{
    class Program
    {
        static void Main(string[] args)
        {
            int [][] shoppingCarts = {
                new int [] { 1, 2, 3, 4 },
                new int [] { 45, 65, 12, 45, 56, 78 },
                new int [] { 52, 74, 10, 98, 12 }
            };

            for (int i = 0; i < shoppingCarts.Length; i++) {
                for (int j = 0; j < shoppingCarts[i].Length; j++) {
                    Console.Write(shoppingCarts[i][j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}
csharp

Results:

1
2
3
1 2 3 4
45 65 12 45 56 78
52 74 10 98 12
console

Conclusion

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

0