Menu
Coddy logo textTech

Jagged Arrays

Part of the Logic & Flow section of Coddy's C# journey — lesson 5 of 66.

Jagged arrays in C# are arrays of arrays, where each inner array can have a different length.

Create a jagged array with 3 rows:

int[][] jaggedArray = new int[3][];

Initialize each row with different lengths:

jaggedArray[0] = new int[4]; // First row has 4 elements
jaggedArray[1] = new int[2]; // Second row has 2 elements
jaggedArray[2] = new int[5]; // Third row has 5 elements

Assign values to elements:

jaggedArray[0][0] = 10;
jaggedArray[1][1] = 20;
jaggedArray[2][3] = 30;

Initialize a jagged array with values:

int[][] numbers = new int[][]
{
    new int[] {1, 2, 3, 4},
    new int[] {5, 6},
    new int[] {7, 8, 9, 10, 11}
};

Get the number of rows:

int rows = jaggedArray.Length; // Returns 3

Get the length of a specific row:

int elementsInRow1 = jaggedArray[1].Length; // Returns 2
challenge icon

Challenge

Medium

Create a method called createTriangle that:

  1. Takes a positive integer size as a parameter
  2. Returns a jagged array representing a triangle pattern
  3. Each row should have one more element than the previous row
  4. Each element should be equal to its row index plus its column index

For example, with size = 4, the jagged array should be:

[0]
[1, 2]
[2, 3, 4]
[3, 4, 5, 6]

Cheat sheet

Jagged arrays are arrays of arrays where each inner array can have different lengths.

Create a jagged array:

int[][] jaggedArray = new int[3][];

Initialize rows with different lengths:

jaggedArray[0] = new int[4]; // First row has 4 elements
jaggedArray[1] = new int[2]; // Second row has 2 elements
jaggedArray[2] = new int[5]; // Third row has 5 elements

Assign values to elements:

jaggedArray[0][0] = 10;
jaggedArray[1][1] = 20;
jaggedArray[2][3] = 30;

Initialize with values directly:

int[][] numbers = new int[][]
{
    new int[] {1, 2, 3, 4},
    new int[] {5, 6},
    new int[] {7, 8, 9, 10, 11}
};

Get array dimensions:

int rows = jaggedArray.Length; // Number of rows
int elementsInRow1 = jaggedArray[1].Length; // Length of specific row

Try it yourself

public class CreateTriangle
{
    // Implement the CreateTriangle method
    public static int[][] createTriangle(int size)
    {
        // Write your code here
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow