Tic Tac Toe in C
Tic Tac Toe is the perfect first board game to program: a 3 × 3 grid, two players (X and O), and a simple goal: get three in a row. Behind it are skills you'll use in every game: storing a board in a 2D array, checking that a move is valid, and testing for a win or a draw after each move.
In this project you will build a two-player version and then a version where you play against a computer that tries to win and blocks your winning moves.
What You Will Learn
- How to store a game board in a 2D
chararray. - How to print the board neatly.
- How to read and validate a move (range and empty cell).
- How to check rows, columns and diagonals for a win.
- How to detect a draw and switch players.
- How to write a simple computer opponent.
Tic Tac Toe in C Explained
Exam definition: The board is stored as a two-dimensional array char board[3][3], where each cell holds 'X', 'O' or ' ' (empty). A player wins if any of the 8 lines (3 rows, 3 columns, 2 diagonals) contains three equal non-empty marks. The game is a draw when all 9 cells are filled and nobody has won.
Memory trick: To check a win, remember "3 + 3 + 2 = 8": 3 rows, 3 columns, 2 diagonals. A game can last at most 9 moves, and nobody can win before move 5.
Syntax: Board and Win Check
char board[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
/* row r is a win if all three cells equal p */
board[r][0] == p && board[r][1] == p && board[r][2] == p
/* diagonals */
board[0][0] == p && board[1][1] == p && board[2][2] == p
board[0][2] == p && board[1][1] == p && board[2][0] == p
Rows and columns are typed as 1-3 by the player, stored as 0-2 in the array:
col 1 col 2 col 3
row 1 [0][0] | [0][1] | [0][2]
row 2 [1][0] | [1][1] | [1][2]
row 3 [2][0] | [2][1] | [2][2]
Example 1: Two-Player Tic Tac Toe
#include <stdio.h>
char board[3][3];
void init_board(void)
{
int r, c;
for (r = 0; r < 3; r++)
for (c = 0; c < 3; c++)
board[r][c] = ' ';
}
void print_board(void)
{
int r;
for (r = 0; r < 3; r++)
{
printf(" %c | %c | %c\n", board[r][0], board[r][1], board[r][2]);
if (r < 2)
printf("---+---+---\n");
}
}
int is_winner(char p)
{
int i;
for (i = 0; i < 3; i++)
{
if (board[i][0] == p && board[i][1] == p && board[i][2] == p) return 1; /* row */
if (board[0][i] == p && board[1][i] == p && board[2][i] == p) return 1; /* column */
}
if (board[0][0] == p && board[1][1] == p && board[2][2] == p) return 1; /* diagonal */
if (board[0][2] == p && board[1][1] == p && board[2][0] == p) return 1; /* anti-diagonal */
return 0;
}
int main(void)
{
int moves = 0, row, col;
char player = 'X';
init_board();
while (moves < 9)
{
printf("Player %c, enter row and column (1-3): ", player);
if (scanf("%d %d", &row, &col) != 2)
return 1;
if (row < 1 || row > 3 || col < 1 || col > 3)
{
printf("Out of range, try again.\n");
continue;
}
if (board[row - 1][col - 1] != ' ')
{
printf("Cell already taken, try again.\n");
continue;
}
board[row - 1][col - 1] = player;
moves++;
print_board();
if (is_winner(player))
{
printf("Player %c wins in %d moves!\n", player, moves);
return 0;
}
player = (player == 'X') ? 'O' : 'X';
}
printf("It's a draw!\n");
return 0;
}
Output
Player X, enter row and column (1-3): 1 1 X | | ---+---+--- | | ---+---+--- | | Player O, enter row and column (1-3): 2 2 X | | ---+---+--- | O | ---+---+--- | | Player X, enter row and column (1-3): 1 2 X | X | ---+---+--- | O | ---+---+--- | | Player O, enter row and column (1-3): 1 1 Cell already taken, try again. Player O, enter row and column (1-3): 3 3 X | X | ---+---+--- | O | ---+---+--- | | O Player X, enter row and column (1-3): 1 3 X | X | X ---+---+--- | O | ---+---+--- | | O Player X wins in 5 moves!
Code Explanation
init_board()fills all 9 cells with a space, meaning "empty".- The player types 1–3, and the program subtracts 1 to get the array index 0–2.
- Two checks protect the board: the numbers must be in range, and the cell must be empty. On a bad move,
continueasks the same player again without counting a move. - After each valid move,
is_winner()checks all 8 lines for the current player only (only they could have just won). player = (player == 'X') ? 'O' : 'X';switches turns.- If 9 moves pass with no winner, the loop ends and the game is a draw.
How the Game Loop Works
while moves < 9:
read move ─► invalid? ─► message, same player again
│
place mark, moves++, print board
│
winner? ─► yes ─► announce, stop
│ no
switch player
after 9 moves with no winner ─► draw
Example 2: Play Against the Computer
You are X and choose a cell number 1–9. The computer (O) uses three simple rules: 1) win if it can, 2) block your winning move, 3) otherwise take the centre, then the first free cell.
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
#include <stdio.h>
char b[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
const int lines[8][3] = {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, /* rows */
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, /* columns */
{0, 4, 8}, {2, 4, 6} /* diagonals */
};
int wins(char p)
{
int i;
for (i = 0; i < 8; i++)
if (b[lines[i][0]] == p && b[lines[i][1]] == p && b[lines[i][2]] == p)
return 1;
return 0;
}
/* a free cell that would complete a line for p, or -1 */
int winning_cell(char p)
{
int i;
for (i = 0; i < 9; i++)
if (b[i] == ' ')
{
b[i] = p; /* try it */
if (wins(p)) { b[i] = ' '; return i; }
b[i] = ' '; /* undo */
}
return -1;
}
int computer_move(void)
{
int i = winning_cell('O'); /* 1. win */
if (i == -1) i = winning_cell('X'); /* 2. block */
if (i == -1 && b[4] == ' ') i = 4; /* 3. centre */
for (int k = 0; i == -1 && k < 9; k++)
if (b[k] == ' ') i = k; /* 4. first free cell */
return i;
}
void show(void)
{
printf(" %c | %c | %c\n---+---+---\n %c | %c | %c\n---+---+---\n %c | %c | %c\n",
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
}
int main(void)
{
int moves = 0, cell;
while (moves < 9)
{
printf("Your move (1-9): ");
if (scanf("%d", &cell) != 1) return 1;
if (cell < 1 || cell > 9 || b[cell - 1] != ' ')
{
printf("Invalid move.\n");
continue;
}
b[cell - 1] = 'X';
moves++;
if (wins('X')) { show(); printf("You win!\n"); return 0; }
if (moves == 9) break;
cell = computer_move();
b[cell] = 'O';
moves++;
printf("Computer plays %d\n", cell + 1);
show();
if (wins('O')) { printf("Computer wins!\n"); return 0; }
}
printf("It's a draw!\n");
return 0;
}
Output
Your move (1-9): 1 Computer plays 5 X | | ---+---+--- | O | ---+---+--- | | Your move (1-9): 2 Computer plays 3 X | X | O ---+---+--- | O | ---+---+--- | | Your move (1-9): 9 Computer plays 7 X | X | O ---+---+--- | O | ---+---+--- O | | X Computer wins!
- A one-dimensional array of 9 cells plus a table of the 8 winning
linesmakes the win check a single loop. winning_cell()tries each empty cell, checks for a win and undoes the move. This "try and undo" idea is the heart of game AI.- After you play 2, X threatens 1-2-3, so the computer blocks at 3. After you play 9, O can complete 3-5-7, so it wins at 7.
- This computer is not perfect. A perfect player uses the minimax algorithm, which tries every possible future game.
Important Points to Remember
- Store the board in char board[3][3] (or
char b[9]);' '= empty. - Convert user input 1–3 to index 0–2 by subtracting 1.
- Validate every move: in range and cell empty.
- Win = any of 8 lines with three equal marks.
- Draw = 9 moves and no winner.
- Simple AI: win, block, centre, any free cell.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Using row and column directly as indexes | board[3][3] is out of bounds | Subtract 1 from the user's numbers |
| Not checking if the cell is empty | Players overwrite each other's marks | Check board[r][c] == ' ' |
| Forgetting one diagonal | Some wins are never detected | Check both diagonals (8 lines total) |
| Switching player after an invalid move | The wrong player gets the next turn | continue before switching |
| Checking for a draw before checking for a win | A winning 9th move is called a draw | Check the win first |
Tic Tac Toe Practice Questions
- How is the Tic Tac Toe board stored in C?
- How many winning lines are there? Name them.
- When is the game a draw?
- Why do we subtract 1 from the row and column entered by the user?
- Describe the four rules of the simple computer player.
Show answers
- As a 2D array
char board[3][3]with 'X', 'O' or ' ' in each cell. - 8: three rows, three columns and two diagonals.
- When all 9 cells are filled and no player has three in a row.
- The user types 1–3, but C array indexes start at 0.
- Take a winning cell if possible, otherwise block the opponent's winning cell, otherwise take the centre, otherwise take the first free cell.
Coding Exercise
Write a function char check_board(char b[3][3]) that returns 'X' or 'O' if that player has won, 'D' for a full board with no winner, and ' ' if the game is still going. Test it on three boards.
Show solution
#include <stdio.h>
char check_board(char b[3][3])
{
int i, r, c, empty = 0;
for (i = 0; i < 3; i++)
{
if (b[i][0] != ' ' && b[i][0] == b[i][1] && b[i][1] == b[i][2]) return b[i][0];
if (b[0][i] != ' ' && b[0][i] == b[1][i] && b[1][i] == b[2][i]) return b[0][i];
}
if (b[1][1] != ' ' && ((b[0][0] == b[1][1] && b[1][1] == b[2][2]) ||
(b[0][2] == b[1][1] && b[1][1] == b[2][0])))
return b[1][1];
for (r = 0; r < 3; r++)
for (c = 0; c < 3; c++)
if (b[r][c] == ' ')
empty++;
return empty ? ' ' : 'D';
}
void report(const char *name, char b[3][3])
{
char r = check_board(b);
if (r == 'D') printf("%s: draw\n", name);
else if (r == ' ') printf("%s: game in progress\n", name);
else printf("%s: %c wins\n", name, r);
}
int main(void)
{
char a[3][3] = {{'O', 'X', 'X'}, {'X', 'O', ' '}, {' ', ' ', 'O'}};
char d[3][3] = {{'X', 'O', 'X'}, {'X', 'O', 'O'}, {'O', 'X', 'X'}};
char p[3][3] = {{'X', ' ', ' '}, {' ', 'O', ' '}, {' ', ' ', ' '}};
report("Board A", a);
report("Board B", d);
report("Board C", p);
return 0;
}
Board A: O wins Board B: draw Board C: game in progress
Quick Quiz: Tic Tac Toe (MCQ)
-
How many winning lines does a 3×3 board have?
A) 6 B) 8 C) 9 D) 3
-
The user enters row 3, column 2. Which array element is used?
A) board[3][2] B) board[2][1] C) board[2][2] D) board[1][2]
-
The earliest move on which someone can win is:
A) 3 B) 4 C) 5 D) 6
-
Maximum number of moves in one game:
A) 8 B) 9 C) 10 D) 6
-
The algorithm used for a perfect Tic Tac Toe player is:
A) Binary search B) Minimax C) Bubble sort D) Hashing
Show answers
- B: 8.
- B: board[2][1].
- C: move 5 (X's third mark).
- B: 9.
- B: minimax.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Board | char board[3][3], ' ' = empty |
|---|---|
| User input | 1–3, index = input − 1 |
| Valid move | In range and cell empty |
| Win lines | 8 = 3 rows + 3 columns + 2 diagonals |
| Draw | 9 moves, no winner |
| Simple AI | Win, block, centre, any |
| Perfect AI | Minimax |
Frequently asked questions
- How do you check for a win in Tic Tac Toe in C?
- Check all 8 lines (3 rows, 3 columns, 2 diagonals) for three equal non-empty marks.
- Which data structure is used for the board?
- A 2D char array of size 3 × 3 (or a 1D array of 9 cells).
- How does a simple computer opponent choose a move?
- It tries each empty cell: first to win, then to block, otherwise it takes the centre or any free cell.
Remember
- 3 + 3 + 2 = 8 winning lines.
- Validate the move, place it, check win, then switch player.
Next Topic
Next lesson: Quiz Game in C. You will store questions in an array of structures and build a quiz game with a score.