A Tic-Tac-Toe program in C

Beginners code hub
By -
0
#include <stdio.h>

char board[3][3] = {
    {'1', '2', '3'},
    {'4', '5', '6'},
    {'7', '8', '9'}
};

void displayBoard() {
    printf("\n %c | %c | %c\n---|---|---\n %c | %c | %c\n---|---|---\n %c | %c | %c\n",
           board[0][0], board[0][1], board[0][2],
           board[1][0], board[1][1], board[1][2],
           board[2][0], board[2][1], board[2][2]);
}

// Further implementation of the game...
    

Steps of program 

1. Initialize the Game Board:


A 3x3 array (like a matrix) is used to represent the board.


Each cell is initially filled with numbers (1 to 9) or empty spaces to indicate the positions available for marking.



2. Display the Board:


The program defines a function to print the current state of the board on the screen.


The board is displayed with clear row and column divisions (e.g., X | O | X).



3. Take User Input:


Players take turns choosing a position on the board by entering the corresponding number (1 to 9).


The program validates the input to ensure the position is not already occupied and is within range.



4. Update the Board:


After a valid move, the program updates the chosen position with the player's symbol ('X' or 'O').



5. Check for a Winner:


After each turn, the program checks if there is a winner. A player wins if:


Three of their symbols are aligned horizontally.


Three of their symbols are aligned vertically.


Three of their symbols are aligned diagonally.



If there is a winner, the program announces the result and ends the game.



6. Check for a Draw:


If all cells are filled and no player has won, the game ends in a draw.



7. Switch Player Turns:


After each valid move, the program switches the turn to the other player.



8. Game Loop:


The game continues in a loop until there is a winner or the game ends in a draw.


Key Functions in the Program


1. Display Function:


Prints the current board state.


2. Input Validation Function:


Ensures the position entered by the player is valid and unoccupied.


3. Winner Check Function:


Checks all possible winning conditions (rows, columns, diagonals).


4. Turn Manager:


Alternates between Player 1 and Player 2.



Example

A Tic-Tac-Toe program in C


Tags:

Post a Comment

0Comments

Post a Comment (0)