CodeBlanks Logo Icon CodeBlanks

Jagged arrays

C# course · Beginner · Lesson 57/116

Learn flexible row structures with arrays of arrays (jagged).

Jagged arrays

An array whose rows may have different sizes is called a jagged array. Its type is int[][]; literally 'array of arrays'. int[][] rows = new int[3][]; creates a jagged array with three rows.

Each row is a separate array; for example rows[0] = new int[] { 1, 2 }; makes the first row two elements. int[,] keeps every row the same size, while int[][] allows flexible row lengths.

Jagged initialization and access

You can also initialize a jagged array in one line: int[][] rows = { new int[] { 1, 2 }, new int[] { 3, 4, 5 } };. The first row has two, the second three elements.

Access uses two separate brackets: rows[1][2] gives the second row's third element. rows.Length is the row count and rows[i].Length the length of row i.

Exercise Declare a jagged array and print a cell

Declare a jagged array rows with the value { new int[] { 1, 2 }, new int[] { 3, 4, 5 } }. Then print rows[1][2] with Console.WriteLine. The output should be 5.

Show example solution
Write int[][] rows = { new int[] { 1, 2 }, new int[] { 3, 4, 5 } }; and print it with Console.WriteLine(rows[1][2]);
Example solution:
using System;

class Program
{
    static void Main()
    {
        int[][] rows = { new int[] { 1, 2 }, new int[] { 3, 4, 5 } };
        Console.WriteLine(rows[1][2]);
    }
}

Test yourself

  1. Write the jagged array type

    int____ rows = new int[3][];
    Show answer
    int[][] rows = new int[3][];
  2. Match each type to its meaning

    int[][]
    Jagged array
    int[,]
    Matrix (rectangular)
    new int[3][]
    Three-row jagged
    rows[0]
    First row array
  3. Which is a jagged array (rows of different sizes)?

    // which one?
    • int[,] m
    • int[] nums
    • int[][] rows
    • int n
    Show answer

    int[][] rows — Correct. int[][] is an 'array of arrays' where each row may have a different size.

All lessons in Beginner