0% found this document useful (0 votes)
4 views

Assignment 6

This document contains a C program for a Tic Tac Toe game. It includes functions to initialize the board, print the board, check for a win or draw, switch players, and make moves. The main function orchestrates the game flow until a player wins or the game ends in a draw.

Uploaded by

abhinavrao666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Assignment 6

This document contains a C program for a Tic Tac Toe game. It includes functions to initialize the board, print the board, check for a win or draw, switch players, and make moves. The main function orchestrates the game flow until a player wins or the game ends in a draw.

Uploaded by

abhinavrao666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Assignment 6 (Tic Tac Toe Game)

#include <stdio.h>

char board[3][3];
char player = 'X';

void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}

void printBoard() {
printf("\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(" %c ", board[i][j]);
if (j < 2) printf("|");
}
if (i < 2) printf("\n---|---|---\n");
}
printf("\n");
}

int checkWin() {
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player &&
board[i][2] == player) return 1;
if (board[0][i] == player && board[1][i] == player &&
board[2][i] == player) return 1;
}
if (board[0][0] == player && board[1][1] == player && board[2][2]
== player) return 1;
if (board[0][2] == player && board[1][1] == player && board[2][0]
== player) return 1;

return 0;
}

int checkDraw() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') return 0;
}
}
return 1;
}

void switchPlayer() {
player = (player == 'X') ? 'O' : 'X';
}

void makeMove() {
int row, col;
while (1) {
printf("Player %c, enter your move (row and column): ",
player);
scanf("%d %d", &row, &col);
if (row >= 1 && row <= 3 && col >= 1 && col <= 3 &&
board[row-1][col-1] == ' ') {
board[row-1][col-1] = player;
break;
} else {
printf("Invalid move! Try again.\n");
}
}
}

int main() {
initializeBoard();
while (1) {
printBoard();
makeMove();
if (checkWin()) {
printBoard();
printf("Player %c wins!\n", player);
break;
}
if (checkDraw()) {
printBoard();
printf("It's a draw!\n");
break;
}
switchPlayer();
}

return 0;
}

You might also like