Menu
Coddy logo textTech

Nested Loops with 2D Arrays

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

When working with 2D arrays (jagged arrays) in C#, we often use nested loops to iterate over each row and each column, allowing us to access or modify every element in the array.

Here's a typical structure of nested loops for a 2D array in C#:

for (int i = 0; i < array.Length; i++) {
    // Outer loop iterates over rows
    for (int j = 0; j < array[i].Length; j++) {
        // Inner loop iterates over columns
        // Access or modify array[i][j]
    }
}

The outer loop iterates over the rows, and the inner loop iterates over the columns of each row. This way, you can access each element in the 2D array by using array[i][j].

challenge icon

Challenge

Easy
Create a method named printMatrix that takes a 2D array (jagged array) of integers as an argument and prints its elements in a matrix format. Use nested loops to iterate over the rows and columns of the array.

Print each element followed by a space (including the last element in each row), then print a newline after each row. For example, for the row [1, 2, 3], the output should be 1 2 3 (with a trailing space), followed by a newline.

Cheat sheet

Use nested loops to iterate over 2D arrays (jagged arrays) in C#:

for (int i = 0; i < array.Length; i++) {
    // Outer loop iterates over rows
    for (int j = 0; j < array[i].Length; j++) {
        // Inner loop iterates over columns
        // Access or modify array[i][j]
    }
}

The outer loop iterates over rows using array.Length, and the inner loop iterates over columns using array[i].Length. Access elements with array[i][j].

Try it yourself

// Write your code only inside the class. Do not write Main() or any code outside this class.
using System;

class PrintMatrix 
{
    public static void printMatrix(int[][] matrix) 
    {
        // 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