What is 2D Array In C#

Introduction 

The two-dimensional array is a data structure consisting of cells arranged in a two-dimensional grid, much like a table with rows and columns. It is also known as a multidimensional array. A 2D array is an array of arrays where each element is an array. The syntax for declaring a 2D array in C# is as follows.

Syntax  

dataType[,] arrayName = new dataType[rowSize, columnSize];

Where dataType specifies the type of data that the array will hold, arrayName is the array's name, rowSize is the number of rows in the array, and columnSize is the number of columns in the array.

For example, we can use the following code to declare a 2D array holding integers with three rows and four columns. 

int[,] myArray = new int[3, 4];

Once the 2D array is declared, we can access and manipulate its elements using two indices. The first index refers to the row number, and the second relates to the column number. For example, we can use the following code to access the element in the second row and third column of the myArray. 

int myElement = myArray[1, 2];

2D Array in C#

Access a 2D array in C#

A table with I rows and j columns is an equal representation of a 2-dimensional array. This method is used to determine whether any row in the matrix mat[] of size a * b that is sorted row-by-row and an array row[] is equal to the given array row[] in the array.

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

// Accessing an element in the 2D array
int element = myArray[1,2]; // This will return

In the program above, we have declared and initialized a 2D array named myArray with three rows and four columns. We then accessed an element in the second row (row index 1) and the third column (column index 2) using the syntax myArray[1,2]. You can also use loops to iterate over a 2D array and access all its elements. Here's an example,

/ Iterating over a 2D array using nested loops
for (int a = 0; a < myArray.GetLength(0); a++) {
    for (int b = 0; b < myArray.GetLength(1); b++) {
        Console.Write(myArray[a,b] + " ");
    }
    Console.WriteLine();
}

In this statement, we use nested loops to iterate over each element in the 2D array and print its value to the console. We use the GetLength method to get the length of each array dimension and use these values as the loop conditions.

internal class Class1
{
    // Main Method
  // C# implementation of the approach GFG
    static int a = 4;
    static int b = 2;

    // Function to find a row in the
    // given matrix using linear search
    static int linearCheck(int[,] ar, int[] arr)
    {
        for (int i = 0; i < a; i++)
        {
            // Assume that the current row matched
            // with the given array
            bool matched = true;

            for (int j = 0; j < b; j++)
            {

                // If any element of the current row doesn't
                // match with the corresponding element
                // of the given array
                if (ar[i, j] != arr[j])
                {

                    // Set matched to false and break;
                    matched = false;
                    break;
                }
            }

            // If matched then return the row number
            if (matched)
                return i + 1;
        }

        // No row matched with the given array
        return -1;
    }

    // Driver code
    static public void Main()
    {
        int[,] mat = { { 0, 0, 1, 0 },
                { 10, 9, 22, 23 },
                { 40, 40, 40, 40 },
                { 43, 44, 55, 68 },
                { 81, 73, 100, 132 },
                { 100, 75, 125, 133 } };
        int[] row = { 10, 9, 22, 23 };

        Console.Write(linearCheck(mat, row));
    }
}

This program implements a function to find a row in a 2D matrix using linear search. The program defines a class called Class1 with a static method called linearCheck that takes in a 2D integer array and a 1D integer array as parameters and returns the index of the row in the 2D matrix that matches the given 1D array. If no row matches, the function returns -1. The program also defines a Main method that initializes a 2D matrix and a 1D array and calls the linearCheck method with these parameters.

The program's output is the index of the row in the matrix that matches the given array. The linearCheck method works by iterating over each row in the matrix and comparing each element in the row to the corresponding component of the given array. If all features match, the function returns the current row's index. If no row matches, the process returns -1. 

Output  

Do a linear search on the matrix, just like you would on a 1-D array, and compare each row to the provided array. Print the row number of any matching row in the array; otherwise, display -1. The application of the strategy above is seen below. 

internal class Class1
{
  // Main Method
  // C# implementation of the approach GFG

    static int a = 2, b = 4;

    // Function that compares both the arrays
    // and returns -1, 0 and 1 accordingly
    static int compareRow(int[] a1, int[] a2)
    {
        for (int i = 0; i < b; i++)
        {
            // Return 1 if mid row is less than arr[]
            if (a1[i] < a2[i])
                return 1;

            // Return 1 if mid row is greater than arr[]
            else if (a1[i] > a2[i])
                return -1;
        }
        // Both the arrays are equal
        return 0;
    }
    // Function to find a row in the
    // given matrix using binary search
    static int binaryCheck(int[,] ar, int[] arr)
    {
        int l = 0, r = b - 1;
        while (l <= r)
        {
            int mid = (l + r) / 2;
            int temp = compareRow(GetRow(ar, mid), arr);

            // If current row is equal to the given
            // array then return the row number
            if (temp == 0)
                return mid + 1;

            // If arr[] is greater, ignore left half
            else if (temp == 1)
                l = mid + 1;

            // If arr[] is smaller, ignore right half
            else
                r = mid - 1;
        }

        // No valid row found
        return -1;
    }

    public static int[] GetRow(int[,] matrix, int row)
    {
        var rowLength = matrix.GetLength(1);
        var rowVector = new int[rowLength];

        for (var i = 0; i < rowLength; i++)
            rowVector[i] = matrix[row, i];

        return rowVector;
    }

    // Driver code
    public static void Main(String[] args)
    {
        int[,] mat = {{ 0, 0, 1, 0 },
                { 10, 9, 22, 23 },
                { 40, 40, 40, 40 },
                { 43, 44, 55, 68 },
                { 81, 73, 100, 132 },
                { 100, 75, 125, 133 }};
        int[] row = { 10, 9, 22, 23 };
        Console.WriteLine(binaryCheck(mat, row));
    }
}

This program implements the binary search algorithm for a row in a 2D matrix. The program takes in a 2D array mat and a 1D array row and searches for the row in the carpet. The compareRow function compares two matrix rows, a1 and a2, and returns one if a1 is less than a2, -1 if a1 is greater than a2, and 0 if they are equal. The binaryCheck function performs the binary search on the matrix to find the row that matches the row. It starts by setting the left index l to 0 and the correct index r to b-1, where b is the number of columns in the matrix.

The GetRow function is a utility function that takes in a 2D matrix and a row number and returns the row as a 1D array. It then repeatedly calculates the middle index mid, compares the middle row to the row using compareRow, and updates l and r accordingly until it finds the matching row or determines that it does not exist. Finally, the Main function creates a sample matrix mat and a sample row and calls binaryCheck to search for the row in the carpet. The program then outputs the index of the matching row.  

 

Conclusion 

In this article, you will learn about the code that taught us What 2D Array In C# is. Also, check out Working with Arrays in C# (code included), and check out Working with Arrays in C# (code included) 

FAQs

Q- What is a 2D array in C#?

A- the 2D or multidimensional array has two or more dimensions. In C#, a 2D array is declared by specifying the number of rows and columns: int[,] myArray = new int[3, 4];. This creates a 2D array with three rows and four columns, with each element initialized to its default value (0 for int).

Q- How do you access elements in a 2D array in C#?

A- Elements in a 2D array are accessed using their row and column indices. For example, to access the element in the second row and third column of a 2D array named myArray, you would use the syntax myArray[1, 2] (remember that array indices are zero-based in C#).


Similar Articles