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
- We start by initializing a jagged array
jaggedArraywith three rows, and each row contains an array of integers with varying lengths. - We use predefined functions to find the length of the jagged array. The
Lengthproperty of the outer array gives us the number of rows. - We create an integer array
columnLengthsto store the lengths of the inner arrays (columns) in each row. - We use a loop to iterate through each row of the jagged array and find the length of the inner arrays (columns) using the
Lengthproperty and store them in thecolumnLengthsarray. - Finally, we display the original jagged array and the lengths of rows and columns.
Input / Output
