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

Brick Game - Arcanoid with mouse - a small game with a efficient

/* Brick Game - Arcanoid with mouse - a small game with a efficient error handling */ #include <iostream.h> #include <conio.h> #include <ctype.h> //defining toupper # include <process.h> //exit(0) # include <dos.h> # include <stdlib.h> # include <graphics.h> # include <stdio.h> # define NULL 0 # define YES 1 # define NO 0 #define ESC 0x1b /* Define the escape key */ int MaxX, MaxY, MidX, MidY ; int bri[5][20] ; int GraphDriver; /* The Graphics device driver */ int GraphMode; /* The Graphics mode value */ int MaxXX, MaxYY; /* The maximum resolution of the screen */ int MaxColors; /* The maximum # of colors available */ int ErrorCode; /* Reports any graphics errors */ struct palettetype palette; /* Used to read palette info*/ // Initialize the graphics mode void Initialize(void); // Display the last screen of bricks void SayGoodbye(void); // Changes the text style and report any error if encounter void changetextstyle(int font, int direction, int charsize); // Welcome screen of bricks game mainscreen(); // Instruction messages of bricks game screen(); // To display the bricks (in square box) and paddles in rectangle form and bulbs rounded form bricks(); // Delete a bricks when bulb hit it delbrick(int,int); // Echoes different musics bell(int); int graphmode = CGAHI, graphdriver = CGA, level; // resolution of CGAHI = 640 x 200 (col x row) /*-------------------Mouse Library--------------*/ void InitMouse()//initializes the mouse { union REGS in,out; in.x.ax=33; int86(0x33,&in,&out); } void MousePos(int* x,int* y,int* click) { //stores back (x,y) values and click type //click=1: left click //2: right click //3: middle click union REGS in,out; in.x.ax=3; int86(0x33,&in,&out); *click=(int)out.x.bx; *x=(int)out.x.cx; *y=(int)out.x.dx; } /*-----------------------End Of Mouse Methods----------*/ main () { union REGS ii, oo ; int BallX, BallY, Base1, Base2, dx = 1, dy = -1, OldX, OldY ; int totallayer[5] = { 10, 20, 30, 40, 50 }, max = 50, layer = 4 ; int i, flag = 0, speed = 15, score = 0, chance = 4, areareq ; char *m1, *m2 ; //pointers to memory /* Function to initialise the graphics mode */ initgraph ( &graphdriver, &graphmode, "c:\tc\bgi" ) ; mainscreen(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi" ) ; /**************************************************/ /* Function to initialise the mouse */ InitMouse(); /* get the maximum value of x and y coordinates of the screen */ MaxX = getmaxx() ; MaxY = getmaxy() ; /* finding the center of the screen */ MidX = MaxX / 2 ; MidY = MaxY / 2 ; /* create opening screen and accept the level of the player's */ level = screen() ; /* assign the speed to ball as per the level chosen */ switch ( level ) { case 'M' : case 'm' : speed = 10 ; break ; case 'F' : case 'f' : speed = 3 ; } /* draw the four layer of bricks, the paddle and the ball */ rectangle ( 0, 0, MaxX, MaxY - 12 ) ; bricks() ; rectangle ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 12 ) ; floodfill ( MidX, MaxY - 1 - 12, 12 ) ; circle ( MidX, MaxY - 13 - 12, 12 ) ; // fillellipse ( MidX, MaxY - 13 - 12,12,12 ) ; floodfill ( MidX, MaxY - 10 - 12, 12 ) ; /* memory allocation for storing the image of the paddle */ areareq = imagesize ( MidX - 12, MaxY - 18, MidX + 12, MaxY - 8 ) ; m1 =((char*) malloc ( areareq )) ; /* memory allocation for storing the image of the ball */ areareq = imagesize ( MidX - 25, MaxY - 7, MidX + 25, MaxY - 1 ) ; m2 =((char *) malloc ( areareq ) ); /* if unable to alloacte the memory */ if ( m1 == NULL || m2 == NULL ) { puts ( "Not Enough memory!!" ) ; exit ( 1 ) ; } /* image of the paddle and the ball is stored into allocated memory */ getimage ( MidX - 12, MaxY - 7 - 12 - 12 + 1, MidX + 12, MaxY - 8 - 12, m1 ) ; getimage ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 1 - 12, m2 ) ; /* store current position of the paddle and ball */ Base1 = MidX - 25 ; Base2 = MaxY - 7 - 12 ; BallX = MidX - 12 ; BallY = MaxY - 7 - 12 + 1 - 12 ; /* display balls remaining ( initially 3 ) */ gotoxy ( 45, 25 ) ; cout<< "Balls :" ; for ( i = 0 ; i < 3 ; i++ ) { circle ( 515 + i * 35, MaxY - 5, 12 ) ; floodfill ( 515 + i * 35, MaxY - 5, 12 ) ; } /* display starting score */ gotoxy ( 1, 25 ) ; cout<< "Score: "; gotoxy(16,25); cout<<score; /* select font and alignment for displaying text */ settextjustify ( CENTER_TEXT, CENTER_TEXT ) ; changetextstyle ( GOTHIC_FONT, HORIZ_DIR, 4 ) ; while ( 1 ) { flag = 0 ; /* saving current x and y coordinates of the ball */ OldX = BallX ; OldY = BallY ; /* update ballx and bally to move the ball in correct direction */ BallX = BallX + dx ; BallY = BallY + dy ; /* according to the position of ball the layer of bricks is determined */ if ( BallY > 40 ) { max = 50 ; layer = 4 ; } else { if ( BallY > 30 ) { max = 40 ; layer = 3 ; } else { if ( BallY > 20 ) { max = 30 ; layer = 2 ; } else { if ( BallY > 10 ) { max = 20 ; layer = 1 ; } else { max = 10 ; layer = 0 ; } } } } /* if the ball hits the right boundary, move it to the left */ if ( BallX > ( MaxX - 24 - 1 ) ) { bell ( 5 ) ; BallX = MaxX - 24 - 1 ; dx = -dx ; } /* if the ball hits the left boundary, move it to the right */ if ( BallX < 1 ) { bell ( 5 ) ; BallX = 1 ; dx = -dx ; } /* if the ball hits the top boundary, move it down */ if ( BallY < 1 ) { bell ( 5 ) ; BallY = 1 ; dy = -dy ; } /* if the ball is in the area of the bricks */ if ( BallY < max ) { /* if there is no brick at the top of the ball */ if ( bri[layer][ ( BallX + 10 ) / 32 ] == 1 ) { /* if the ball touches a brick */ for ( i = 1 ; i <= 6 ; i++ ) { /* check whether there is a brick to the right of the ball */ if ( bri[layer][ ( BallX + i + 10 ) / 32 ] == 0 ) { /* if there is a brick */ BallX = BallX + i ; flag = 1 ; break ; } /* check whether there is a brick to the left of the ball */ if ( bri[layer][ ( BallX - i + 10 ) / 32 ] == 0 ) { BallX = BallX - i ; flag = 1 ; break ; } } /* if the ball does not touch a brick at the top, left or right */ if ( !flag ) { /* check if the ball has moved above the current layer */ if ( BallY < totallayer[layer - 1] ) { /* if so, change current layer appropriately */ layer-- ; max = totallayer[layer] ; } /* restore the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, OR_PUT ) ; /* erase the image at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* place the image of the ball at the new coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* delay for fewseconds*/ delay ( speed ) ; /* carry on moving the ball */ continue ; } } /* when ball touch the brick control comes to this point */ bell ( 5 ) ; /* play music */ /* erase the touched brick */ delbrick ( ( BallX + 10 ) / 32, layer ) ; /* if the brick hit is on the extreme right */ if ( ( BallX + 10 ) / 32 == 19 ) line ( MaxX, 0, MaxX, 50 ) ; /* redraw right boundary */ /* if the brick hit is on the extreme left */ if ( ( BallX + 10 ) / 32 == 0 ) line ( 0, 0, 0, 50 ) ; /* redraw left boundary */ /* if the brick hit is in the topmost layer */ if ( layer == 0 ) line ( 0, 0, MaxX, 0 ) ; /* redraw top boundary */ /* set appropriate array element to 1 to indicate absence of brick */ bri[layer][ ( BallX + 10 ) / 32 ] = 1 ; BallY = BallY + 1 ; /* update the y coordinate */ dy = -dy ; /* change the current direction of the ball */ score += 10 ; /* increment the score by 10 */ gotoxy ( 16, 25 ) ; cout<< score; /* display latest score */ /* if the first brick is hit during a throw*/ } /* if ball reached the bottom */ if ( BallY > 180 - 12 ) { /* if paddle missed the ball */ if ( BallX < Base1 - 20 || BallX > Base1 + 50 ) { /* continue the decrement of the ball */ while ( BallY < 177 ) { /* erase the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* put the image of the ball at the new coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* introduce delay for fewseconds */ delay ( speed ) ; /* saveing current x and y coordinates of the ball */ OldX = BallX ; OldY = BallY ; /* update ballx and bally to move the ball in correct direction */ BallX = BallX + dx ; BallY = BallY + dy ; } chance-- ; /* decrement the total number of chances */ score -= 10 ; /* decrement 10 points for each ball lost */ gotoxy ( 16, 25 ) ; cout<< score; /* display latest score */ bell ( 1 ) ; /* erase one of the available balls */ if ( chance ) putimage ( 515 + ( chance - 1 ) * 35 - 12 , MaxY - 10, m1, XOR_PUT ) ; /* if the last ball is being played */ if ( chance == 1 ) { gotoxy ( 45, 25 ) ; cout<< "Last ball... careful!"; } /* if all the balls are lost */ if ( !chance ) { gotoxy ( 45, 25 ) ; cout<<"Press any key to continue ... " ; outtextxy ( MidX, MidY, "Better luck next time" ) ; bell ( 2 ) ; closegraph() ; restorecrtmode() ; closegraph(); /* Close the graphics mode */ Initialize(); /* Intialize the graphics mode */ setbkcolor(4); SayGoodbye(); /* Display the That's all Folks message */ closegraph(); /* Return the system to text mode */ exit ( 0 ) ; } } /* if ball is collected on paddle */ bell ( 4 ) ; BallY = 180 - 12 ; /* restore the y coordinate of ball */ dy = -dy ; /* move the ball upwards */ } /* put the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, OR_PUT ) ; /* erase the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* put the image of the ball at the upadted coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* If score becomes 500 for every level player the speed of the ball will be standard PLAYER playing Fast level feel reduction of speed n PLAYER playing slow or medium level feel increment in speed... */ if(score==600) speed=6 ; /* if all the bricks have been knockout */ if ( score == 800 - ( ( 4 - chance ) * 10 ) ) { outtextxy ( MidX, MidY, "Winner !!" ) ; if ( score < 800 ) outtextxy ( MidX, MidY + 30, "Try to score 800" ) ; else outtextxy ( MidX, MidY + 30, " GREAT!" ) ; bell ( 2 ) ; SayGoodbye(); /* Display the That's all Folks message */ closegraph() ; restorecrtmode() ; exit ( 0 ) ; } /* introduce delay for few seconds */ delay ( speed ) ; /* if the key is pressed to exit the game */ if ( kbhit() ) { /* interrupt issue to obtain the ascii and scan codes of key hit */ ii.h.ah = 0 ; int86 ( 22, &ii, &oo ) ; /* if Esc key has been pressed */ if ( oo.h.ah == 1 ) exit ( 0 ) ; } /* put the image of the paddle at the old coordinates */ putimage ( Base1, Base2, m2, OR_PUT ) ; /* erase the image of the paddle at the old coordinates */ putimage ( Base1, Base2, m2, XOR_PUT ) ; // /* if Esc key has been pressed */ // if ( oo.h.ah == 1 ) // exit ( 0 ) ; /* right arrow key */ // if ( oo.h.ah == 75 ) // Base1 = //Base1 - 25 ; /* left arrow key */ // if ( oo.h.ah == 77 ) // Base1= Base1 + 25 ; /**********************************************************/ //dummy variables are useless //to get current x co-ordinate of the //mouse pointer pointer of Base1 is passed //the result is copied in the variable int ydummy,clickdummy; MousePos(&Base1,&ydummy,&clickdummy); /* if paddle goes beyond left boundary */ if ( Base1 < 0 ) Base1 = 0 ; /* if paddle goes beyond right boundary */ if ( Base1 > 589 ) Base1 = 589 ; /* put the image of the paddle at the proper position */ putimage ( Base1, Base2, m2, XOR_PUT ) ; // } } closegraph(); Initialize(); SayGoodbye(); /* Give user the closing screen */ closegraph(); /* Return the system to text mode */ return(0); } /* This function creates the opening screen and displyed instruction related to the game along with two option play or exit.After selecting the paly option it display three levels of the game and according to your choice you can select any level. This selected level is returned by this function to the mainprogram according to which the speed is assigned to the ball*/ screen() { int i, j, lx = 0, ly = 0, ch ; rectangle(1,1,600,195); setbkcolor(4); /* set the textstyle for displaying instruction */ changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ; outtextxy ( 150, 55, " Instructions " ) ; changetextstyle (4, HORIZ_DIR, 5 ); outtextxy ( 130, 0, " B R I C K S" ) ; changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ; outtextxy ( 30, 68, "Use mouse to move the paddle" ) ; // can also use KEYBOARD after activating keyboard event (use LEFT and RIGHT keys to move the PADDLE outtextxy ( 30, 88, "If you don't collect the ball on the paddle, you lose the ball." ) ; outtextxy ( 30, 108, "On loosing a ball you loose 10 points." ) ; outtextxy ( 30, 128, "On taking a brick you gain 10 points." ) ; changetextstyle(7, HORIZ_DIR, 3); outtextxy ( 100, 148, "Press any key to continue ..." ) ; bell ( 3 ) ; /* ring music */ fflush ( stdin ) ; // if ( getch() == 0 ) // getch() ; closegraph(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi" ) ; rectangle(2,2,620,195); setbkcolor(4); /* display the main menu */ while ( 1 ) { changetextstyle(4,HORIZ_DIR,5); outtextxy ( 60, 8, "Options Available:" ) ; outtextxy ( 150, 55, "Play ( P )" ) ; outtextxy ( 150, 125, "Exit ( E )" ) ; ch = 0 ; /* continue untill you select the correct choice */ while ( ! ( ch == 'E' || ch == 'P' ) ) { fflush ( stdin ) ; /* if a special key is hit, flush the keyboard buffer */ if ( ( ch = getch() ) == 0 ) getch() ; else ch = toupper ( ch ) ; /* store the uppercase of the choice made*/ } if ( ch == 'P' ) break ; if (ch == 'E') exit ( 0 ) ; } // setviewport ( 1, 125 - 12, MaxX - 1, MaxY - 1, 1 ) ; // clearviewport() ; closegraph(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi" ) ; rectangle(2,2,620,195); setbkcolor(4); /* display menu for the diffrent levels */ changetextstyle(7,HORIZ_DIR,3); outtextxy ( 60, 8, "Select the level for play:" ) ; outtextxy ( 150,50, "Slow ( S )" ) ; outtextxy ( 150, 100, "Medium ( M )" ) ; outtextxy ( 150, 150, "Fast ( F )" ) ; /* accept user's choice */ fflush ( stdin ) ; if ( ( ch = getch() ) == 0 ) getch() ; clearviewport() ; /* return the choice selected by the user */ return ( ch ) ; } /* This function draws bricks at the start of the game.There are four layers of the bricks */ bricks() { int i, j, lx = 0, ly = 0 ; for ( i = 0 ; i < 5 ; i++ ) /* 5 rows */ { for ( j = 0 ; j < 30 ; j++ ) /* 20 columns */ { /* draw a brick at appropriate coordinates */ rectangle ( lx, ly, lx + 20, ly + 7 ) ; floodfill ( lx + 1, ly + 1, 2 ) ; lx = lx + 32 ; } lx = 0 ; ly = ly + 10 ; } } /* This function erases the brick which is knock by the ball */ delbrick ( int b, int l ) { /* b - brick number, l - layer */ setcolor ( BLACK ) ; rectangle ( b * 32, l * 10, ( b * 32 ) + 20 , ( l * 10 ) + 7 ) ; rectangle ( b * 32 + 1, l * 10, ( b * 32 ) + 20 - 1, ( l * 10 ) + 7 - 1 ) ; rectangle ( b * 32 + 2, l * 10, ( b * 32 ) + 20 - 2, ( l * 10 ) + 7 - 2 ) ; rectangle ( b * 32 + 3, l * 10, ( b * 32 ) + 20 - 3, ( l * 10 ) + 7 - 3 ) ; rectangle ( b * 32 + 4, l * 10, ( b * 32 ) + 20 - 4, ( l * 10 ) + 7 - 4 ) ; rectangle ( b * 32 + 5, l * 10, ( b * 32 ) + 20 - 5, ( l * 10 ) + 7 - 5 ) ; rectangle ( b * 32 + 6, l * 10, ( b * 32 ) + 20 - 6, ( l * 10 ) + 7 - 6 ) ; setcolor ( CGA_YELLOW ) ; } /* plays different types of music */ bell ( int m_no ) { /* natural frequencies of 7 notes */ float wave[6] = { 120.81, 136.83, 144.81, 154.61, 216, 240 } ; int n, i ; switch ( m_no ) { case 1 : for ( i = 0 ; i < 6 ; i++ ) { sound ( wave[i] * 1 ) ; delay ( 30 ) ; } nosound() ; break ; case 2 : for ( i = 0 ; i < 15 ; i++ ) { n = random ( 6 ) ; sound ( wave[n] * 2 ) ; delay ( 100 ) ; } nosound() ; break ; case 3 : // while ( !kbhit() ) { n = random ( 6 ) ; sound ( wave[n] * 2 ) ; delay ( 100 ) ; } nosound() ; /* flush the keyboard buffer */ if ( getch() == 0 ) getch() ; break ; case 4 : for ( i = 5 ; i >= 0 ; i-- ) { sound ( wave[i] * 4 ) ; delay ( 15 ) ; } nosound() ; break ; case 5 : sound ( wave[2] * 5 ) ; delay ( 50 ) ; nosound() ; } } /* */ /* INITIALIZE: Initializes the graphics system and reports */ /* any errors which occured. */ /* */ void Initialize(void) { int xasp, yasp; /* Used to read the aspect ratio*/ GraphDriver = DETECT; /* Request auto-detection */ initgraph( &GraphDriver, &GraphMode, "c:\tc\bgi" ); ErrorCode = graphresult(); /* Read result of initialization*/ if( ErrorCode != grOk ){ /* Error occured during init */ printf(" Graphics System Error: %s ", grapherrormsg( ErrorCode ) ); exit( 1 ); } getpalette( &palette ); /* Read the palette from board */ MaxColors = getmaxcolor() + 1; /* Read maximum number of colors*/ MaxXX = getmaxx(); MaxYY = getmaxy(); /* Read size of screen */ } /* */ /* SAYGOODBYE: Give a closing screen to the user before leaving. */ /* */ void SayGoodbye(void) { struct viewporttype viewinfo; /* Structure to read viewport */ int h, w; // MainWindow( "== Finale ==" ); getviewsettings( &viewinfo ); /* Read viewport settings */ changetextstyle( TRIPLEX_FONT, HORIZ_DIR, 4 ); settextjustify( CENTER_TEXT, CENTER_TEXT ); h = viewinfo.bottom - viewinfo.top; w = viewinfo.right - viewinfo.left; cleardevice(); // StatusLine( "Press any key to EXIT" ); getch(); cleardevice(); /* Clear the graphics screen */ } //} /* */ /* CHANGETEXTSTYLE: similar to settextstyle, but checks for */ /* errors that might occur while loading the font file. */ /* */ void changetextstyle(int font, int direction, int charsize) { int ErrorCode; graphresult(); /* clear error code */ settextstyle(font, direction, charsize); ErrorCode = graphresult(); /* check result */ if( ErrorCode != grOk ){ /* if error occured */ closegraph(); printf(" Graphics System Error: %s ", grapherrormsg( ErrorCode ) ); exit( 1 ); } } /* The main function body of main screen which displays the main screen creating the opening screen display */ mainscreen() { int maxx, maxy, in, area; // get maximum x, y coordinates of the screen maxx = getmaxx(); maxy = getmaxy(); // setbkcolor sets the current background color using the palette setbkcolor(RED); // Draws a rectangle (graphics mode) rectangle(0, 0, maxx, maxy); // sets the line style and text justification in screen changetextstyle(10, HORIZ_DIR, 4); // displaying the output text on main screen outtextxy(140, 0, " WELCOME"); outtextxy(170,50," TO "); outtextxy(140,100," BRICKS"); changetextstyle(7, HORIZ_DIR, 3); bell(3); outtextxy(110, 160, "Press any key to continue..."); // Flushes the standard input device fflush(stdin); getch(); closegraph(); }

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

To create a program in Graphics Mode, the first step would be to include the header file graphics.h. This file is required for Graphics programming. After this, the graphics have to be initialized. C Language supports 16 Bit's MS-DOS environment. Initializing the Graphics mode is to call various functions, one such is called initgraph. initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver), and putting the system into graphics mode. To start the graphics system, first call the initgraph function. initgraph loads the graphics driver and puts the system into graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode. initgraph also resets all graphics settings to their defaults (current position, palette, color, viewport, and so on)

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

getmaxcolor() returns highest possible color value. The header file graphics.h contains getmaxcolor() function, which returns maximum color value for current graphics mode and driver. As color numbering starts from zero, total number of colors available for current graphics mode and driver are ( getmaxcolor() + 1 ) . getmaxcolor returns the maximum color value. There are various colors that are also mentioned in graphics.h header file and the possible color values are from 0 - 15:

The nosound() function in C language is used to stop the sound played by sound() function. The nosound() function is simply silent the system. The sound() and nosound() functions are very useful as they can create very nice music with the help of programming and our user can enjoy music during working in out the program.

Our system can create various sounds on different frequencies. The sound() is very useful as it can create very nice music with the help of programming and our user can enjoy music during working in out the program. Sound function produces the sound of a specified frequency. Used for adding music to a C++ program.

