C# Program to Find the Length of Jagged Array using Predefined Functions

Intro

Jagged arrays are arrays where each element is an array, and these inner arrays can have different lengths. In this program, we will demonstrate how to find the length of a jagged array using C# predefined functions.

Problem Statement

Write a C# program to find the length of a jagged array using predefined functions.

C# Program to Find the Length of Jagged Array using Predefined Functions

using System;

class Program
{
    static void Main()
    {
        // Initialize a jagged array
        int[][] jaggedArray = new int[][]
        {
            new int[] { 1, 2, 3 },
            new int[] { 4, 5 },
            new int[] { 6, 7, 8, 9 }
        };

        // Find the length of the jagged array using predefined functions
        int rows = jaggedArray.Length;
        int[] columnLengths = new int[rows];

        for (int i = 0; i < rows; i++)
        {
            columnLengths[i] = jaggedArray[i].Length;
        }

        // Display the results
        Console.WriteLine("Jagged Array:");
        Console.WriteLine("--------------------");

        for (int i = 0; i < rows; i++)
        {
            Console.Write("Row " + i + ": ");
            for (int j = 0; j < columnLengths[i]; j++)
            {
                Console.Write(jaggedArray[i][j] + " ");
            }
            Console.WriteLine();
        }

        Console.WriteLine("--------------------");
        Console.WriteLine("Length of Jagged Array:");
        Console.WriteLine("Rows: " + rows);

        for (int i = 0; i < rows; i++)
        {
            Console.WriteLine("Columns in Row " + i + ": " + columnLengths[i]);
        }
    }
}

How it works

  1. We start by initializing a jagged array jaggedArray with three rows, and each row contains an array of integers with varying lengths.
  2. We use predefined functions to find the length of the jagged array. The Length property of the outer array gives us the number of rows.
  3. We create an integer array columnLengths to store the lengths of the inner arrays (columns) in each row.
  4. We use a loop to iterate through each row of the jagged array and find the length of the inner arrays (columns) using the Length property and store them in the columnLengths array.
  5. Finally, we display the original jagged array and the lengths of rows and columns.

Input / Output

C# Program to Find the Length of Jagged Array using Predefined Functions

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...