DEV Community

Codebuns
Codebuns

Posted on • Updated on • Originally published at codebuns.com

C# Jagged Array (With STEP-BY-STEP Video)

C# Jagged Array(Array of Arrays

There are two kinds of multi-dimensional arrays: Rectangular and Jagged.

C# jagged array is an array of arrays whose elements are fixed, and each element can hold a separate array of different dimensions and sizes. Think of a 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 lengths.

C# for Absolute Beginners: the Basics

Once you’ve read this article, I’d recommend you to check out my free C# Quick Start Guide Here, where I explained most of the topics in detail with YOUTUBE videos. Read updated version of this article Here.

Declaration and Instantiation of a Jagged Array

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;
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array Declaration

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 representing 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][];
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array Initialization

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][];
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array Declaration Initialization

Create and Assign Values to a Jagged Array

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

int[][] intArray = new int[3][];
Enter fullscreen mode Exit fullscreen mode

To assign values to jagged array elements, you use initializers to add the array elements with three separate single-dimensional arrays-one statements 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 };
Enter fullscreen mode Exit fullscreen mode

You can use the 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 } };
Enter fullscreen mode Exit fullscreen mode

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 } };
Enter fullscreen mode Exit fullscreen mode

There’s a shorter form below.

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

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

Another way with the var keyword

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

Run Demo

Access Individual Array Elements

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

Syntax
arrayName[rowIndex][columnIndex]

Example

intArray[1][2];
Enter fullscreen mode Exit fullscreen mode

Access the whole row of data using the following syntax.

Syntax
arrayName[row]

Example

intArray[2]
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array Get Whole Row By Index

Example 1: Jagged Array with 3 Rows of Different Lengths

This array consists of three rows.

int[][] intArray = new int[3][];
Enter fullscreen mode Exit fullscreen mode

To assign values to jagged array elements, you can have arrays of different lengths for each element. In the following example, a 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 };
Enter fullscreen mode Exit fullscreen mode

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 } };
Enter fullscreen mode Exit fullscreen mode

C# jagged array with 3 rows of different sizes

  • 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.

C# Jagged Array Index Values

Index values of a Jagged Array with 3 Rows of Different Lengths
You can access each element of the arrays, which are part of the jagged array, using their index. The index positions are used inside two indexers ([ ][ ]) when retrieving the value from an array.

intArray[0][0]; // return 1
Enter fullscreen mode Exit fullscreen mode

The 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
Enter fullscreen mode Exit fullscreen mode

The 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
Enter fullscreen mode Exit fullscreen mode

The 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.

C# Jagged Array Get Values By index

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;
Enter fullscreen mode Exit fullscreen mode

The 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;
Enter fullscreen mode Exit fullscreen mode

The 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;
Enter fullscreen mode Exit fullscreen mode

The 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.

C# Jagged Array Set Values By index

Run Demo

Example 2: Jagged Array with 2 Rows of Different Lengths

This array consists of two rows.

char[][] charArray = new char[2][];
Enter fullscreen mode Exit fullscreen mode

Let’s assign values to the elements of a jagged array. In the following example, a 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' };
Enter fullscreen mode Exit fullscreen mode

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

char[][] charArray = { new[] { 'A', 'B', 'C' }, new[] { 'D', 'E' } };
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array with 2 rows of different sizes

  • 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.

C# Jagged Array With 2 Rows Index Values

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

charArray[0][2]; // return C
Enter fullscreen mode Exit fullscreen mode

The 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
Enter fullscreen mode Exit fullscreen mode

The 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.

C# Jagged Array With 2 Rows Get Index Values

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

charArray[0][2] = 'F';
Enter fullscreen mode Exit fullscreen mode

The 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';
Enter fullscreen mode Exit fullscreen mode

The 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'.

C# Jagged Array With 2 Rows Set Values By Index

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" } };
Enter fullscreen mode Exit fullscreen mode

Another way with the var keyword

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

Run Demo

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

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

char[][,] charArray = new char[2][,];
Enter fullscreen mode Exit fullscreen mode

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' } };
Enter fullscreen mode Exit fullscreen mode

Alternatively, you declare and initialize a jagged array with an 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' } } };
Enter fullscreen mode Exit fullscreen mode

C# Jagged Array With 2 Rows 2 Rectangular Array

The index position is used inside a pair of indexers ([ ][ ]) when retrieving the value from the individual array element. The 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
Enter fullscreen mode Exit fullscreen mode

Jagged array 1st row ([0]) indicated by the first bracket contains the element [0, 2]. Therefore, the 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
Enter fullscreen mode Exit fullscreen mode

Jagged array 2nd row ([1]) indicated by the first bracket contains the element [1, 1]. Therefore, the 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.

C# Jagged Array With 2 Rows 2 Rectangular Array Get Value

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

charArray[0][0, 2] = 'K';
Enter fullscreen mode Exit fullscreen mode

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 element [0, 2] of the 1st array from C to K.

charArray[1][1, 1] = 'L';
Enter fullscreen mode Exit fullscreen mode

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

C# Jagged Array With 2 Rows 2 Rectangular Array Update Value

Run Demo

Jagged Array Property and Method

Length: Gets the number of elements in all of the dimensions of an array.

GetLength(dimension): Gets the number of elements in the specified dimension of an array.

Processing Jagged 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: Jagged 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);
Enter fullscreen mode Exit fullscreen mode

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, a pair of two square brackets ([ ][ ]) indicate the number of dimensions. The array is two-dimensional; that’s why you need to use two 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 the GetLength method and passing 0 for the dimension; instead, you can use the Length property. On the other hand, nested for loop requires a different approach because each row of a jagged array contains a different number of columns. Therefore, instead of the GetLength method to return the number of columns for that row, you use the array’s Length property.

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 the 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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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 lengths.
  • Think of a table that has rows of unequal lengths.
  • The declaration statement must specify the number of rows in the array. Then, declare the number of columns in each row before assigning values to the elements in that row.
  • Also called an array of arrays.

C# Reference | Microsoft Docs

Jagged Arrays

Please Share This Post With Love ❤️

Top comments (0)