In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value

putimage puts the bit image previously saved with getimage back onto the screen, with the upper left corner of the image placed at (left,top). bitmap points to the area in memory where the source image is stored. The op parameter to putimage specifies a combination operator that controls how the color for each destination pixel onscreen is computed, based on the pixel already onscreen and the corresponding source pixel in memory.

The kbhit is basically the Keyboard Hit. This function is present at conio.h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero. kbhit() is used to determine if a key has been pressed or not. If a key has been pressed then it returns a non zero value otherwise returns zero.

restorecrtmode restores the original video mode detected by initgraph. This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes. Textmode should not be used for this purpose; use it only when the screen is in text mode, to change to a different text mode. restorecrtmode is implemented in winbgim, but it does not do any work. This is because both the graphics window and the text window are always open during any Windows program, so there is no need to switch back and forth between the two modes.

Positions cursor in text window. The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved. If the coordinates are in any way invalid the call to gotoxy is ignored. Neither argument to gotoxy can be zero.

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 header file graphics.h contains line() function which is used to draw a line from a point(x1, y1) to point(x2, y2) i.e. (x1, y1) and (x2, y2) are end points of the line. The function line() draws a line on the graphics screen between two specified points. So this function requires four parameters namely x1, y1, x2, and y2 to represent two points. This function draws a line from (x1, y1) coordinates to (x2, y2) coordinates on the graphics screen.

floodfill function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area.(x, y) is any point on the screen if (x,y) lies inside the area then inside will be filled otherwise outside will be filled, border specifies the color of boundary of area. To change fill pattern and fill color use setfillstyle.

Draws an ellipse using (x,y) as a center point and xradius and yradius as the horizontal and vertical axes, and fills it with the current fill color and fill pattern. The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (xradius, yradius) as x and y radius of ellipse. Where, (x, y) is center of the ellipse. (xradius, yradius) are x and y radius of ellipse.

The header file graphics.h contains imagesize() function which returns the number of bytes required to store a bit-image. This function is used when we are using getimage. imagesize() function returns the required memory area to store an image in bytes. imagesize() function returns the number of bytes needed to store the top-left corner of the screen at left, top and the bottom-right corner at right, bottom. This function is usually used in conjunction with the getimage() function. The imagesize() function only works in graphics mode.

getimage() function copy a specific portion into memory. This specific image would be any bit image like rectangle, circle or anything else. getimage() copies an image from the screen to memory. Left, top, right, and bottom define the screen area to which the rectangle is copied. Bitmap points to the area in memory where the bit image is stored. The first two words of this area are used for the width and height of the rectangle; the remainder holds the image itself.

rectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.

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.

clearviewport() function clears the current viewport. setviewport will create a new viewport by accepting left, top, right and bottom coordinates. clearviewport() function will erase the drawing done on the view port only and not the whole screen. Cleardevice is the function used to clear the whole screen with the background color.

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.

