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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...