DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on • Edited on

🔹Jagged Arrays in C#

🧠 What is a Jagged Array?

A jagged array is an array of arrays, where each "row" (inner array) can have a different length.

It's like a table where each row has a different number of columns.

🧾 Think of it as:

int[][] jaggedArray;
Enter fullscreen mode Exit fullscreen mode

✅ Each element of a jagged array is an array itself!


🧩 Syntax

// Declare a jagged array with 3 rows
int[][] jagged = new int[3][];

// Initialize each row with different sizes
jagged[0] = new int[2];  // 2 elements
jagged[1] = new int[4];  // 4 elements
jagged[2] = new int[1];  // 1 element
Enter fullscreen mode Exit fullscreen mode

📦 Assigning Values

jagged[0][0] = 10;
jagged[0][1] = 20;

jagged[1][0] = 30;
jagged[1][1] = 40;
jagged[1][2] = 50;
jagged[1][3] = 60;

jagged[2][0] = 70;
Enter fullscreen mode Exit fullscreen mode

🔍 Full Example: Declaring, Initializing, and Printing

using System;

class Program {
    static void Main() {
        int[][] jagged = new int[3][];

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

        for (int i = 0; i < jagged.Length; i++) {
            Console.Write("Row " + i + ": ");
            for (int j = 0; j < jagged[i].Length; j++) {
                Console.Write(jagged[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ Output:

Row 0: 1 2 
Row 1: 3 4 5 6 
Row 2: 7 
Enter fullscreen mode Exit fullscreen mode

🔄 Jagged vs. Multidimensional Arrays

Jagged Array Multidimensional Array
Rows can have different lengths All rows must have the same length
More flexible memory-wise Simple matrix-style structure
int[][] jagged; int[,] matrix;

🧠 Use Cases

Jagged arrays are useful when:

  • Data is irregular (e.g., a school with classes of different sizes)
  • You want to save memory by not allocating uniform size

Top comments (0)