Flush stream. The fflush() function in C++ flushes any buffered data to the respective device. Buffered data is the temporary or application specific data stored in the physical memory of the computer until a certain time. If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file. If stream is a null pointer, all such streams are flushed. In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).

delay() function is used to hold the program's execution for given number of milliseconds, it is declared in dos.h header file. There can be many instances when we need to create a delay in our programs. C++ provides us with an easy way to do so. We can use a delay() function for this purpose in our code. We can run the code after a specific time in C++ using delay() function.

setbkcolor() function is used to set the background color in graphics mode. The default background color is black and default drawing color as we know is white. setbkcolor() function takes only one argument it would be either the name of color defined in graphics.h header file or number associated with those colors. If we write setbkcolor(yellow) it changes the background color in Green. The possible color values are from 0 - 15 black, blue, green, cyan, red, magenta, brown, lightgray, darkgray, lightblue, lightgreen, lightcyan, lightred, lightmagenta, yellow, white and blink (128).

Settextstyle function is used to change the way in which text appears, using it we can modify the size of text, change direction of text and change the font of text. settextstyle sets the text font, the direction in which text is displayed, and the size of the characters. A call to settextstyle affects all text output by outtext and outtextxy.

Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.

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().)

The header file graphics.h contains closegraph() function which closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. closegraph() function is used to re-enter in the text mode and exit from the graphics mode. If you want to use both text mode and graphics mode in the program then you have to use both initgraph() and closegraph() function in the program. This function deallocates all memory allocated by graphics system and restores the screen to that mode in which it was presented before you called the initgraph() function.

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.

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.

