C
  • Introduction
    • Fundamentals of a Program
    • Overview of C
    • Features of C
  • Installing Required Software
    • Setting Up VSCode for Windows
    • Setting Up VSCode for macOS
    • Setting Up VSCode for Ubuntu
  • Starting to write code
    • Compiling and Running Your Code
    • Creating Our First C Program
    • Errors and Warnings
    • Program: Writing a C Program to Display Your Name
    • Structure of a C Program
  • Basic Concepts
    • Comments in C
    • Preprocessor in C
    • The #include Statement
    • Displaying Output
    • Reading Input from the Terminal
    • Enums and Chars
    • Data Types and Variables
    • Format Specifiers
    • Command Line Arguments
    • Program: Calculating the Area of a Triangle
  • Operators
    • Converting Minutes to Years and Days
    • Basic Operators
    • Bitwise Operators
    • Program: Byte Sizes of Basic Data Types
    • cast and sizeof Operators
    • Operator Precedence
  • Control Flow
    • If-Else Statements
    • Program: Weekly Pay Calculation
    • Switch Statement
    • For Loop
    • While and Do-While Loops
    • Nested Loops and Loop Control
    • Program: Guess the Number
  • Arrays
    • Introduction to Arrays
    • Program: Prime Number Generator
    • Multidimensional Arrays
    • Program: simple Weather Program
    • Variable Length Arrays (VLAs)
  • Functions
    • Overview of Functions
    • Defining Functions
    • Arguments and Parameters
    • Returning Data from Functions
    • Variable Scoping
    • Program: Tic Tac Toe Game
    • Recursion
  • Strings
    • Defining a String
    • Constant Strings in C
    • Common String Functions
    • Program: Bubble Sort
    • Searching, Tokenizing, and Analyzing Strings
    • Converting Strings
  • Debugging
    • What is Debugging
    • Understanding the Call Stack
    • Common C Mistakes
    • Understanding Compiler Errors
  • Pointer
    • Defining Pointers
    • Accessing Pointers
    • Program: Pointer Demonstration
    • Pointers and Const
    • Void Pointers
    • String Pointers
    • Array Pointers
    • Utilizing Pointers with Functions
    • Pointer Arithmetic
  • Dynamic Memory Allocation
    • malloc, calloc, and realloc
    • Program: User Input String
    • Memory Deallocation
  • Structure
    • Structures and Arrays
    • Nested Structures
    • Structures and Pointers
    • Structures and Functions
    • Program: Structure pointers and Functions
  • File Input and Output
    • Accessing Files
    • Reading from a File
    • Program: Finding the Total Number of Lines in a Text File
    • Writing to a Text File
    • Finding Your Position in a File
    • Program: Converting Characters in a File to Uppercase
    • Program: Printing the Contents of a File in Reverse Order
  • The Standard C Library
    • Various Functions in C
    • Math Functions in C
    • Utility Functions in C
Powered by GitBook
On this page
  • Introduction
  • Algorithm
  • Pseudocode
  • Program Structure
  • 1. Header Files
  • 2. Constants
  • 3. Function Declarations
  • 4. Main Function
  • 5. Function Definitions
  • Conclusion

Was this helpful?

  1. Functions

Program: Tic Tac Toe Game

Introduction

In this section, we'll create a simple console-based Tic Tac Toe game in C. Tic Tac Toe is a classic two-player game where the goal is to form a line of three of your symbols (either 'X' or 'O') horizontally, vertically, or diagonally on a 3x3 grid.

Algorithm

  1. Initialize Board:

    • Create a 3x3 matrix representing the Tic Tac Toe board.

    • Initialize all cells with empty spaces.

  2. Display Board:

    • Display the current state of the board to the players.

  3. Get Player Move:

    • Ask the current player to input their move (row and column).

  4. Validate Move:

    • Check if the specified move is within the board boundaries.

    • Verify that the selected cell is empty.

  5. Update Board:

    • If the move is valid, update the board with the current player's symbol.

  6. Check for Win:

    • Check if the current player has won horizontally, vertically, or diagonally.

    • If a win is detected, declare the current player as the winner.

  7. Check for Tie:

    • Check if the board is full (all cells are filled) without a winner.

    • If a tie is detected, declare the game as a tie.

  8. Switch Player:

    • Switch to the other player (from 'X' to 'O' or vice versa).

  9. Repeat:

    • Repeat steps 2-8 until a win or a tie is achieved.

Pseudocode

function initializeBoard():
    for each row in board:
        for each cell in row:
            cell = ' '

function displayBoard():
    print("  0 1 2")
    for i from 0 to 2:
        print(i, end=" ")
        for j from 0 to 2:
            print(board[i][j], end=" ")
        print()

function isMoveValid(row, col):
    return (0 <= row < 3) and (0 <= col < 3) and (board[row][col] == ' ')

function checkForWin(player):
    for i from 0 to 2:
        if (board[i][0] == player and board[i][1] == player and board[i][2] == player) or
           (board[0][i] == player and board[1][i] == player and board[2][i] == player):
            return true

    if (board[0][0] == player and board[1][1] == player and board[2][2] == player) or
       (board[0][2] == player and board[1][1] == player and board[2][0] == player):
        return true

    return false

function isBoardFull():
    for each row in board:
        for each cell in row:
            if cell is empty:
                return false
    return true

function main():
    initializeBoard()
    currentPlayer = 'X'

    repeat:
        displayBoard()

        print("Player", currentPlayer + ",", "enter your move (row and column): ")
        row, col = getUserInput()

        if isMoveValid(row, col):
            board[row][col] = currentPlayer

            if checkForWin(currentPlayer):
                displayBoard()
                print("Player", currentPlayer, "wins!")
                break

            if isBoardFull():
                displayBoard()
                print("The game is a tie!")
                break

            currentPlayer = switchPlayer(currentPlayer)
        else:
            print("Invalid move. Try again.")

    end repeat

This pseudocode outlines the key steps of the Tic Tac Toe game, providing a structured guide for the implementation in C. Feel free to use this as a reference when coding the actual program.

Program Structure

1. Header Files

#include <stdio.h>
#include <stdlib.h>

2. Constants

#define SIZE 3

Define constants for the board size.

3. Function Declarations

void initializeBoard(char board[SIZE][SIZE]);
void displayBoard(char board[SIZE][SIZE]);
int isMoveValid(int row, int col, char board[SIZE][SIZE]);
int isBoardFull(char board[SIZE][SIZE]);
int checkForWin(char board[SIZE][SIZE], char player);

4. Main Function

int main() {
    char board[SIZE][SIZE];
    char currentPlayer = 'X';
    int row, col;

    initializeBoard(board);

    do {
        displayBoard(board);

        printf("Player %c, enter your move (row and column): ", currentPlayer);
        scanf("%d %d", &row, &col);

        if (isMoveValid(row, col, board)) {
            board[row][col] = currentPlayer;

            if (checkForWin(board, currentPlayer)) {
                displayBoard(board);
                printf("Player %c wins!\n", currentPlayer);
                break;
            }

            if (isBoardFull(board)) {
                displayBoard(board);
                printf("The game is a tie!\n");
                break;
            }

            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        } else {
            printf("Invalid move. Try again.\n");
        }
    } while (1);

    return 0;
}

5. Function Definitions

initializeBoard

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

displayBoard

void displayBoard(char board[SIZE][SIZE]) {
    printf("\n  ");
    for (int i = 0; i < SIZE; i++) {
        printf("%d ", i);
    }
    printf("\n");

    for (int i = 0; i < SIZE; i++) {
        printf("%d ", i);
        for (int j = 0; j < SIZE; j++) {
            printf("%c ", board[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

isMoveValid

int isMoveValid(int row, int col, char board[SIZE][SIZE]) {
    return (row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == ' ');
}

isBoardFull

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

checkForWin

int checkForWin(char board[SIZE][SIZE], char player) {
    for (int i = 0; i < SIZE; 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;
        }
    }

    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;
}

Conclusion

This enhanced Tic Tac Toe program provides a clearer structure and includes pseudocode for key functions. Feel free to explore additional features and improvements. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

PreviousVariable ScopingNextRecursion

Was this helpful?