C# Jagged Arrays with Examples

C# | Jagged Arrays: In this tutorial, we will learn about the jagged array, its declaration, initialization with the help of examples. By IncludeHelp Last updated : April 11, 2023

Overview

We have discussed about C# Single-dimensional arrays and C# Two-dimensional Arrays. We know that in two dimensional arrays, each row has some number of elements but all rows will have same number of elements. In this post we are going to learn about Jagged Array, which are not supported by C++ programming language. But, C# provides the concept jagged arrays.

What is a Jagged Array in C#?

A jagged array is a special type of multidimensional array that has irregular dimensions sizes. Every row has a different number of elements in it. Sometimes, a jagged array can also be known as an "array of arrays".

Declaration of a Jagged Array

The following syntax shows the declaration of a jagged array:

<data_type>[][] variable = new <data_type> [row_size][];

The following code shows the declaration of a jagged array with different sizes of arrays:

int[][] jarr = new int[2][];
jarr[0] = new int [4];
jarr[1] = new int [6];

Initialization of a Jagged Array

The following code shows the initialization of a jagged array:

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

C# Example of a Jagged Array

using System;

namespace arrayEx {
  class Program {
    static void Main(string[] args) {
      int i = 0;
      int j = 0;

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

      Console.Write("\n\nElements are: \n");
      for (i = 0; i < jarr.GetLength(0); i++) {
        for (j = 0; j < jarr[i].Length; j++) {
          Console.Write(jarr[i][j] + " ");
        }
        Console.WriteLine();
      }
    }
  }
}

Output

Elements are:
1 2 3
4 5 6 7
Press any key to continue . . .

In above example Jagged array jarr contains 3 elements in first row and 4 elements in second row.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.