How to put char ('X') to int array?

Just taking your question as it is, I can imagine two ways I’d do it without getting too fancy.

The first one would be to use two arrays. One for holding the numbers (and int array), one for holding the player input (a char array holding “x” and “o”). This could look like this:

public class Program
{
    public static void Main()
    {
        int width = 10;
        int height = 10;

        char[,] playerBoard = new char[width, height];
        int[,] numberedBoard = new int[width, height];

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // Fill the numbered board with 1 to 100
                numberedBoard[x, y] = x * width + y + 1;

                // And the player board with emptyness
                playerBoard[x, y] = ' ';
            }
        }

        System.Console.WriteLine("Number at x = 3 / y = 5: " + numberedBoard[3, 5]);
        System.Console.WriteLine("Current owner of x = 3 / y = 5: \"" + playerBoard[3, 5] + "\"");

        // Let's change the owner of x = 3 and y = 5
        playerBoard[3, 5] = 'X';

        System.Console.WriteLine("New owner of x = 3 / y = 5: \"" + playerBoard[3, 5] + "\"");
    }
}

A second solution could be to create an object to fit your needs, and have an array of this one. The benefit is that you only have one array, and each cell holds all the information relevant to this cell. Consider the following:

using System;

public class Program
{
    struct BoardEntry {
        public int number;
        public char owner;
    }

    public static void Main()
    {
        int width = 10;
        int height = 10;

        BoardEntry[,] board = new BoardEntry[width, height];

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // For each "cell" of the board, we create a new instance of
                // BoardEntry, holding the number for this cell and a possible ownage.
                board[x, y] = new BoardEntry() {
                    number = x * width + y + 1,
                    owner=" "
                };
            }
        }

        // You can access each of those instances with `board[x,y].number` and `board[x,y].owner`

        System.Console.WriteLine("Number at x = 3 / y = 5: " + board[3, 5].number);
        System.Console.WriteLine("Current owner of x = 3 / y = 5: \"" + board[3, 5].owner + "\"");

        // Let's change the owner of x = 3 and y = 5
        board[3, 5].owner="X";
        System.Console.WriteLine("New owner at x = 3 / y = 5: \"" + board[3, 5].owner + "\"");
    }
}

It seems like you are new to programming, so the first solution might be easier to understand and use right now, but I suggest you read at some point a little bit into what structs and classes are, because they let you do some really powerful things, like in this case bundle the relevant information that belongs together.

Leave a Comment