Problem with Multi-dimensional Arrays

I'm writing a program to play tic-tac-toe using multi-dimensional arrays but I'm having trouble plugging in the x's and o's because the indexes only exist within that first nested for loop. Any suggestions? By the way, I'm a beginner so be nice ;)

cout << "Play yourself in tic-tac-toe!! \n"
<< "";

char array[3][3];
char number = '1' ;

for (int index1=0; index1<3; index1++)
{
for (int index2=0; index2<3; index2++)
{
array[index1][index2] = number;
cout << array[index1][index2] << " ";
number++;

cout << endl;
} }

int option;
int turncounter;
char turn;

for (turncounter = 1; turncounter < 10; turncounter++)
{
if ((turncounter % 2) == 0)
{
turn = 'X';
}
else
{
turn = 'O';
}
cout << "It's " << turn << "'s turn. \n";
cout << "Enter the number where you want to put an " << turn << ". \n";
cin >> option;
if (array[index1][index2] == option)
{
array[index1][index2] = turn;
}
}

cout << "Congratulations! You played yourself! \n";

return 0;
First of all - please, use code tags ([.code] [./code], without dots).
"because the indexes only exist withing that first nested for loop"

You are confusing yourself by trying to create a mapping between a two dimensional and a one dimensional array.

I recommend that you just don't do that. Make the user give you the row and column to place his piece.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  while (true)
  {
    cout << "Enter the row (1-3) and column (1-3) to put an " << turn << ": ";
    int row, column;
    cin >> row >> column;
    row--;
    column--;
    if (array[row][column] != ' ')
    {
      cout << "Try again.\n";
      continue;
    }
    else
    {
      array[row][column] = turn;
      break;
    }
  }

Hope this helps.
Last edited on
Topic archived. No new replies allowed.