Topic Overview

Welcome to today's session on "Mastering Array Traversal and Manipulation in C#". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. Picture it as an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in C#.

Creating Multidimensional Arrays

To construct a multidimensional array in C#, we use arrays of arrays. Here are examples to demonstrate how to create and work with 2D static arrays.

using System;

class Solution {
    public static void Main(string[] args) {
        // Creating a 2D array
        int[,] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Printing the 2D array
        for (int i = 0; i < array.GetLength(0); i++) {
            for (int j = 0; j < array.GetLength(1); j++) {
                Console.Write(array[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

/*
Prints:
1 2 3 
4 5 6 
7 8 9 
*/
Indexing in Multidimensional Arrays

All indices in C# arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building. Here's how you can do it:

class Solution {
    public static void Main(string[] args) {
        int[,] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Accessing an element
        Console.WriteLine(array[1, 0]);  // Outputs: 4
    }
}

We visited the element 4 in the array by its position. The number [1] refers to the second inner array, and [0] refers to the first element of that array.

Finding the Number of Rows and Columns

C# offers various ways to manage multidimensional arrays. For instance, you can determine the number of rows (floors) and columns (units on each floor):

class Solution {
    public static void Main(string[] args) {
        int[,] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Finding the number of rows
        int numFloors = array.GetLength(0);
        Console.WriteLine(numFloors);  // Outputs: 3

        // Finding the number of columns
        int numUnits = array.GetLength(1);
        Console.WriteLine(numUnits);  // Outputs: 3
    }
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal