Coders Packet


By Dimple Singhvi

Using functions, arrays, conditional and logical operators, a simple tic-tac-toe game was created.

First we declare our char type array 'tictactoe' of size 10 and initialize it from 0 to 9, globally so we can access it from anywhere easily.

We declare and define the function board() of type void, to create a 3x3 square grid for the game.

We now declare and define the function checkwin(), that checks if player 1 won or player 2. Since it is of int type it returns 1 if any of the given conditions matches else it returns 0 implying the game is draw. Here we check for different conditions for wining by using if and else if ladder by matching the value of the array 'tictactoe' at different positions in the grid.

Now, we come to the main function of type int. Here we declare the variable 'player' of type int, initializing it with 1. We also declare variables 'i' and 'choice' of type int and 'mark' of type char for 'X' and 'O'. 

We first ask the player to enter it's choice, i.e a number between 1 and 9 as mentioned in the grid. The variable 'choice' stores this value. Now using conditional operator we check and decide the player's turn and assign 'O' to player 1 and 'X' to player 2. Now, using if and else if ladder we check the value of 'choice' with array 'tictactoe' at different positions and then assign the value of 'mark' to that particular position of the array 'tictactoe'. eg: if 'choice' was equal to 1 and 'tictactoe' at position 1 was equal to 1 we assign the value of 'mark' to 'tictactoe' at position 1.

Similarly we do this for all other positions and choices as well, i.e from 1 to 9. If none of the input values match the conditions we display "Invalid move" and use post decrement operator on player to decrease the value of 'player' by 1. We use cin.ignore() we ignore the value and using cin.get() we retake the value from the player. This helps us to make sure the value doesn't get overwritten. Once all conditions are checked we call the function checkwin() and assign its value to 'i'. Then use post increment operator on 'player' to increase the value of the player by 1. Hence implying that it was now the turn of player 2. This whole things runs on a do while loop till the value of 'i' was -1.

Now we call the board() function to draw the board and we check the value of 'i'. If the value of 'i' was 1 then we display the particular player who won, but if the value of 'i' was other than 1 we display that it was a draw.


Download project

Reviews Report

Submitted by Dimple Singhvi (dimplesinghvi)

Download packets of source code on Coders Packet