You are on page 1of 20

C++ Programs’ collection

Program 1: if(!(i%j)) //if ( i%j==0)


/* This program displays all printable characters, break; // if factor found, not prime
including the extended character set, if one
exists. if(j>i/2) cout << i << " is prime\n";

*/ }

#include <iostream> return 0;


void main() }
{ Program 3: /* a program that Changes case
without using the built-in functions toupper() or
unsigned char ch; tolower() */
ch = 32; #include <iostream.h>
while(ch) { int main()
{
cout << ch; char ch;
int changes = 0;
ch++;
cout << "Enter your text \n\t and a period to
} stop.\n";
do {
return; cin >> ch;
if(ch >= 'a' && ch <= 'z') //if case
}
is lower
Program 2: {
ch -= (char) 32; //cast to Char
/* This program finds the prime numbers
changes++;
from 2 to 1000. */ cout << ch;
#include <iostream.h> }
else if(ch >= 'A' && ch <= 'Z') //if upper case
int main() {
ch += (char) 32;
{ int i, j; changes++;
cout << ch;
for(i=2; i<1000; i++)
}
{ } while(ch != '.');
cout << "\nCase changes: " << changes << "\n";
//see if number is evenly divisible return 0;
}
Functions
for(j=2; j <= i/2; j++)
Program 1:// demo of function calling

Adama University Page 1


Department of computer science
C++ Programs’ collection

#include <iostream.h> func1();

int mul(int , int ); // mul()'s prototype }

int main() return 0;

{ }

int answer; void func1()

answer = mul(10, 11); // assign return value {

cout << "The answer is " << answer; cout << "count: " << count<<endl;

return 0; func2();

} }

// This is function definition void func2()

int mul(int x, int y) {

{ int count; // this is a local variable

return x * y; // return product of x and y for(count=0; count<3; count++)

} cout << '.';

Example 2: //demo 2 }

#include <iostream.h> Program 3:/*a program that Swaps args and


returns the minimum using pass-by-reference */
void func1();
#include <iostream.h>
void func2(); int & min_swap(int &x, int &y);
void main()
int count; // this is a global variable {
int i, j, min;
int main() i = 10;
j = 20;
{
cout << "Initial values of i and j: ";
int i; // this is a local variable cout << i << ' ' << j << '\n';
min = min_swap(j, i);
cout << "Swapped values of i and j: ";
cout << i << ' ' << j << '\n';
for(i=0; i<10; i++) cout << "Minimum value is " << min << "\n";
return ;
{ count = i * 2; }
// Swap function’s definition

Adama University Page 2


Department of computer science
C++ Programs’ collection

int & min_swap(int &x, int &y) Program 5: /* this program squares a number
{ and displays the result*/
int temp; // use references to exchange
//the values of the arguments void main(void)
temp = x;
x = y; {
y = temp;
// return reference to minimum arg int i;
if(x < y)
return x; for(prompt(); i=readnum(); prompt())
else
return y; sqrnum(i); //calling ‘sqrnum’ function
}
return;

Program 4: //odd or even using functions }

// declaring functions prototypes void prompt(void)


#include <iostream.h>
//function prototypes {
void odd (int a);
void even (int a); cout<<”Enter a number:\t”;

int main () return ;


{
}
int i;
do {
int readnum(void)
cout << "Type a number (0 to exit): ";
cin >> i; {
odd (i);
} while (i!=0); int n;
return 0;
} cin>>n;

void odd (int a) return n;


{
if ((a%2)!=0) }
cout << "Number is odd.\n";
else
even (a);
} int sqrnum(int num)

void even (int a) {


{
if ((a%2)==0) cout<<num*num;
cout << "Number is even.\n";
else return num*num;
odd (a);
} }

Program 6:

Adama University Page 3


Department of computer science
C++ Programs’ collection

//this program recursively multiplies natural N os Program 2: /*this prog finds max, min,sum, and
average of array elements*/
Int Mul( int a, int b) //function defintion
#include<iostream.h>
{
Int const size=21;
If(b==1)
void main()
return a;

else { float numbers[size], max_value, min_value,


sum, average;
return(Mul(a,b-1) +a);
int counter, max_index, min_index;
}

void main() for (counter = 1, sum = 0, max_value = -10000,


min_value = 10000; counter < 21; counter++)
{ {
int x, y, prod; //Add value to running total
sum += numbers[counter];
cout<<”Give me two Nos:\n”; /* Compare value to current minimum */
if (numbers[counter] < min_value)
cin>>x>>y;
{ min_value = numbers[counter];
prod=Mul(x,y); min_index = counter;
}
cout<<”The Product=\t”<<prod;
/* Compare value to current maximum */
return; if (numbers[counter] > max_value)
{ max_value = numbers[counter];
}
max_index = counter;
}
}
cout << "The total is " << sum << endl;
Arrays average = sum / size;
cout << "The average is " << average << endl;
Program 1: // Find duplicates cout << "The smallest element was element "
<< min_index << " which was " <<
#include <iostream.h>
Void main() min_value << endl;
{ cout << "The largest element was element "
int nums[] = {1, 1, 2, 3, 4, 2, 5, 4, 7, 7}; << max_index << " which was " << max_value
for(int i=0; i < 10; i++) << endl;
for(int j=i+1; j < 10; j++)
if(nums[i] == nums[j]) }
cout << "Duplicate: " << nums[i] << "\n";
return; Program 3:
} #include <iostream.h>

Adama University Page 4


Department of computer science
C++ Programs’ collection

#define MAX 5
void main () switch(ch)
{ int i; // the array loop variable {
int temp; case 'E':
int x[]={100,200,300,400,500}; enter_grades();
break;
cout << "The array firstly looks like this :\n"; case 'R':
for (i = 0; i < MAX; i++) disp_grades(grade);
cout << x[i] << " "; break;
cout << endl; case 'Q':

for (i = 0; i <=2; i++) //Why not exit(0);


i<MAX? }
{ temp = x[i]; }
x[i] = x[4 - i]; return;
x[4 - i] = temp; }
}
/* Enter the student's grades. */
cout << "The array now looks like this :\n"; void enter_grades(void)
for (i = 0; i < MAX; i++) {
cout << x[i] << " "; int t, i;
cout << endl;
return; for(t=0; t<CLASSES; t++) {
} cout<<"Class #\t"<<t+1;
for(i=0; i<GRADES; ++i)
Program 4: /* A simple students’ grade grade[t][i] = get_grade(i);
database. */ }
#include <iostream.h> }
#include <ctype.h> /* Read a grade. */
#include <stdlib.h> int get_grade(int num)
//assume 2 classes each with 5 students {
#define CLASSES 2 char s[80];
#define GRADES 5
int grade[CLASSES][GRADES]; cout<<”Enter grade for student # \t"<< num+1;
void enter_grades(void); cin.get(s,80);
int get_grade(int num); return(atoi(s)); // converts string to int
void disp_grades(int g[][GRADES]); }

void main(void) /* Display grades. */


{ void disp_grades(int g[][GRADES])
char ch, str[80]; {
int t, i;
for(;;)
{ for(t=0; t<CLASSES; ++t) {
do { cout<<"Class #:\t"<< t+1;
cout<<"Press (E) to Enter grades\n"; for(i=0; i<GRADES; ++i)
cout<<"Press (R) to Report grades\n"; cout<<"Student #: \t"<< i+1<< g[t][i]);
cout<<"Press (Q) to Quit\n"; }
cin>>ch; }
ch = toupper(ch); //change to capital letter
} while(ch!='E' && ch!='R' && ch!='Q'); Program 5:

Adama University Page 5


Department of computer science
C++ Programs’ collection

s[i] = s[string_length - i];


// a program that counts uppercase //letters. s[string_length - i] = temp;
#include <iostream.h> }
#include <string.h> cout << "After the swap : " << s << endl;
#include <ctype.h> }
int main()
Program 7:
{
// A simple employee database program.
char str[80];
int i; #include <iostream.h>
int count;
strcpy(str, "This Is A Test"); char name[10][80]; // this array holds
count = 0; //employee names
for(i=0; str[i]; i++) char phone[10][20]; // their phone numbers
if(isupper(str[i])) count++; float hours[10]; // hours worked per week
cout << str<< " contains " << count << float wage[10]; // wage
" uppercase letters.";
return 0; int menu();
void enter(), report();
}

void main()
{
int choice;
Program 6:
do {
// a program that reverses a string choice = menu(); // get selection
switch(choice) {
#include <iostream.h> case 0: break;
void main () case 1: enter();
{ int i; // loop variable break;
char temp; case 2: report();
char s[14] = "saipuakaupias"; break;
int string_length, half_way; default: cout << "Try again.\n\n";
}
// determine the length of the //string } while(choice != 0);
for (i = 0; i <= 14; i++)
if (s[i] == '\0') return ;
string_length = i - 1; }
/* Note that string_length is the position of the
character before the \0 */ // Return a user's selection.
int menu()
half_way = string_length / 2; {
int choice;
cout << "Before the swap : " << s;
cout<< endl; cout << "0. Quit\n";
cout << "1. Enter information\n";
// now swap cout << "2. Report information\n";
for (i = 0; i < half_way; i++) cout << "\nChoose one: ";
{ cin >> choice;
temp = s[i];

Adama University Page 6


Department of computer science
C++ Programs’ collection

return choice; f(p);


}
cout << i; // i is now 100
// Enter information.
void enter() return 0;
{
int i; }
char temp[80];
void f(int* j)
for(i=0; i<10; i++) {
cout << "Enter last name: ";
{ *j = 100; }
cin >> name[i];
cout << "Enter phone number: ";
cin >> phone[i]; // here var pointed to by j is assigned 100
cout << "Enter number of hours worked: ";
Program 2:
cin >> hours[i];
cout << "Enter wage: ";
// swaps two floating points numbers
cin >> wage[i];
}
} #include <iostream.h>

// Display report. float * my_ptr; /* global so that function


void report() display_values can access them.*/
{ float x = 736.733, y = 55.55;
int i;
for(i=0; i<10; i++) { void get_value () //function defintion1
cout << name[i] << ' ' << phone[i] << '\n'; { float decimal_number;
cout << "Pay for the week: " ; cout << "Please enter a number : ";
cout<<wage[i]*hours[i]; cin >> decimal_number;
cout << '\n'; *my_ptr = decimal_number;
} }
} void display_values () //function definition 2
{ cout << "The value of x is " << x << endl;
Pointers cout << "The value of y is " << y << endl;
cout << endl;
}
Program 1: // Pass a pointer to a function.
void main ()
{
#include <iostream> display_values();
my_ptr = &x; // Points to x
void f(int *j); //function prototype get_value();
my_ptr = &y; // Points to y
int main() get_value();
display_values();
{ }

int i;
Structures
int *p;
Program 1: // Demonstrate structure assignments.
p = &i; // p now points to i

Adama University Page 7


Department of computer science
C++ Programs’ collection

#include <iostream.h> #include <iostream.h>

struct stype #include <ctype.h>

{ #include <string.h>

int a, b; #include <stdlib.h>

};

const int SIZE = 100;

int main() struct inv_type {

{ char item[40]; // name of item

stype svar1, svar2; double cost; // cost

svar1.a = svar1.b = 10; double retail; // retail price

svar2.a = svar2.b = 20; int on_hand; // amount on hand

cout << "Structures before assignment.\n"; int lead_time; // number of days before
//resupply
cout << "svar1: " << svar1.a << ' ' << svar1.b;
} invtry[SIZE];
cout << '\n';
//prototypes
cout << "svar2: " << svar2.a << ' ' << svar2.b;
void enter(), init_list(), display();
cout << "\n\n";
void update(), input(int i);
svar2 = svar1; // assign structures
int menu();
cout << "Structures after assignment.\n";
int main()
cout << "svar1: " << svar1.a << ' ' << svar1.b;
{ char choice;
cout << '\n';
init_list();
cout << "svar2: " << svar2.a << ' ' << svar2.b;
for(;;) {
return 0;
choice = menu();
}
switch(choice) {
Program 2: /* A simple inventory program that
uses an array of structures. */ case 'e': enter();

Adama University Page 8


Department of computer science
C++ Programs’ collection

break; cout << "(Q)uit\n\n";

case 'd': display(); cout << "choose one: ";

break; cin >> ch;

case 'u': update(); } while(!strchr("eduq", tolower(ch)));

break; return tolower(ch);

case 'q': return 0; }

} // Enter items into the list.

} void enter()

} { int i;

// Initialize the inv_type_info array. // find the first free structure

void init_list() for(i=0; i<SIZE; i++)

{ if(!*invtry[i].item) break;

int t; // i will equal SIZE if the list is full

// a zero length name signifies empty if(i==SIZE) {

for(t=0; t<SIZE; t++) *invtry[t].item = '\0'; cout << "List full.\n";

} return;

// Get a menu selection. }

int menu() input(i);

{ char ch; }

cout << '\n'; // Input the information.

do { void input(int i)

cout << "(E)nter\n"; {

cout << "(D)isplay\n"; char str[80];

cout << "(U)pdate\n"; // enter the information

Adama University Page 9


Department of computer science
C++ Programs’ collection

cout << "Item: "; return;

cin >> invtry[i].item; }

cout << "Enter new information.\n";

cout << "Cost: "; input(i);

cin >> invtry[i].cost; }

cout << "Retail price: "; // Display the list.

cin >> invtry[i].retail; void display()

cout << "On hand: "; {

cin >> invtry[i].on_hand; int t;

cout << "Lead time to resupply (in days): "; for(t=0; t<SIZE; t++) {

cin >> invtry[i].lead_time; if(*invtry[t].item) {

} cout << invtry[t].item << '\n';

// Modify an existing item. cout << "Cost: $" << invtry[t].cost;

void update() cout << "\nRetail: $";

{ cout << invtry[t].retail << '\n';

int i; cout << "On hand: " << invtry[t].on_hand;

char name[80]; cout << "\nResupply time: ";

cout << "Enter item: "; cout << invtry[t].lead_time << " days\n\n";

cin >> name; }

for(i=0; i<SIZE; i++) }

if(!strcmp(name, invtry[i].item)) }

break;

if(i==SIZE) { File System

cout << "Item not found.\n"; Prog 1:/* this prog writes the numbers 1 to 10 to
a file called TEST */

Adama University Page 10


Department of computer science
C++ Programs’ collection

#include<iostream.h>
#include<fstream.h>
const char* filename = "TEST";

void main()
{
int i = 0; // count from 1 to 10
ofstream numbers (filename);
// Creates a file variable called 'numbers'
//and ties it to the name TEST on the disc

for (i = 1; i <= 10; i++)


numbers << i << endl;
// Write the numbers to the file

numbers.close() // Close the file at the end

Making Games in C++

In making games just remember the following things:


 simplicity is the key. Of course, if you are comfortable with the more advanced graphics
capabilities of C++, you can go on to make a complex game, the simpler the better.
 Optimal difficulty- not too easy, not too hard. It needs also to have some sort of reward
(e.g a colorful message) when you win, so the user is playing for some reason.
 A game also needs to have a little more than plain text. For example, you could use a
noughts and crosses board, or simply colorful text.

Now, to make a game, first of all, you need to have an idea of what kind of game you
want to make.

Below are simple programs which you can enrich them further by adding whatever you
think should be integrated. Have Fun!

This prog makes use of:

do-while , if-else statments

Game1: //Number guessing game Brief Description:

/* ****************************

Adama University Page 11


Department of computer science
C++ Programs’ collection

//The computer generates a random number #define MAX_RANGE 100


between 1 and MAX_RANGE. The user
must guess the number. Each time the user void main ()
makes an attempt the computer, tells if the
number is greater or less than the hidden {
number.
int counter=0;
*******************************
*/ long value, input;

#include <iostream.h> srand ( time (NULL) ); // Initialize


random //generator.
#include <stdlib.h>
value = rand()%MAX_RANGE+1;
#include <time.h>
// rand() function generates random numbers
b/n 1 and MAX_RANGE

// Define the greatest possible value: cout << "\nInsert a value between 1 and "
<< MAX_RANGE << " : ";

do { else

cin >> input; // Get user input { // else it is the correct number!

counter++; //count user attempts cout << "That's right! Value was " << input;
cout << "\nYou have needed " << counter
if (value>input <<" attempts.";

cout << "Value is greater than " << input }


<< ". Try again : ";
} while (value!=input);
else if (value<input) // if not, is it less?
return 0;
cout << "Value is less than " << input << ".
Try again : "; }

******************************************************************************
Game2: "Higher or Lower?" Brief Description:

/* This game uses selection and jump


statements.

Adama University Page 12


Department of computer science
C++ Programs’ collection

The user will be shown a number and asked if (num2<num)


if the next randomly generated number is goto win;
higher or lower. else if (num2>num)
****************************** */ goto lose;
#include <iostream.h> else if (num2==num)
#include <time.h> goto same;
#include <stdlib.h> win:
#include <windows.h> {
if (score==4)
int main() {
{ cout <<" Well Done! U completed the
short unsigned int score = 0; game!!!!\n";
short unsigned int num = 0; system ("pause");
short unsigned int num2 = 0; return 0;
char letter; }
loop: else
srand(time(NULL)); //Initialize random number {
generator cout <<"You win! Well done!\n";
num = 1 + rand() % (6 - 1 + 1); // random system ("pause");
integer between 1 and 6 score++;
num2 = 1 + rand() % (6 - 1 + 1);// random goto loop;
integer between 1 and 6 }
cout <<"\nPoints: "; }
same:
{
cout << score << endl; if (score==4)
cout <<"Get to 5 points to win. The numbers {
range between 1 and 6.\n"; cout <<" You
cout << num; completed the game! Well done!!!\n";
cout <<" is the first number. \nIs the next system ("pause");
number going to be higher or lower? H or L?" return 0;
<< endl; }
cin >> letter; else
{
cout <<"Wow!The numbers were the same! You
if (letter == 'h'||letter == 'H') get a point for that...";
{ system ("pause");
cout << num2; score++;
cout <<" is the second number."; goto loop;
}
if (num2>num) }
goto win;
else if (num2<num) lose:
goto lose; {
else if (num2==num) cout <<"You lose...\n";
goto same; system ("pause");
}
else
{ }
cout << num2; }
cout <<" is the second number."; return 0;

Adama University Page 13


Department of computer science
C++ Programs’ collection

*********************************************************************************

Game3: /* "Stone, Scissors or Paper" // * Returns a random character between 's',


'x', //and 'p'
*****************************************
char PickRandomOption (void)
This game makes use of:
{
Functions, switch-case and if-else statements
char option;
Brief Description:
srand ( time (NULL) ); //initialize
In this game, the user and the computer choose random //number generator
each one an option between stone, scissors and
paper. int value = rand()%3; // Generate
random //number between 0 and 2
Scoring:

Stone wins over scissors, scissors over paper


and paper over stone: switch (value) {

stone -> scissors -> paper -> stone... case 0: option='s'; break;

The first who wins WINSCORE times is the case 1: option='x'; break;
competition winner.
case 2: option='p'; break;
****************************** */
}

return option;
#include <iostream.h>
}
#include <stdlib.h>
// Function WhoWins
#include <time.h>
// * check which of the characters passed wins.
#define WINSCORE 3
// return values:
// Function PickRandomOption
// 0= tie, 1=the first, 2=the second, -1=error

Adama University Page 14


Department of computer science
C++ Programs’ collection

int WhoWins (char a, char b) {

{ char you, me;

switch (a) int mypoints=0;

{ int yourpoints=0;

case 's': int winner;

if (b=='x') return 1;

else if (b=='p') return 2;

else return 0; do {

case 'x': //prompt user.

if (b=='p') return 1; cout << "\nEnter [s],[ x] or[ p] ";

else if (b=='s') return 2; cout << "(s=stone, x=scissors, p=paper): ";

else return 0; cin >> you;

//decide computer's option and say it

case 'p': me = PickRandomOption();

if (b=='s') return 1; cout << "I say: " << me << "\n";

else if (b=='x') return 2; // check who is the winner

else return 0; winner = WhoWins (you,me);

default: // show appropriate message:

return -1; if (winner==0) cout << "Tied\n";

} else if (winner==1)

} { cout << "You win\n"; yourpoints++; }

else if (winner==2)

{ cout << "I win\n"; mypoints++; }

void main () else

Adama University Page 15


Department of computer science
C++ Programs’ collection

cout << "Sorry. You entered an Invalid The user has to discover all the letters in a
option\n"; secret keyword one by one. Each letter said that
is in the keyword is shown in its rightful
// show current scoreboard. location. If you know the hangman game,

cout << "POINTS: You:" << yourpoints; You have the opportunity to fail up to
FAILS_ALLOWED times.
cout << " Me:" << mypoints << "\n";
Enjoy the Game!
} while (yourpoints<WINSCORE &&
mypoints<WINSCORE); ******************************** */

#include <iostream.h>

if (yourpoints>mypoints) #include <stdlib.h>

cout << "You win the competition!\n"; #include <time.h>

else #include <string.h>

cout << "I win the competition!\n";

return; #define N_KEYS 12

} #define KEY_MAX_WIDTH 20

#define FAILS_ALLOWED 7

// Possible keywords. You may insert new ones


if you increase N_KEYS.

char possiblekeys [N_KEYS]


[KEY_MAX_WIDTH] = { "Adama", "csit",
"Ethiopia", ”Awassa”, “Mississippi",
*************************************** "programming", "java", "fundamental", "Bible",
"computer", "Quran", "restaurant", "civilization"
};
Game 4: “The Secret Word”

***************************************
// This will store the key
This game makes use of Shows:
char key [KEY_MAX_WIDTH];
Strings, arrays of strings, string functions:
strcpy and strlen
// This will store the string shown on screen
//with letters already discovered.

char outstring [KEY_MAX_WIDTH];


Brief Description:

Adama University Page 16


Department of computer science
C++ Programs’ collection

int CheckLetter (char letter); cout << "Enter a letter (You may fail " <<
fails << " times): ";
main ()
cin >> input;
{
cin.ignore (100,'\n');
char input;
// check if letter is valid
int valid;
valid = CheckLetter (input);
int fails = FAILS_ALLOWED;
// if it is valid, increase discovered letters
unsigned int discovered = 0; //counter; if not, decrease allowed fails

unsigned int n; if (valid!=0)

discovered+=valid;

// Select a key. else fails--;

srand ( time (NULL) ); // Initialize } while (discovered < strlen(key) && fails>0);
random //number generator
// The loop ends if key is discovered or fails are
int value = rand()%N_KEYS; // Get random exhausted.
//between 0 and NKEYS-1
// Display CORRECT! only if key was
strcpy (key,possiblekeys[value]); // Copy key discovered.

// Set outstring to '-' characters plus if (discovered == strlen(key))


//terminating null-character
cout << "CORRECT! ";
for (n=0; n<strlen(key); n++)
cout "Key was '" << key <<"'.\n";
outstring[n]='-';
return 0;
outstring[n]='\0';
}

// Function that checks if letter is in key.


do {
// returns the number of times the letter was
// Prompt user //found in key

cout << "\nDiscover the secret key: " << int CheckLetter (char letter)
outstring << "\n";
{

Adama University Page 17


Department of computer science
C++ Programs’ collection

unsigned int n; char check(void);

int found=0; void init_matrix(void);

for (n=0; n<strlen(key); n++) void get_player_move(void);

if (key[n]==letter && outstring[n]=='-') void get_computer_move(void);

{ found++; void disp_matrix(void);

outstring[n]=key[n];

} int main(void)

return found; {

} char done;

******************************** cout<<"This is the game of Tic Tac Toe.\n";

Game 5: Tic-tac-toe cout<<"You will be playing against the


computer.\n";
Tic-tac-toe is a classic paper-and-pencil game in
which each of two opponents tries to get 3
marks, usually represented by ‘O’ and ‘X’ in a
row. done = ' ';

Below are some of the possible moves: init_matrix(); //function to initialize array

do{
O O
disp_matrix();
X X X X X wins!
O O O O X O
get_player_move();
X X O X X O X X O
X X X
done = check(); /* see if winner */
O
if(done!= ' ') break; /* winner!*/
X X O
get_computer_move();

#include <iostream.h> done = check(); /* see if winner */

#include <stdlib.h> } while(done== ' ');

char matrix[3][3]; /* the tic tac toe matrix */ if(done=='X')

cout<<"You won!\n";

Adama University Page 18


Department of computer science
C++ Programs’ collection

else cout<<"I won!!!!\n"; else

disp_matrix(); /* show final positions */ matrix[x][y] = 'X'; //put the ‘X’ mark

return 0; }

} /* Get a move from the computer. */

void get_computer_move(void)

/* Initialize the matrix. */ {

void init_matrix(void) int i, j;

{ for(i=0; i<3; i++){

int i, j; for(j=0; j<3; j++)

for(i=0; i<3; i++) if(matrix[i][j]==' ')

for(j=0; j<3; j++) matrix[i][j] = ' '; break;

} if(matrix[i][j]==' ')

/* Get a player's move. */ break;

void get_player_move(void) }

int x, y; if(i*j==9) {

cout<<"Enter X,Y coordinates for your move: "; cout<<"draw\n";

cin>>x>>y; exit(0);

x--; y--; }

if(matrix[x][y]!= ' ') else

{ matrix[i][j] = 'O'; //put ‘O’ mark

cout<<"Invalid move, try again.\n"); }

get_player_move(); /* Display the matrix on the screen. */

} void disp_matrix(void)

Adama University Page 19


Department of computer science
C++ Programs’ collection

{ return matrix[0][0];

int t; if(matrix[0][2]==matrix[1][1] &&

for(t=0; t<3; t++) { matrix[1][1]==matrix[2][0])

cout<<matrix[t][0] <<”|”<< matrix[t][1]<< return matrix[0][2];


“|”<< matrix[t][2] ";
return ' ';
if(t!=2)
}
cout<<"\n---|---|---\n");

cout<<"\n";

/* See if there is a winner. */

char check(void)

int i;

for(i=0; i<3; i++) /* check rows */

if(matrix[i][0]==matrix[i][1] && matrix[i]


[0]==matrix[i][2])

return matrix[i][0];

for(i=0; i<3; i++) /* check columns */

if(matrix[0][i]==matrix[1][i] &&

matrix[0][i]==matrix[2][i])

return matrix[0][i];

/* test diagonals */

if(matrix[0][0]==matrix[1][1] &&

matrix[1][1]==matrix[2][2])

Adama University Page 20


Department of computer science

You might also like