C# Intermediate

Jagged Array

The objective of this article is to familiarize you with the C# jagged array, also called array of arrays. Jagged array elements can be of different dimensions and sizes. You will learn how to declare, create, instantiate and use this type of array. Finally, how to iterate through all the elements of the array.

There are two kinds of multi-dimensional arrays: Rectangular and Jagged.
A jagged array is an array of arrays, whose elements are fixed and each element can hold a separate array of different dimension and size. Think of table with the rows of unequal lengths, meaning. When you create a jagged array, you declare the number of fixed rows in the array. Then, each row will hold an array of different length.

Array Declaration and Instantiation Using Two Statements

Jagged arrays are declared by placing one pair of square brackets after another ([][]) to represent the number of dimensions. Here is an example of declaring a jagged array:

Syntax

type[][] arrayName;

Example

int[][] intArray;

To initialize the jagged array, only the size that defines the number of rows in the first pair of brackets is set. The second brackets that define the number of elements inside the row are kept empty because every row has a different number of elements.

Syntax

arrayName = new type[rows][];

Example

intArray = new int[3][];

Array Declaration and Instantiation Combined on a Single Line

Declaration and initialization of an array at the same time on a single line.

Syntax

type[][] arrayName = new type[rows][];

Example

int[][] intArray = new int[3][];

Create and Assign Values to an Array

The following intArray consists of three elements, each of which is a single-dimensional array of integers.

int[][] intArray = new int[3][];

To assign values to the elements of a jagged array, you use initializers to add the array elements with three separate single dimensional arrays—one statement at a time as shown below.

intArray[0] = new int[] { 1, 2 };
intArray[1] = new int[] { 3, 4, 5 };
intArray[2] = new int[] { 6, 7, 8, 9 };

You can use second method, which is quite convenient. With this method, values can be assigned all at once using a curly bracket {…}.

int[][] intArray = new int[3][] { new int[] { 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8, 9 } };

If you initialize the jagged array using curly-bracket syntax, then you can omit the size that defines the number of rows. The C# compiler determines the size from the number of elements assigned to it.

int[][] intArray = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8, 9 } };

There’s a shorter form below.

int[][] intArray = { new int[] { 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8, 9 } };

Note: You cannot omit the new operator from the elements initialization.

Another way with var keyword

var intArray =  new[] { new int[] { 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8, 9 } };

Run Demo

Access Individual Array Elements

You refer to each element of the array using its row and column index with 2 indexers.

Syntax

arrayName[rowIndex][columnIndex]

Example

intArray[1][2];

Access whole row of data using the following syntax.

Syntax

arrayName[row]

Example

intArray[2]

Example 1: Array with 3 Rows of Different Lengths

This array consists of three rows.

int[][] intArray = new int[3][];

To assign values to the elements of a jagged array, you can have arrays of different lengths for each element. In the following example, jagged array is composed of three separate single-dimensional arrays—one per row.

intArray[0] = new int[] { 1, 2 };
intArray[1] = new int[] { 3, 4, 5 };
intArray[2] = new int[] { 6, 7, 8, 9 };

Alternatively, this is how you declare and initialize a jagged array with array initializer syntax, whose elements are arrays of integer values.

int[][] intArray = { new[] { 1, 2 }, new[] { 3, 4, 5 }, new[] { 6, 7, 8, 9 } };
  • int[3][] indicates jagged array has 3 rows and the number of columns is undefined.
  • intArray[0] = new int[] indicates row 0 has 2 columns with the values {1, 2}.
  • intArray[1] = new int[] indicates row 1 has 3 columns with the values {3, 4, 5}.
  • intArray[2] = new int[] indicates row 2 has 4 columns with the values {6, 7, 8, 9}.

Index values for the above array.

You can access each element of the arrays, which are part of the jagged array by using their index. The index positions are used inside two indexers ([ ] [ ]) when retrieving the value from an array.

intArray[0][0]; // return 1

Above statement fetches a value 1 from the 1st column ([0]) of the 1st row ([0]), which displays the value of the element [0, 0] of the 1st array.

intArray[1][2]; // return 5

Above statement fetches a value 5 from the 3rd column ([2]) of the 2nd row ([1]), which displays the value of the element [1, 2] of the 2nd array.

intArray[2][1]; // return 7

Above statement fetches a value 7 from the 2nd column ([1]) of the 3rd row ([2]), which displays the value of the element [2, 1] of the 3rd array.

