C Project – Tic Tac Toe Game

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

#include <stdio.h>
#include<conio.h>
// 2 D Array
char board[3][3] = 
{
    {' ', ' ', ' '},
    {' ', ' ', ' '},
    {' ', ' ', ' '}
};

void printBoard() 
{
    printf("-------------\n");
    for (int i = 0; i < 3; i++)    // outer
    {
        printf("| ");
        for (int j = 0; j < 3; j++) // inner 
        {
            printf("%c",board[i][j]);
            printf( " | ");
        }
        printf("\n-------------\n");
    }
}
                         // player=X or O
int checkWin(char player) {
    // Check rows and columns
    for (int i = 0; i < 3; i++) 
    {
        if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
            (board[0][i] == player && board[1][i] == player && board[2][i] == player)) 
            {
               return 1;
            }
    }

    // Check diagonals
    if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
        (board[0][2] == player && board[1][1] == player && board[2][0] == player)) 
        {
            return 1;
       }

    return 0;
}

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

int main()
 {
    char currentPlayer = 'X';
    int row, col;
    printf("Welcome to Tic Tac Toe!\n");
    printBoard();

    while (1) 
    {
        printf("Player %c enter your move (row and column: 1-3): ",currentPlayer);
        scanf("%d",&row);
        scanf("%d",&col);
        row--; col--; // Adjust for 0-based index

        if (row < 0 || row > 2 || col < 0 || col > 2) 
        {
            printf("Invalid input. Try again.\n");
            continue;
        }

        if (board[row][col] != ' ') 
        {
            printf("Cell already taken. Try again.\n");
            continue;
        }

        board[row][col] = currentPlayer;
        printBoard();

        if (checkWin(currentPlayer)) 
        {
            printf("Congrats Player %c  wins!\n",currentPlayer);
            break;
        } 
        else if (isBoardFull()) 
         {
            printf("It's a draw!\n");
            break;
        }
         else 
         {
            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        }
    }

    return 0;
}

 

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *