< Previous | Contents | Next >

Indexing Multidimensional Arrays

The next thing I do in the program is display the tic-tac-toe board. But before I get into the details of that, I want to explain how to index an individual array element. You index an individual element of a multidimensional array by supplying a value for each dimension of the array. Thats what I do to place an X in the array where a space was:

board[1][0] = ’X’;

The previous code assigns the character to the element at board[1][0] (which was ’ ’). Then I display the tic-tac-toe board after the move the same way I displayed it before the move.

for (int i = 0; i < ROWS; ++i)

{

106 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


for (int j = 0; j < COLUMNS; ++j)

{

cout << board[i][j];

}


cout << endl;

}

By using a pair of nested for loops, I move through the two-dimensional array and display the character elements as I go, forming a tic-tac-toe board.