Menu
Coddy logo textTech

Accessing 2D Array Elements

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

Accessing elements in a 2D array uses a similar syntax to regular arrays, but requires two indices: one for the row and one for the column.

Note: In C#, there are two kinds of multi-dimensional arrays: rectangular arrays (int[,]) and jagged arrays (int[][]). This lesson covers jagged arrays, where each row is its own array.

Create a jagged array with 3 rows and 4 columns:

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

Assign a value to a specific position (row index 1, column index 2):

grid[1][2] = 42;

Read a value from a specific position (row index 0, column index 3):

int value = grid[0][3];

Since indices start at 0, row index 0 is the 1st row and column index 3 is the 4th column.

Remember that array indices start at 0, so the valid index ranges are:

  • Rows: index 0 to 2 (for a 3-row array — the 1st row is index 0, the 2nd is index 1, the 3rd is index 2)
  • Columns: index 0 to 3 (for a 4-column array — the 1st column is index 0, the 2nd is index 1, and so on)
If you try to access an element outside these ranges (like grid[3][2]), you'll get an IndexOutOfRangeException.
challenge icon

Challenge

Medium

Write a method named getElement that takes three arguments:

  1. A 2D integer array (int[][] matrix)
  2. A row index (int row)
  3. A column index (int col)

The method should return the element at the specified position if the indices are valid. If either index is out of range, the method should return -1.

Cheat sheet

Access elements in a 2D array using two indices: [row][column]

Create a 2D array:

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

Assign a value:

grid[1][2] = 42;

Read a value:

int value = grid[0][3];

Array indices start at 0. Accessing elements outside valid ranges throws an IndexOutOfRangeException.

Try it yourself

public class GetElement
{
    public static int getElement(int[][] array, int row, int col)
    {
        // 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