You can access a value of an indexed array element, which is part of the jagged array by using two indexers ([ ] [ ]) and then assign a value to it with assignment operator (=). Look at the following statements.

intArray[0][0] = 10;

Above statement assigns a value 10 to the 1st column ([0]) of the 1st row ([0]), which updates the value of the element [0, 0] of the 1st array from 1 to 10.

intArray[1][2] = 50;

Above statement assigns a value 50 to the 3rd column ([2]) of the 2nd row ([1]), which updates the value of the element [1, 2] of the 2nd array from 5 to 50.

intArray[2][1] = 70;

Above statement assigns a value 70 to the 2nd column ([1]) of the 3rd row ([2]), which updates the value of the element [2, 1] of the 3rd array from 7 to 70.

Run Demo

Example 2: Array with 2 Rows of Different Lengths

This array consists of two rows.

char[][] charArray = new char[2][];

Let’s assign values to the elements of a jagged array. In the following example, jagged array is composed of two separate single dimensional arrays of char values — one per row.

charArray[0] = new char[] { 'A', 'B', 'C' };
charArray[1] = new char[] { 'D', 'E' };

Another way is to declare and initialize a jagged array with array initializer syntax.

char[][] charArray = { new[] { 'A', 'B', 'C' }, new[] { 'D', 'E' } };
  • char[2][] indicates jagged array has 2 rows and the number of columns is undefined.
  • charArray[0] = new char[] indicates row 0 has 3 columns with the values { 'A', 'B', 'C' }.
  • charArray[1] = new char[] indicates row 1 has 2 columns with the values { 'D', 'E' }.

Index values for the above array.

The index positions are used inside two indexers ([ ] [ ]) when retrieving the value from an array.

charArray[0][2]; // return C

Above statement fetches a value C from the 3rd column ([2]) of the 1st row ([0]), which displays the value of the element [0, 2] of the 1st array.

charArray[1][1]; // return E

Above statement fetches a value E from the 2nd column ([1]) of the 2nd row ([1]), which displays the value of the element [1, 1] of the 2nd array.

You can access a value of an indexed array element by using two indexers ([ ] [ ]) and then assign a value to it with assignment operator (=).

charArray[0][2] = 'F';

Above statement assigns a value ‘F’ to the 3rd column ([2]) of the 1st row ([0]), which updates the value of the element [0, 2] of the 1st array from ‘C’ to ‘F’.

charArray[1][1] = 'G';

Above statement assigns a value ‘G’ to the 2nd column ([1]) of the 2nd row ([1]), which updates the value of the element [1, 1] of the 2nd array from ‘E’ to ‘G’.

Run Demo

Array of Strings

You can declare a jagged array of strings as

string[][] fruits = { new string[] { "Apple", "Banana" }, new string[] { "Orange", "Papaya", "Apricot", "Cherry" } };

Another way with var keyword

var fruits =  new[] { new string[] { "Apple", "Banana" }, new string[] { "Orange", "Papaya", "Apricot", "Cherry" } };

Run Demo

Example 3: Jagged Array with 2 Rows, Each of Which Contains Multi-Dimensional Array

In the following example, single dimensional jagged array consists of two rows, each of which contains two separate multi-dimensional array elements of different sizes—one per row.

char[][,] charArray = new char[2][,];

Let’s assign values to the elements of a jagged array.

charArray[0] = new char[,] { { 'A', 'B', 'C' }, { 'D', 'E', 'F' } };
charArray[1] = new char[,] { { 'G', 'H' }, { 'I', 'J' } };

Alternatively, you declare and initialize a jagged array with array initializer whose elements are multi-dimensional arrays.

char[][,] charArray = new char[2][,] 
{
    new char[,] { { 'A', 'B', 'C' }, { 'D', 'E', 'F' } },
    new char[,] { { 'G', 'H' }, { 'I', 'J' } }
};

The index position is used inside pair of indexers ([ ] [ ]) when retrieving the value from individual array element. First bracket is used for the jagged array row and the second bracket indicates the element within that row.

charArray[0][0, 2]; // return C

Jagged array 1st row ([0]) indicated by the first bracket contains the element [0, 2]. Therefore, above statement fetches value C from the 3rd column ([2]) of the 1st row ([0]), which displays the value of the element [0, 2] of the 1st array.

charArray[1][1, 1]; // return J

Jagged array 2nd row ([1]) indicated by the first bracket contains the element [1, 1]. Therefore, above statement fetches a value J from the 2nd column ([1]) of the 2nd row ([1]), which displays the value of the element [1, 1] of the 2nd array.

