< Previous | Contents | Next >
Introducing the Tic-Tac-Toe Board
The Tic-Tac-Toe Board program displays a tic-tac-toe board. The program displays the board and declares X the winner. Although the program could have been written using a one-dimensional array, it uses a two-dimensional array to represent the board. Figure 3.5 illustrates the program.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 3 folder; the filename is tic-tac-toe_board.cpp.
Figure 3.5
The tic-tac-toe board is represented by a two-dimensional array.
104 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble
// Tic-Tac-Toe Board
// Demonstrates multidimensional arrays #include <iostream>
using namespace std;
int main()
{
const int ROWS = 3; const int COLUMNS = 3;
char board[ROWS][COLUMNS] = { {’O’, ’X’, ’O’},
{’ ’, ’X’, ’X’},
{’X’, ’O’, ’O’} };
cout << "Here’s the tic-tac-toe board:\n"; for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLUMNS; ++j)
{
cout << board[i][j];
}
cout << endl;
}
cout << "\n’X’ moves to the empty location.\n\n"; board[1][0] = ’X’;
cout << "Now the tic-tac-toe board is:\n"; for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLUMNS; ++j)
{
cout << board[i][j];
}
cout << endl;
}
Using Multidimensional Arrays 105
cout << "\n’X’ wins!";
return 0;
}