setcolor() function is used to set the foreground color in graphics mode. After resetting the foreground color you will get the text or any other shape which you want to draw in that color. setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors shown below are available for the CGA and EGA, respectively.

Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is

setviewport() establishes a new viewport for graphics output. The viewport corners are given in absolute screen coordinates by (left,top) and (right,bottom). The current position (CP) is moved to (0,0) in the new window. The parameter clip determines whether drawings are clipped (truncated) at the current viewport boundaries. If clip is nonzero, all drawings will be clipped to the current viewport. setviewport function is used to restrict drawing to a particular portion on the screen.

Convert lowercase letter to uppercase. The toupper() function in C++ converts a given character to uppercase. It is defined in the cctype header file. Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged. Notice that what is considered a letter may depend on the locale being used; In the default "C" locale, a lowercase letter is any of: a b c d e f g h i j k l m n o p q r s t u v w x y z, which translate respectively to: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z. The toupper() function takes the following parameter: c - a character, casted to int type or EOF. Function returns the uppercase equivalent to c, if such value exists, or c (unchanged) otherwise. The value is returned as an int value that can be implicitly casted to char.

Text output after a call to settextjustify is justified around the current position horizontally and vertically, as specified. The default justification settings are LEFT_TEXT (for horizontal) and TOP_TEXT (for vertical). The enumeration text_just in graphics.h provides names for the horiz and vert settings passed to settextjustify.

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.