You can access a value of an indexed array element by using two indexers ([ ] [ ]) and then assign a value to it with assignment operator (=).

charArray[0][0, 2] = 'K';

Jagged array 1st row ([0]) indicated by the first bracket contains the element [0, 2]. Therefore, above statement assigns a value K to the 3rd column of the 1st row, which updates the value of the element [0, 2] of the 1st array from C to K.

charArray[1][1, 1] = 'L';

Jagged array 2nd row ([0]) indicated by the first bracket contains the element [1, 1]. Therefore, above statement assigns a value L to the 2nd column of the 2nd row, which updates the value of the element [1, 1] of the 2nd array from J to L.

Run Demo

Array Property and Method

Property Description
Length Gets the number of elements in all of the dimensions of an array.
Method Description
GetLength(dimension) Gets the number of elements in the specified dimension of an array.

Processing Array Using Nested for Loops

Never hardcode total number elements, when you want to iterate through the array. Always use properties or methods such as Length and GetLength to determine the total number of iterations needed. Let’s look at the following examples.

Example 1: Array with 3 Rows of Different Lengths

string display = string.Empty;

int[][] intArray = { 
  new int[] { 1, 2 }, 
  new int[] { 3, 4, 5 }, 
  new int[] { 6, 7, 8, 9 } 
};

// Use intArray.GetLength(0) or intArray.Length
for (int row = 0; row < intArray.GetLength(0); row++)
{
    for (int column = 0; column < intArray[row].Length; column++)
    {
          display += intArray[row][column].ToString() + " ";
    }

    display += "\n";
}

Console.WriteLine(display);

Run Demo

The following output displays the rows and every element within that row.

OUTPUT

1 2
3 4 5
6 7 8 9

First, declared and initialized jagged intArray variable. On the left side of the declaration, pair of two square brackets ([ ][ ]) indicate the number of dimensions. The array is two-dimensional that’s why you need to use 2 separate for loops to iterate through each row and every element within that row.
Outer for loop is to get the number of rows by calling GetLength method and passing 0 for the dimension, instead you can use Length property as well. Nested for loop on the other hand requires different approach because each row of a jagged array contains different number of columns. Therefore, instead of GetLength method to return the number of columns for that row, you use Length property of the array.
Finally within the inner loop, you use variable intArray with the loop counter row for rowIndex and column for columnIndex inside two sets of square brackets ([ ] [ ]) to refer to each element in the array.
So the outer loop iterates through every row, and inner loop iterates through every element inside that row.

Example 2: Array with 2 Rows of Different Lengths

string display = string.Empty;
      char[][] charArray = { new[] { 'A', 'B', 'C' }, new[] { 'D', 'E' } };

      for (int i = 0; i < charArray.GetLength(0); i++)
      {
          for (int j = 0; j < charArray[i].Length; j++)
          {
                display += charArray[i][j].ToString() + " ";
          }

          display += "\n";
      }

      Console.WriteLine(display);

Run Demo

OUTPUT

A B C
D E

Example 3: Loop Through Jagged Array Composed of Multi-Dimensional Arrays

string display = string.Empty;

char[][,] charArray = new char[2][,] 
{
    new char[,] { { 'A', 'B', 'C' }, { 'D', 'E', 'F' } },
    new char[,] { { 'G', 'H' }, { 'I', 'J' } },
};

// First for loop is used to iterate through jagged array rows
for (int i = 0; i < charArray.Length; i++)
{
    display += $"Element({i}): \n";

    // For each jagged array row, 2nd and 3rd for loop is used iterate through elements on that row
    for (int j = 0; j < charArray[i].GetLength(0); j++)
    {
        // Column iteration
        for (int k = 0; k < charArray[i].GetLength(1); k++)
        {
              display += charArray[i][j, k].ToString() + " ";
        }

        display += "\n";
    }
}

Console.WriteLine(display);

Run Demo

Loop counters

  • i is used for jagged array row.
  • j (row) and k (column) is used for array element.
OUTPUT

Element(0):
A B C
D E F
Element(1):
G H
I J

Jagged Array in Short

  • Elements are fixed and each element can hold a separate array of different length.
  • Think of a table that has rows of unequal lengths.
  • Declaration statement must specify the number of rows in the array. Then, declare the number of columns in each row before you assign values to the elements in that row.
  • Also called an array of arrays.

C# Reference | Microsoft Docs

Sending
User Rating 0 (0 vote)

Add Comment

Click here to post a comment