Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C++ Programming Code Examples

C++ > Games Code Examples

This is a tictactoe game in C++.

/* This is a tictactoe game in C++. Although it is not too smart to prevent you from winning but it is worth playing it. I hope u enjoy it. Happy gaming! */ #include<iostream.h> //opening headerfile iostream for in-out #include<conio.h> //opening headerfile conio for clrscr(); #include<stdlib.h> //opening headerfile stdlib for random(int); char tic[3][3]; //global matrix declerations int d,e,f,a,t,i,j,x,y; //global variables declerations void display(); //displays the matrix void user(); //function for user's move void newdisp(); //function for display of matrix after every move void pc(); //function for pc's move int check(); //function for finding out the winner int horcheck(); //function for horizontal line check int vercheck(); //function for vertical line check int diagcheck(); //function for diagonal line check main() //main function { clrscr(); //clears the previous output screen randomize(); //initialize random function calling int d=random(2); //random function call for(i=0;i<3;i++) for(j=0;j<3;j++) tic[i][j]=' '; //assigning space ' ' to all elements of matrix display(); //display function call d==0?user():pc(); //random starting of the game depending on d getch(); //provides output by getting input without returning to program return 0; //return int to main function } void display() //display function definition { for(t=0;t<3;t++) { cout<<" "<<tic[t][0]<<" | "<<tic[t][1]<<" | "<<tic[t][2]<<endl; //figure formation if(t!=2) cout<<" --|---|--"<<endl; } } void user() //user function definition { cout<<" ENTER THE CO-ORDINATES WHERE YOU WANT TO PUT UR 'X' i.e 0,1,2 "; cin>>x>>y; if((x<0)||(x>2)&&(y<0)||(y>2)) //check for valid co-ordinates { cout<<" ENTER THE CORRECT CO-ORDINATES"; user(); //user function call } else { if(tic[x][y]==' ') //check for vacant space at entered co-ordinates { tic[x][y]='X'; //assigning user 'X' to the co-ordinates newdisp(); //newdisp function call } else { cout<<" THIS POSITION IS ALREADY FILLED. CHOOSE SOME OTHER CO-ORDINATES"; user(); //user function call } } d=check(); //check function call if(d==0) pc(); //pc function call else { cout<<" YOU ARE THE WINNER"; getche(); //requires enter to return to program. prevents return without display exit(1); //program termination } } void newdisp() //newdisp function definition { for(t=0;t<3;t++) { cout<<" "<<tic[t][0]<<" | "<<tic[t][1]<<" | "<<tic[t][2]<<endl; //displays new tictactoe after user or pc turn if(t!=2) cout<<" --|---|--"<<endl; } } void pc() //pc function call { int f,z; randomize(); //initialize random function calling cout<<" THIS IS THE COMPUTER'S MOVE "; for(i=0;i<=20;i++) { f=random(3); z=random(3); if(tic[f][z]==' ') //check for vacant space at entered co-ordinates { tic[f][z]='O'; //assigning pc 'O' to the co-ordinates goto x; //exiting for loop to display new tictactoe } else continue; // } x:newdisp(); //newdisp function call d=check(); //check function call if(d==0) user(); //user function call else { cout<<" I'M THE WINNER"; getche(); //requires enter to return to program. prevents return without display exit(1); //program termination } } check() //check function definition { horcheck(); //horcheck function call vercheck(); //vercheck function call diagcheck(); //diagcheck function call return (d||e||f); } horcheck() //horcheck function definition { if(((tic[0][0]==tic[0][1])&&(tic[0][1]==tic[0][2])&&(tic[0][1]!=' '))||((tic[1][0]==tic[1][1])&&(tic[1][1]==tic[1][2])&&(tic[1][1]!=' '))||((tic[2][0]==tic[2][1])&&(tic[2][1]==tic[2][2])&&(tic[2][2]!=' '))) d=1; //checks each element of a horizontal line to be same else //returns 1 if all 3 elements of any horizontal line are same d=0; //else returns 0 return d; } vercheck() //vercheck function definition { if(((tic[0][0]==tic[1][0])&&(tic[1][0]==tic[2][0])&&(tic[0][0]!=' '))||((tic[0][1]==tic[1][1])&&(tic[1][1]==tic[2][1])&&(tic[0][1]!=' '))||((tic[0][2]==tic[1][2])&&(tic[1][2]==tic[2][2])&&(tic[0][2]!=' '))) e=1; //checks each element of a vertical line to be same else //returns 1 if all 3 elements of any vertical line are same e=0; //else returns 0 return e; } diagcheck() //diagcheck function definition { if(((tic[0][0]==tic[1][1])&&(tic[1][1]==tic[2][2])&&(tic[0][0]!=' '))||((tic[0][2]==tic[1][1])&&(tic[1][1]==tic[2][0])&&(tic[1][1]!=' '))) f=1; //checks each element of a diagonal line to be same else //returns 1 if all 3 elements of any diagonal line are same f=0; //else returns 0 return f; }

The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.

In C++, goto is a jump statement and sometimes also referred as unconditional jump statement. It can be used to jump from goto to a labeled statement within the same function. The target label must be within the same file and context. Please note that the use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making hard to understand and modify the program.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

This function waits for any character input from keyboard. And, it will also echo the input character on to the output screen. The getch() function is very useful if you want to read a character input from the keyboard. Like getch(), getche() is also character input functions. It is unformatted input function meaning it does not allow user to read input in their format. Difference between getch() and getche() is that getche() echoes pressed character. getche() also returns character pressed like getch(). It is also defined in header file conio.h.

A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

Continue statement is used inside loops. Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop's body for the current iteration. The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.

The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order).

Randomly select pivot value from the subpart of the array. Partition that subpart so that the values left of the 'pivot' are smaller and to the right are greater from the pivot. And consider

You enter number size then ask to enter the numbers of that size. To calculate arithmetic 'mean of all numbers', first perform addition of all the numbers, and then make a variable

Number of bits in the Bloom filter. Number of bits set per Mapping in Filter. Table of "8-bit" CRC32 remainders. Bloom filter array of M/8 bytes. Number of bytes in Bloom filter. Main