In this article, we will learn how to print a 2D array to the console using C#. Whether we are handling complex data structures or simply organizing information efficiently, understanding how to manipulate 2D arrays is a valuable skill.

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

Understanding 2D Arrays

First, let’s understand what 2D arrays are. A 2D or two-dimensional array is a data structure that organizes data in a grid consisting of rows and columns.

To learn more about 2D arrays, check out our article C# Back to Basics – Arrays.

In essence, 2D arrays are arrays of arrays, with each sub-array representing a row. To better illustrate how this kind of array is structured, we will learn how to print a chessboard-style 2D array to the console. 

Create a 2D Array Chessboard

Now that we know what a 2D array is, let’s learn how to print one to the console.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

For it, we will create a new class

public static class Print2DArrayChessBoard
{
    private static readonly string[,] board = new string[8, 8]
    {
        { "R", "N", "B", "Q", "K", "B", "N", "R" },
        { "P", "P", "P", "P", "P", "P", "P", "P" },
        { "-", "-", "-", "-", "-", "-", "-", "-" },
        { "-", "-", "-", "-", "-", "-", "-", "-" },
        { "-", "-", "-", "-", "-", "-", "-", "-" },
        { "-", "-", "-", "-", "-", "-", "-", "-" },
        { "P", "P", "P", "P", "P", "P", "P", "P" },
        { "R", "N", "B", "Q", "K", "B", "N", "R" }
    };
}

Here, we define the Print2DArrayChessBoard class that holds the data and methods related to printing out our chessboard-themed 2D array. Within this class, we initialize an array, board. This array holds 8 rows and 8 columns of data, just like a normal chessboard. The first and last two rows contain letters that represent the types of chess pieces, while the center four rows represent empty squares on the board.

Next, let’s define the GetBackgroundColorOfSquare() method to alternate the background color of each square on the board:

public static ConsoleColor GetBackgroundColorOfSquare(int row, int col)
{
    return (row + col) % 2 == 0 ? ConsoleColor.White : ConsoleColor.Black;
}

With this method, we calculate the background color for each square based on its coordinates. We return a ConsoleColor, an enum from the System namespace that allows us to access a variety of colors for console apps.

We determine which square should be black and which should be white by adding the row and column indices together. If the result is even (the remainder of the sum divided by two is zero), we set the background to white, otherwise, we set the background to black.

Display the 2D Array Chessboard

Now, let’s create a method in our Print2DArrayChessBoard class that displays our chessboard:

public static void Display()
{
    for (int i = 0; i < board.GetLength(0); i++)
    {
        for (int j = 0; j < board.GetLength(1); j++)
        {
            Console.BackgroundColor = GetBackgroundColorOfSquare(i, j);
            Console.ForegroundColor = Console.BackgroundColor == ConsoleColor.White 
                ? ConsoleColor.Black 
                : ConsoleColor.White;

            Console.Write(" " + board[i, j] + " ");
            Console.ResetColor();
        }

        Console.WriteLine();
    }
}

First, we define the Display() method, which organizes our chessboard, assigns the correct background color and displays it to the console.

Within this method, we create two for loops, one nested within the other. No matter the kind of 2D array (be it a chessboard or otherwise), using a nested for loop can be a useful way to print it to the console. 

Let’s run through the first loop to get an idea of how this works.

In the outer for loop we access the first row { "R", "N", "B", "Q", "K", "B", "N", "R" } at index 0. Then, we move to the inner for loop. Here, we access the first item in this row at index 0. That means we will be targeting the first letter “R” in this row.

Then, we change the background color of “R” using our GetBackgroundColorOfSquare() method. Because both the row and column indices are 0, their sum is 0, which means the remainder, when divided by 2, is also 0, setting the background color to white.

Additionally, we need to make sure the letter will be visible in the console. Since the background color is white, the text must be set to black.

After that, we print the letter to the console surrounded by 2 spaces. We add these spaces so the letter is in the center of the square. Finally, we reset the console color and move to the next row with Console.WriteLine().

Print the 2D Array to the Console

Now that we have our code ready, all we need to do is call our method in the Program class:

Print2DArrayChessBoard.Display();

After we call our Display() method from the Print2DArrayChessBoard class, our chessboard should appear in the console:

Screenshot of the 2D array chessboard printed to the console

Looks like a chessboard, right? 

Conclusion

In this article, we saw how to print a chessboard-style 2D array to the console. This method can be adapted to print any kind of 2D array, making it useful for applications that need clear data visualization.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!