Menu
Coddy logo textTech

2D Arrays Basics

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

In C#, a jagged array is an array of arrays, forming a grid or a matrix-like structure. It's like a table with rows and columns, where each cell can hold a value. Jagged arrays are useful for representing data that has a two-dimensional relationship, such as a chessboard, a seating chart, or a grid-based game.

Here's how you declare and initialize a jagged array in C#:

data_type[][] arrayName = new dataType[numberOfRows][];

dataType: The type of elements the array will hold (e.g., int, string, etc.).

arrayName: The name you give to the array.

numberOfRows: The number of rows in the array.

Each row must then be initialized separately:

arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];
// and so on...

For example, to create a jagged array of integers with 3 rows, where each row has 4 columns, you would write:

int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];

You can also initialize a jagged array with values directly:

int[][] matrix = new int[][] {
    new int[] {1, 2, 3},
    new int[] {4, 5, 6},
    new int[] {7, 8, 9}
};
challenge icon

Challenge

Easy

Initialize a jagged array with the following values:

5, 7, 10, 24, 41
86, 13, 683, 64, 13
42, 46, 791, 111, 9
86, 88, 1845, 5, 15897
9, 1, 5, 5, 6

Your task is to correctly initialize the jagged array with these exact values and ensure that the program correctly prints the matrix.

Cheat sheet

A jagged array is an array of arrays, forming a matrix-like structure with rows and columns.

Declaration syntax:

data_type[][] arrayName = new dataType[numberOfRows][];

Each row must be initialized separately:

arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];

Example with separate initialization:

int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];

Direct initialization with values:

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

Try it yourself

using System;

class Program
{
    static void Main(string[] args)
    {
        int[][] matrix = {
            // Write your code here
        };
        
        // Print the matrix
        int rows = matrix.Length;
        
        for (int i = 0; i < rows; i++)
        {
            int cols = matrix[i].Length;
            for (int j = 0; j < cols; j++)
            {
                Console.Write(matrix[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow