Lecture 17:  Multidimensional Arrays

Activity:



Are you ready to play tic-tac-toe?

Today we learned about multidimensional arrays.  One problem that includes a 2-Dimensional object is a tic-tac-toe board with 9 squares.  A typical tic-tac-toe board looks like the following:

   |   |
___|___|___
   |   |
___|___|___
   |   |
   |   |

Two players compete to win the game.  Traditionally, players are either "X" or "O" and they take turns selecting a square for which to place their letter.  A player wins if they have created a line (vertically, horizontally, or diagonally) containing their letter.

You will be writing functions that involve a tic-tac-toe board declared as the following:
char tic_tac_toe[3][3] =
        {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};

1.  Write a function to place a character ('x' or 'o') at a certain position in the board. Check to make sure the
character parameter is indeed an 'x' or an 'o' and that the row and column are proper indices for the tic_tac_toe
board. Also, make sure that the position at row and column is not already filled with a (non-space) character. To
help you out, here's the function prototype:

void place_character_at (char ch, char tic_tac_toe[3][3], int row, int column);

As always, follow the appropriate design steps when writing the function.  (Note that players are placing lowercase 'x' and 'o' on the board.  For simplicity, uppercase 'X' and 'O' will not be allowed as letters on the board.)
 
 
 
 
 
 
 
 
 
 
 

2.  Write a function to print out the current state of the board. You want the printout to "look" like the board if we
were looking at it on paper. Don't worry about the separating lines.  Here's the function prototype:

void print_board (char tic_tac_toe[3][3]);
 
 
 
 
 
 
 
 
 
 
 
 

3.  Write a function to check if 'x' or 'o' has won. Hint: find all possible winning configurations for tic tac toe. If 'x' or 'o' has won, print a message declaring that there is a winner and state who the winner is. Also, return 1 if there is a winner. If no one has won, return 0. Here's the prototype:

int has_won (char tic_tac_toe[3][3]);