The header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver. getmaxx() returns the maximum (screen-relative) x value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxx returns 319. getmaxx is invaluable for centering, determining the boundaries of a region onscreen, and so on.

This library function is declared in graphics.h and used to draw a circle; it takes centre point coordinates and radius. Circle function is used to draw a circle with center (x,y) and third parameter specifies the radius of the circle. The code given below draws a circle. Where, (x, y) is center of the circle. 'radius' is the Radius of the circle.

The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver. getmaxy returns the maximum (screen-relative) y value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxy returns 199. getmaxy is invaluable for centering, determining the boundaries of a region onscreen, and so on.

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.

outtextxy displays a text string in the viewport at the given position (x, y), using the current justification settings and the current font, direction, and size. To maintain code compatibility when using several fonts, use textwidth and textheight to determine the dimensions of the string. If a string is printed with the default font using outtext or outtextxy, any part of the string that extends outside the current viewport is truncated. outtextxy is for use in graphics mode; it will not work in text mode.

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block. • The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and

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).

The header file graphics.h contains cleardevice() function. cleardevice() is a function which is used to clear the screen by filling the whole screen with the current background color. It means that cleardevice() function is used to clear the whole screen with the current background color and it also sets the current position to (0,0). Both clrscr() and cleardevice() functions are used to clear the screen but clrscr() is used in text mode and cleardevice function is used in the graphics mode.

#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.

Heap sort is comparison based algorithm. It's selection sort sample. The time complexity is O(n*log(n)). Build a max heap using the given data element. And then Delete the root node





A "stack" is a basic data structure and can be defined in an abstract, implementation-free manner, or it can be generally "defined" as a linear list of items in which all additions and




C++ Program demonstrates the Removal of All the nodes which don't lie in any Path with Sum greater than or equal to K. Create a new 'Binary Tree node' with given data. Truncates