C# - Length of a Jagged Array

Here, we are going to learn how to get the length of a jagged array using predefine property in C#?
Submitted by Nidhi, on August 22, 2020 [Last updated : March 19, 2023]

C# Jagged Array

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

Problem statement

Here, we will create the jagged array of strings; here each row contains a different number of elements. Then we find the size of each using Length property.

C# program to get the length of a jagged array using predefine property

The source code to get the length of the jagged array using predefine property is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to get the length of a jagged 
//array using predefined property in C#.

using System;

class Demo
{
    public static void Main()
    {
        string [][] jagged = new string[5][];
        int loop=0;

        for (loop = 0; loop < jagged.Length; loop++)
        {
            jagged[loop] = new string[loop+2];
        }
        for (loop = 0; loop < jagged.Length; loop++)
        {
            Console.WriteLine("Size of row {0}->{1}", loop, jagged[loop].Length);
        }
    }
}

Output

Size of row 0->2
Size of row 1->3
Size of row 2->4
Size of row 3->5
Size of row 4->6
Press any key to continue . . .

Explanation

In the above program, we created a Demo class that contains the Main() method. Here we created a jagged array of strings.

for (loop = 0; loop < jagged.Length; loop++)
{
    jagged[loop] = new string[loop+2];
}

In the above code we created each row of the jagged array with different sizes, and then print the size of each row on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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