C++ Programming Code Examples
C++ > Games Code Examples
Rattle Snake - A excellent snake game developed in c/c++.
/* Rattle Snake - A excellent snake game developed in c/c++. */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <iostream.h>
#include <fstream.h>
#include <string.h>
void main(void)
{
int gdriver = DETECT, gmode, errorcode;
void
*body,*food,*tail1,*tail2,*tail3,*tail4,*head1,*head2,*head3,*head4;
int x, y,X[5000],Y[5000],i=3,
maxx,maxy,speed=100,bo=10,t[10],score=0,hscore=20;
unsigned int size;
char a='6',b,scor[4],hs[4];
int k=2,l,r1,r2,f=0,z=100,first=0,second=1;;
r1=300;
r2=350;
ifstream infile("c:\tc\bin\rattle.txt");
infile.getline(hs,4);
infile.close();
hscore = atoi(hs);
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "c:\tc\bgi");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s
", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
maxx = getmaxx();
maxy = getmaxy();
y = 160;
x = 80;
for(int j=0; j<=3; j++)
{
X[i-j]=x-bo*(j+1);
Y[i-j]=y;
}
//body
setfillstyle(1,2);
bar(10,10,20,20);
setcolor(0);
setlinestyle(0,1,3);
line(9,9,21,21);
line(9,21,21,9);
size = imagesize(10,10,20,20);
body = malloc(size);
getimage(10,10,20,20,body);
cleardevice();
setcolor(0);
//tail1-right
t[0]=20; t[1]=10;
t[2]=10; t[3]=10;
t[4]=20; t[5]=15;
t[6]=10; t[7]=20;
t[8]=20; t[9]=21;
fillpoly(5, t);
size = imagesize(10,10,20,21);
tail1 = malloc(size);
getimage(10,10,20,21,tail1);
cleardevice();
//tail2-left
t[0]=10; t[1]=10;
t[2]=20; t[3]=10;
t[4]=10; t[5]=15;
t[6]=20; t[7]=20;
t[8]=10; t[9]=21;
fillpoly(5, t);
size = imagesize(10,10,20,21);
tail2 = malloc(size);
getimage(10,10,20,21,tail2);
cleardevice();
//tail3-up
t[0]=10; t[1]=20;
t[2]=10; t[3]=10;
t[4]=15; t[5]=20;
t[6]=20; t[7]=10;
t[8]=20; t[9]=21;
fillpoly(5, t);
size = imagesize(10,10,20,21);
tail3 = malloc(size);
getimage(10,10,20,21,tail3);
cleardevice();
//tail4-down
t[0]=10; t[1]=10;
t[2]=10; t[3]=21;
t[4]=15; t[5]=10;
t[6]=20; t[7]=21;
t[8]=20; t[9]=10;
fillpoly(5, t);
size = imagesize(10,10,20,21);
tail4 = malloc(size);
getimage(10,10,20,21,tail4);
cleardevice();
//head1-right
setlinestyle(1,1,1);
setcolor(2);
fillellipse(10,10,10,5);
setcolor(4);
//eyes
fillellipse(15,7,1,1);
fillellipse(15,13,1,1);
size = imagesize(10,5,20,15);
head1 = malloc(size);
getimage(10,5,20,15,head1);
//head2-left
//eyes
fillellipse(5,7,1,1);
fillellipse(5,13,1,1);
size = imagesize(0,5,10,15);
head2 = malloc(size);
getimage(0,5,10,15,head2);
cleardevice();
//head3-up
//eyes
setcolor(2);
fillellipse(12,12,5,10);
setcolor(4);
fillellipse(9,6,1,1);
fillellipse(15,6,1,1);
size = imagesize(7,2,18,12);
head3 = malloc(size);
getimage(7,2,18,12,head3);
//head4-down
//eyes
fillellipse(9,17,1,1);
fillellipse(15,17,1,1);
size = imagesize(7,12,18,22);
head4 = malloc(size);
getimage(7,12,18,22,head4);
cleardevice();
//food
setcolor(15);
setfillstyle(1,15);
fillellipse(10,10,3,5);
size = imagesize(5,3,15,17);
food = malloc(size);
getimage(5,3,15,17,food);
cleardevice();
/* repeat until a key is pressed */
maxx=getmaxx();
maxy=getmaxy();
setlinestyle(0,1,3);
setcolor(9);
rectangle(0,0,maxx,maxy);
setlinestyle(0,1,2);
line(maxx-150,0,maxx-150,maxy);
setcolor(8);
setfillstyle(1,8);
bar(maxx-147,3,maxx-3,63);
setcolor(12);
int maze=1;
if(maze==1)
{
setfillstyle(1,6);
bar(4,4,maxx-154,14);
bar(4,4,14,maxy-4);
bar(4,maxy-4,maxx-154,maxy-14);
bar(maxx-154-10,4,maxx-154,maxy-4);
}
settextstyle(0,0,1);
delay(300);
outtextxy(maxx-125,30,"RATTLE SNAKE");
delay(300);
setcolor(11);
setlinestyle(0,1,2);
rectangle(maxx-145,65,maxx-5,205);
outtextxy(maxx-128,70,"INSTRUCTIONS");
delay(200);
setcolor(6);
outtextxy(maxx-140,90,"Commands Key");
delay(300);
setcolor(8);
outtextxy(maxx-140,110," Move Up 8");
delay(50);
outtextxy(maxx-140,130," Move Down 5");
delay(50);
outtextxy(maxx-140,150," Move Right 6");
delay(50);
outtextxy(maxx-140,170," Move Left 4");
delay(50);
outtextxy(maxx-140,190," Exit 0");
delay(200);
setcolor(12);
setlinestyle(0,1,2);
rectangle(maxx-145,210,maxx-5,350);
setcolor(1);
outtextxy(maxx-130,220,"Player's Name");
setcolor(15);
outtextxy(maxx-100,230,"Yellow");
setcolor(4);
delay(200);
itoa(score,scor,10);
outtextxy(maxx-140,250,"Score");
outtextxy(maxx-50,250,scor);
delay(200);
setcolor(10);
outtextxy(maxx-140,280,"Level");
delay(200);
setcolor(13);
outtextxy(maxx-140,310,"Maze 1");
delay(200);
setcolor(14);
outtextxy(maxx-140,340,"High Score ");
outtextxy(maxx-50,340,hs);
for(j=0; j<=1000; j++)
{
putpixel(random(maxx-150),random(maxy),6);
delay(1);
}
while (a!='0')
{
// plot new image
if(a=='6')
putimage(x, y, head1, XOR_PUT);
if(a=='4')
putimage(x, y, head2, XOR_PUT);
if(a=='8')
putimage(x, y, head3, XOR_PUT);
if(a=='5')
putimage(x, y, head4, XOR_PUT);
for(j=0; j<k; j++)
{
putimage(X[i-j], Y[i-j], body, XOR_PUT);
}
if((X[i-j-1]-X[i-j])<0 && (Y[i-j-1]-Y[i-j])==0)
putimage(X[i-j], Y[i-j], tail1, XOR_PUT);
if((X[i-j-1]-X[i-j])>0 && (Y[i-j-1]-Y[i-j])==0)
putimage(X[i-j], Y[i-j], tail2, XOR_PUT);
if((X[i-j-1]-X[i-j])==0 && (Y[i-j-1]-Y[i-j])<0)
putimage(X[i-j], Y[i-j], tail3, XOR_PUT);
if((X[i-j-1]-X[i-j])==0 && (Y[i-j-1]-Y[i-j])>0)
putimage(X[i-j], Y[i-j], tail4, XOR_PUT);
delay(speed);
if(second==1)
{
setcolor(15);
outtextxy(maxx-140,360,"Press Any Key...");
getch();
setcolor(0);
outtextxy(maxx-140,360,"Press Any Key...");
a='6';
second=2;
}
if(first==1)
{
setcolor(15);
outtextxy(maxx-140,360,"Congratulations ");
sound(100);
delay(300);
nosound();
getch();
setcolor(0);
outtextxy(maxx-140,360,"Congratulations ");
second++;
first=2;
}
// erase old image
if(a=='6')
putimage(x, y, head1, XOR_PUT);
if(a=='4')
putimage(x, y, head2, XOR_PUT);
if(a=='8')
putimage(x, y, head3, XOR_PUT);
if(a=='5')
putimage(x, y, head4, XOR_PUT);
for(j=0; j<k; j++)
{
putimage(X[i-j], Y[i-j], body, XOR_PUT);
}
if((X[i-j-1]-X[i-j])<0 && (Y[i-j-1]-Y[i-j])==0)
putimage(X[i-j], Y[i-j], tail1, XOR_PUT);
if((X[i-j-1]-X[i-j])>0 && (Y[i-j-1]-Y[i-j])==0)
putimage(X[i-j], Y[i-j], tail2, XOR_PUT);
if((X[i-j-1]-X[i-j])==0 && (Y[i-j-1]-Y[i-j])<0)
putimage(X[i-j], Y[i-j], tail3, XOR_PUT);
if((X[i-j-1]-X[i-j])==0 && (Y[i-j-1]-Y[i-j])>0)
putimage(X[i-j], Y[i-j], tail4, XOR_PUT);
if(f==0)
{
putimage(r1,r2,food,XOR_PUT);
f=1;
}
z--;
if((x>=r1 && y>=r2 && x<=r1+10 && y<=r2+10) || (x<=r1 && y<=r2 &&
x>=r1-10 && y>=r2-10) || z==0)
{
if(z!=0)
{
sound(800);
delay(20);
setcolor(0);
score += 10;
outtextxy(maxx-50,250,scor);
itoa(score,scor,10);
if(score>hscore)
{
strcpy(hs,scor);
setfillstyle(1,1);
bar(maxx-140,337,maxx-20,348);
setcolor(14);
outtextxy(maxx-50,340,hs);
outtextxy(maxx-140,340,"High Score ");
if(first==0)
{
first=1;
}
}
setcolor(4);
outtextxy(maxx-50,250,scor);
k++;
nosound();
}
z=100;
putimage(r1,r2,food,XOR_PUT);
repr1:
r1=random(450);
if(r1<50)
goto repr1;
repr2:
r2=random(400);
if(r2<50)
goto repr2;
f=0;
}
i++;
X[i]=x;
Y[i]=y;
b=a;
if(kbhit())
{
rep:
a=getche();
if((b=='6' && a=='4') || (b=='4' && a=='6'))
a=b;
if((b=='8' && a=='5') || (b=='5' && a=='8'))
a=b;
if(a!='6' && a!='4' && a!='8' && a!='0' && a!='5')
a=b;
}
/* if(x>maxx-170)
x=0;
if(y>maxy)
y=0;*/
if(a=='8')
y -= bo;
if(a=='5')
y += bo;
if(a=='4')
x -= bo;
if(a=='6')
x += bo;
for(j=i+1; j<i-k; j--)
{
if((Y[i]>=Y[j] && Y[i]<=Y[j]+10) || (Y[i]<=Y[j] && Y[i]>=X[j]-10))
{
if((X[i]>=X[j] && X[i]<=X[j]+10) || (X[i]<=X[j] && X[i]>=X[j]-10))
{
a='0';
}
outtextxy(maxx-140,360,"C ");
}
if((X[i]>=X[j] && X[i]<=X[j]+10) || (X[i]<=X[j] && X[i]>=X[j]-10))
{
if((Y[i]>=Y[j] && Y[i]<=Y[j]+10) || (Y[i]<=Y[j] && Y[i]>=X[j]-10))
{
a='0';
}
outtextxy(maxx-140,360,"C ");
}
}
/* for(j=i; j<i-k; j--)
{
if((y>=Y[j] && y<=Y[j]+10) || (y<=Y[j] && y>=Y[j]-10))
{
if((x>=X[j] && x<=X[j]+10) || (x<=X[j] && x>=X[j]-10))
{
a='5';
}
}
if((x>=X[j] && x<=X[j]+10) || (x<=X[j] && x>=X[j]-10))
{
if((y>=Y[j] && y<=Y[j]+10) || (y<=Y[j] && y>=Y[j]-10))
{
a='5';
}
}
if(j==0)
break;
} */
/* if(x<=0)
x=maxx-170;
if(y<=0)
y=maxy;*/
if(maze==1)
{
if(x<=14 || x>=maxx-184 || y<=14 || y>=maxy-14)
{
a='0';
}
}
}
if(score>hscore)
{
ofstream onfile("c:\tc\bin\rattle.txt");
onfile<<scor;
onfile.close();
}
setcolor(15);
outtextxy(maxx-140,390," Gameover");
sound(100);
delay(400);
nosound();
getch();
/* clean up */
free(body);
closegraph();
}
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.
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.
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 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.
setlinestyle() is a function which is used to draw the line of different- different styles. Turbo C compiler provides five line styles that are solid, dotted, center, dashed and user defined. These all five line styles are already enumerated in graphics.h header file as given below: setlinestyle() function contains three parameters type, pattern and thickness. First parameter contains the type of line like solid, dashed or dotted etc. Second parameter is applicable only when type of line is user defined. Third parameter specifies the thickness of the line it takes values 1 (line thickness of one pixel (normal)) or 3 (line thickness of three pixels (thick).
Convert string to integer. Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int. The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
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.
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.
bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file. Bar function is used to draw a 2-dimensional, rectangular filled in bar. Coordinates of left top and right bottom corner are required to draw the bar. 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. Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle.
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.
The header file graphics.h contains putpixel() function which plots a pixel at location (x, y) of specified color. Where, (x, y) is the location at which pixel is to be put, and color specifies the color of the pixel. To put a pixel on the screen at a particular position, calling the pixel() function is a good way. This function takes three parameters as the position of the pixel and also the color of the pixel.
The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. Current fill pattern and fill color is used to fill the area. setfillstyle sets the current fill pattern and fill color. To set a user-defined fill pattern, do not give a pattern of 12 (USER_FILL) to setfillstyle; instead, call setfillpattern.
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.
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.
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.
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
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.
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.
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)
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.
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.
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 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.
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().)
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.
Convert integer to string (non-standard function). Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned. str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms. Function returns a pointer to the resulting null-terminated string, same as parameter str.
#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.
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.
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.
Deallocate memory block. A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. If ptr is a null pointer, the function does nothing. Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. free() function in C++ <cstdlib> library is used to deallocate a memory block in C++. Whenever we call malloc, calloc or realloc function to allocate a memory block dynamically in C++, compiler allocates a block of size bytes of memory and returns a pointer to the start of the block. The new memory block allocated is not initialized but have intermediate values. free() method is used to free such block of memory. In case the pointer mentioned does not point to any memory block then it may lead to an undefined behavior, but does nothing in case of null
fillpoly() draws the outline of a polygon with number points in the current line style and color (just as drawpoly does), then fills the polygon using the current fill pattern and fill color. The header file graphics.h contains fillpoly() function which is implemented to draw and fill a polygon such as triangle, rectangle, pentagon, hexagon etc. So this function require same arguments as drawpoly().
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.
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.
Get line from stream into string. The cin is an object which is used to take input from the user but does not allow to take the input in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined function defined in a <string.h> header file used to accept a line or a string from the input stream until the delimiting character is encountered. Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)). The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation. If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
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.
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.
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:
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.
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.
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.
Whenever the 'character' does not match, we slide the pattern in such a way that aligns the bad character with the last occurrence of it in pattern. We preprocess the pattern and store