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++ > Computer Graphics Code Examples

Design of Clock in Turbo C++ 3.0 graphics

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/* Design of Clock in Turbo C++ 3.0 graphics */ #include<stdio.h> #include<process.h> #include<iostream.h> #include<dos.h> #include<graphics.h> #include<conio.h> #include<math.h> void draw() { setbkcolor(0); setlinestyle(0,0,0); setcolor(9); circle(320,240,3); setcolor(11); setfillstyle(6,13); circle(320,240,150); circle(320,240,165); floodfill(156,242,11); settextstyle(2,0,5); setcolor(14); outtextxy(314,98,"12"); outtextxy(384,114,"1"); outtextxy(434,163,"2"); outtextxy(454,230,"3"); outtextxy(317,369,"6"); outtextxy(177,230,"9"); outtextxy(436,300,"4"); outtextxy(195,302,"8"); outtextxy(195,163,"10"); outtextxy(244,112,"11"); outtextxy(388,353,"5"); outtextxy(248,353,"7"); } main() { int gd=0,gm; initgraph(&gd,&gm,"c:\tc\bgi"); draw(); //line(320,240,320,130); //line(320,240,320,150); //getch(); float s; float df; //s=282*M_PI/180; //float angle=4.712389; //float an=4.712389; float anf=4.712389; //float angle=0; int x,y; int q,w; int ta,d; float as; as=6*M_PI/180; int c2=0; int count=0; struct time t; gettime(&t); float angle=4.712389+t.ti_sec*.1047198; float an=4.712389+t.ti_min*.1047198; while(!kbhit()) { draw(); gettime(&t); gotoxy(5,5); angle=4.712389+t.ti_sec*.1047198; an=4.712389+t.ti_min*.1047198; anf=4.712389+t.ti_hour*5*.1047198 ; if(t.ti_min>=12&&t.ti_min<24) { anf=anf+2*.1047198; } if(t.ti_min>=24&&t.ti_min<36) { anf=anf+(3*.1047198); } if(t.ti_min>=36&&t.ti_min<48) { anf=anf+(4*.1047198); } if(t.ti_min>=48&&t.ti_min<60) { anf=anf+(5*.1047198); } gotoxy(2,2); printf("The current time is: %d: %d: %d ", t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund); cout<<" "; setlinestyle(0,0,0); setcolor(0); line(320,240,x,y); line(320,240,q,w); line(320,240,ta,d); x=320+140*cos(angle); y=240+140*sin(angle); q=320+122*cos(an); w=240+122*sin(an); ta=320+86*cos(anf); d=240+86*sin(anf); setcolor(10); setlinestyle(0,0,0); line(320,240,x,y); setlinestyle(0,0,2); setcolor(9); line(320,240,q,w); setlinestyle(0,0,3); setcolor(4); line(320,240,ta,d); angle+=.1047198; delay(1000); count++; /*if(c2==12) { setlinestyle(0,0,3); c2=0; anf+=.1047198; } */ } getch(); }
initgraph() Function in C++
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) and resets graphresult to 0.
Syntax for initgraph() Function in C++
void initgraph (int *graphdriver, int *graphmode, char *pathtodriver);
graphdriver
This is an integer that indicates that the graphics driver has been used.
graphmode
It is also an integer value that detects the available graphics driver and initializes the graphics mode according to its highest resolution.
pathtodriver
This is the path of the directory that first searches the initgraph function graphics driver. If the graphics driver is not available then the system searches it in the current directory. It is necessary to pass the correct value of the three parameters in the initgraph function or else an unpredictable output is obtained.
intgd = DETECT, gm; initgraph (&gd, &gm, " ");
To initialize Graphics mode, you only have to write two lines. Here, we have taken two integer variables 'd' and 'm'. Here, DETECT is an enumeration type that identifies and identifies the proper graphics driver. The initgraph function has to pass the address of both the variables. You can see in the example that we have given a space at the position of the third variable. This means that if you do not know the driver's path then you can leave it blank. The compiler will auto-detect the path. initgraph always sets the internal error code; on success, it sets the code to 0. If an error occurred, *graphdriver is set to -2, -3, -4, or -5, and graphresult returns the same value as listed below: • grNotDetected -2 Cannot detect a graphics card • grFileNotFound -3 Cannot find driver file • grInvalidDriver -4 Invalid driver • grNoLoadMem -5 Insufficient memory to load driver
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* 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. */ int DGraphics::Init( int gmode ) { int gdriver = VGA, errorcode; gdriver=installuserdriver("SVGA256",NULL); initgraph(&gdriver, &gmode, ""); if ( (errorcode = graphresult()) != grOk ) { cout << "Error: Graphics - %s\n" << grapherrormsg(errorcode); return FALSE; } ActiveMode=gmode; return TRUE; }
delay() Function in C++
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.
Syntax for delay() Function in C++
void delay(unsigned int milliseconds);
milliseconds
how many milliseconds to delay The function takes one parameter which is unsigned integer. Here, void suggests that this function returns nothing. 'delay' is the function name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* hold the program's execution for given number of milliseconds by delay() function code example. */ #include<iostream.h> #include<dos.h> //for delay() #include<conio.h> //for getch() int main() { clrscr(); int n; cout<<"Enter the delay (in seconds) you want to make after giving input."<<endl; cin>>n; delay(n*1000); cout<<"This has been printed after "<< n <<" seconds delay"; getch(); return 0; }
outtextxy() Function in C++
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.
Syntax for outtextxy() Function in C++
#include <graphics.h> void outtextxy(int x, int y, char *string);
x
x-coordinate of the point
y
y-coordinate of the point
string
string to be displayed where, x, y are coordinates of the point and, third argument contains the address of string to be displayed. This function does not return any value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* outtextxy() function displays the text or string at a specified point (x, y) on the screen. */ // C++ Implementation for outtextxy() #include <graphics.h> int main() { textcolor(RED); cleardevice(); setcolor(RED); outtextxy(150,205,"Enter the Username:"); outtextxy(150,245,"Enter the Password:"); outtextxy(150,355,"Thank you"); outtextxy(150,445,"nice job"); outtextxy(50,105,"good day"); outtextxy(50,145,"pan"); outtextxy(50,255,"go"); outtextxy(50,245,"nice day"); return 0; }
If Else Statement in C++
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,
Syntax for If Statement in C++
if (condition) { // body of if 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.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
kbhit() Function in C++
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.
Syntax for kbhit() Function in C++
#include <conio.h> int kbhit();
Function returns true (non-zero) if there is a character in the input buffer, otherwise false. Note : kbhit() is not a standard library function and should be avoided.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* kbhit() function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed. */ // C++ program code example to fetch key pressed using kbhit() #include <conio.h> #include <iostream> int main() { char ch; while (1) { if (kbhit) { // Stores the pressed key in ch ch = getch(); // Terminates the loop // when escape is pressed if (int(ch) == 27) break; cout << "Key pressed= " << ch; } } return 0; }
Structures in C++ Language
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.
Syntax for Structures in C++
struct structureName{ member1; member2; member3; . . . memberN; };
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. Consider the following situation:
struct Teacher { char name[20]; int id; int age; }
In the above case, Teacher is a structure contains three variables name, id, and age. When the structure is declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario. Structures in C++ can contain two types of members: • Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++. • Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration. Structure variable can be defined as: Teacher s; Here, s is a structure variable of type Teacher. When the structure variable is created, the memory will be allocated. Teacher structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte. The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.
s.id = 4;
We are accessing the id field of the structure Teacher by using the dot(.) operator and assigns the value 4 to the id field. In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types. */ #include <iostream> using namespace std; struct Person { char name[50]; int age; float salary; }; int main() { Person p1; cout << "Enter Full name: "; cin.get(p1.name, 50); cout << "Enter age: "; cin >> p1.age; cout << "Enter salary: "; cin >> p1.salary; cout << "\nDisplaying Information." << endl; cout << "Name: " << p1.name << endl; cout <<"Age: " << p1.age << endl; cout << "Salary: " << p1.salary; return 0; }
floodfill() Function in C++
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.
Syntax for floodfill() Function in C++
#include <graphics.h> void floodfill(int x, int y, int border_color).
x
X coordinate of the point within the enclosed area to be filled
y
Y coordinate of the point within the enclosed area to be filled
border_color
specify the color int values corresponding to colors: • BLACK 0 • BLUE 1 • GREEN 2 • CYAN 3 • RED 4 • MAGENTA 5 • BROWN 6 • LIGHTGRAY 7 • DARKGRAY 8 • LIGHTBLUE 9 • LIGHTGREEN 10 • LIGHTCYAN 11 • LIGHTRED 12 • LIGHTMAGENTA 13 • YELLOW 14 • WHITE 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* floodfill() fills an enclosed area on bitmap devices. (x,y) is a "seed point" within the enclosed area to be filled. The area bounded by the color border is flooded with the current fill pattern and fill color. If the seed point is within an enclosed area, the inside will be filled. If the seed is outside the enclosed area, the exterior will be filled. Use fillpoly instead of floodfill whenever possible so that you can maintain code compatibility with future versions. */ /* fill an enclosed area on bitmap devices by floodfill() function code example. */ #include <stdio.h> #include <conio.h> void main() { int d,m; int midx,midy; d=DETECT; initgraph(&d,&m,"c:\\tc\\bgi"); midx=getmaxx()/2; midy=getmaxy()/2; circle(midx,midy,50); floodfill(midx,midy,15); circle(midx+50,midy+100,80); floodfill(midx,midy,15); getch(); closegraph(); }
setcolor() Function in C++
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.
Syntax for setcolor() Function in C++
void setcolor(int color);
color
specify the color setcolor() functions contains only one argument that is color. It may be the color name enumerated in graphics.h header file or number assigned with that color. This function does not return any value. INT VALUES corresponding to Colors: • BLACK 0 • BLUE 1 • GREEN 2 • CYAN 3 • RED 4 • MAGENTA 5 • BROWN 6 • LIGHTGRAY 7 • DARKGRAY 8 • LIGHTBLUE 9 • LIGHTGREEN 10 • LIGHTCYAN 11 • LIGHTRED 12 • LIGHTMAGENTA 13 • YELLOW 14 • WHITE 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* setcolor() function change the current drawing color in graphic mode. */ #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm; initgraph(&gd,&gm," "); setbkcolor(5);//set background color setcolor(11);//color of time settextstyle(4, HORIZ_DIR, 8);//font of time setcolor(GREEN); circle(320,240,100); setcolor(RED); outtextxy(320,80."It is circle"); getch(); closegraph(); }
setbkcolor() Function in C++
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).
Syntax for setbkcolor() Function in C++
#include<graphics> void setbkcolor(int color);
color
specify the color setbkcolor sets the background to the color specified by color. The argument color can be a name or a number as listed below. (These symbolic names are defined in graphics.h.) This function does not return any value. INT VALUES corresponding to Colors: • BLACK 0 • BLUE 1 • GREEN 2 • CYAN 3 • RED 4 • MAGENTA 5 • BROWN 6 • LIGHTGRAY 7 • DARKGRAY 8 • LIGHTBLUE 9 • LIGHTGREEN 10 • LIGHTCYAN 11 • LIGHTRED 12 • LIGHTMAGENTA 13 • YELLOW 14 • WHITE 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* change the background to the color specified by color in graphics mode. */ /* Program to make digital clock in C++ graphics */ #include<graphics> #include<conio.h> #include<time.h> int main() { initwindow(700,500,"CLOCK",300,100);//displays graphics window char t[15],date[10]; while(1) { setbkcolor(5);//set background color _strtime(t);//pick system time and saves in char array setcolor(11);//color of time settextstyle(4, HORIZ_DIR, 8);//font of time outtextxy(100, 100, t);//prints time delay(1000); } getch(); closegraph(); }
circle() Function in C++
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.
Syntax for circle() Function in C++
#include <graphics.h> circle(x, y, radius);
x
X-coordinate of the circle
y
Y-coordinate of the circle
radius
radius of the circle This function does not return any value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* draw a circle with center (x,y) and third parameter specifies the radius of the circle by circle() function code example. */ int gd=DETECT,gm=0,col=0,dol=600; initgraph(&gd,&gm,"c:/tc/bgi"); settextstyle(10,HORIZ_DIR,1); outtextxy(30,30,""); settextstyle(11,HORIZ_DIR,1); settextstyle(10,HORIZ_DIR,1); outtextxy(30,200,"Hit ENTER to Start the Magic..."); settextstyle(12,HORIZ_DIR,1); getch(); cleardevice(); while(!kbhit()) { for(int j=0;j<=50;j++) { { setcolor(2); circle(col,100,50+j); setfillstyle(4,2); floodfill(col,100,2); delay(3); col++; if(col>=600) col=0; }
Assignment Operators in C++
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:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */ // C++ program to demonstrate working of Assignment operators #include <iostream> using namespace std; int main() { // Assigning value 10 to a // using "=" operator int a = 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by adding 10 to a // using "+=" operator a += 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by dividing 10 from a // using "/=" operator a /= 10; cout << "Value of a is "<<a<<"\n"; return 0; }
line() Function in C++
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.
Syntax for line() Function in C++
void line(int x1, int y1, int x2, int y2);
x1
X coordinate of first point
y1
Y coordinate of first point.
x2
X coordinate of second point.
y2
Y coordinate of second point. You can change "linestyle", "pattern", "thickness" of the line by setlinestyle() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* draw a line in C++ graphic code example */ #include<iostream.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm,x,y; clrscr(); initgraph(&gd,&gm,"c:\\TC\\bgi"); //INITIALISING GRAPHICS MODE setlinestyle(0,0,3); outtextxy(300,150,"LINE()"); line(350,60,200,200); outtextxy(300,300," CURRENT POSITION"); linerel(320,350); outtextxy(335,315,"LINEREL()"); outtextxy(30,30," CURRENT POSITION"); lineto(30,200); outtextxy(70,45,"LINETO()"); getch(); closegraph(); }
settextstyle() Function in C++
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.
Syntax for settextstyle() Function in C++
#include <graphics.h> void settextstyle(int font, int direction, int charsize);
font
One 8x8 bit-mapped font and several "stroked" fonts are available. The 8x8 bit-mapped font is the default. The enumeration font_names, which is defined in graphics.h, provides names for these different font settings: • DEFAULT_FONT – 0 8x8 bit-mapped font • TRIPLEX_FONT – 1 Stroked triplex font • SMALL_FONT – 2 Stroked small font • SANS_SERIF_FONT – 3 Stroked sans-serif font • GOTHIC_FONT – 4 Stroked gothic font • SCRIPT_FONT – 5 Stroked script font • SIMPLEX_FONT – 6 Stroked triplex script font • TRIPLEX_SCR_FONT – 7 Stroked triplex script font • COMPLEX_FONT – 8 Stroked complex font • EUROPEAN_FONT – 9 Stroked European font • BOLD_FONT – 10 Stroked bold font The default bit-mapped font is built into the graphics system. Stroked fonts are stored in *.CHR disk files, and only one at a time is kept in memory. Therefore, when you select a stroked font (different from the last selected stroked font), the corresponding *.CHR file must be loaded from disk. To avoid this loading when several stroked fonts are used, you can link font files into your program. Do this by converting them into object files with the BGIOBJ utility, then registering them through registerbgifont.
direction
Font directions supported are horizontal text (left to right) and vertical text (rotated 90 degrees counterclockwise). The default direction is HORIZ_DIR. The size of each character can be magnified using the charsize factor. If charsize is nonzero, it can affect bit-mapped or stroked characters. A charsize value of 0 can be used only with stroked fonts.
charsize
• If charsize equals 1, outtext and outtextxy displays characters from the 8x8 bit-mapped font in an 8x8 pixel rectangle onscreen. • If charsize equals 2, these output functions display characters from the 8x8 bit-mapped font in a 16*16 pixel rectangle, and so on (up to a limit of ten times the normal size). • When charsize equals 0, the output functions outtext and outtextxy magnify the stroked font text using either the default character magnification factor (4) or the user-defined character size given by setusercharsize. Always use textheight and textwidth to determine the actual dimensions of the text. This function needs to be called before the outtextxy() function, otherwise there will be no effect on text and output will be the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* settextstyle() function sets the current text font, direction and character size. All calls to outtext() and outtextxy() are affected by the new settings. */ int main() { int gm, gd; gd = VGA; gm = VGAHI; initgraph(&gd, &gm, ""); settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4); outtextxy(32, 8, "SANS_SERIF_FONT"); settextstyle(DEFAULT_FONT, HORIZ_DIR, 4); outtextxy(32, 58, "DEFAULT_FONT"); settextstyle(GOTHIC_FONT, HORIZ_DIR, 4); outtextxy(32, 108, "GOTHIC_FONT"); settextstyle(SCRIPT_FONT, HORIZ_DIR, 4); outtextxy(32, 158, "SCRIPT_FONT"); getch(); closegraph(); }
setlinestyle() Function in C++
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).
Syntax for setlinestyle() Function in C++
#include <graphics.h> void setlinestyle(int linestyle, unsigned upattern, int thickness);
linestyle
First parameter contains the type of line like solid, dashed or dotted etc. The enumeration line_styles, which is defined in graphics.h, gives names to these operators: • SOLID_LINE 0 Solid line • DOTTED_LINE 1 Dotted line • CENTER_LINE 2 Centered line • DASHED_LINE 3 Dashed line • USERBIT_LINE 4 User-defined line style
upattern
Second parameter is applicable only when type of line is user defined.
thickness
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). • NORM_WIDTH 1 1 pixel wide • THICK_WIDTH 3 3 pixels wide Note: The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used. If invalid input is passed to setlinestyle, graphresult returns -11, and the current line style remains unchanged.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/* setlinestyle() function sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on. */ // C Implementation for setlinestyle() #include <graphics.h> // driver code int main() { // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // variable to change the // line styles int c; // initial coordinate to // draw line int x = 200, y = 100; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // To keep track of lines for ( c = 0 ; c < 5 ; c++ ) { // setlinestyle function setlinestyle(c, 0, 1); // Drawing line line(x, y, x+200, y); y = y + 25; } getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
gotoxy() Function in C++
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.
Syntax for gotoxy() Function in C++
void gotoxy(int x, int y);
x
X coordinate of the position where we want to place the cursor.
y
Y coordinate of the position where we want to place the cursor. This function does not return any value. Do not use this function for Win32s or Win32 GUI applications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* 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. */ // Description: prints grid at given origin (xPos, yPos) // Arguments: // xPos - x coordinate of origin // yPos - y coordinate of origin void Grid::print(int xPos, int yPos){ #ifdef EN_PRINT for(int i = 0;i < GRID_LENGTH;i++){ for(int j = 0;j < GRID_LENGTH;j++){ int x = xPos + 6 * j; int y = yPos + 2 * i; gotoXY(x,y); std::cout<<" "; gotoXY(x,y); std::cout<<m_data[i*GRID_LENGTH + j]; } } #endif }
setfillstyle() Function in C++
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.
Syntax for setfillstyle() Function in C++
#include<graphics.h> void setfillstyle(int pattern, int color);
color
Specify the color • BLACK – 0 • BLUE – 1 • GREEN – 2 • CYAN – 3 • RED – 4 • MAGENTA – 5 • BROWN – 6 • LIGHTGRAY – 7 • DARKGRAY – 8 • LIGHTBLUE – 9 • LIGHTGREEN – 10 • LIGHTCYAN – 11 • LIGHTRED – 12 • LIGHTMAGENTA – 13 • YELLOW – 14 • WHITE – 15
pattern
Specify the pattern • EMPTY_FILL – 0 • SOLID_FILL – 1 • LINE_FILL – 2 • LTSLASH_FILL – 3 • SLASH_FILL – 4 • BKSLASH_FILL – 5 • LTBKSLASH_FILL – 6 • HATCH_FILL – 7 • XHATCH_FILL – 8 • INTERLEAVE_FILL – 9 • WIDE_DOT_FILL – 10 • CLOSE_DOT_FILL – 11 • USER_FILL – 12 If invalid input is passed to setfillstyle, graphresult returns -1(grError), and the current fill pattern and fill color remain unchanged. The EMPTY_FILL style is like a solid fill using the current background color (which is set by setbkcolor). This function does not return any value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/* The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area. */ #include <graphics.h> // driver code int main() { // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, " "); // center and radius of circle int x_circle = 250; int y_circle = 250; int radius=100; // setting border color int border_color = WHITE; // set color and pattern setfillstyle(HATCH_FILL,RED); // x and y is a position and // radius is for radius of circle circle(x_circle,y_circle,radius); // fill the color at location // (x, y) with in border color floodfill(x_circle,y_circle,border_color); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0; }
gettime() Function in C++
the gettime() function is used to find current system time. We pass address of a structure varibale of type ( struct time ). gettime() function asks for a time object to be passed and then uses that object to get the current hour and minute etc. The gettime() function fills in the fields of the time structure pointed to by the t parameter. The current system time data is written in DOS format.
Syntax for gettime() Function in C++
#include <dos.h> struct time t; gettime(&t);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* find current system time by gettime() function code example. */ #include<stdio.h> #include<dos.h> #include<conio.h> int main() { struct date fecha; struct time hora; union REGS regs; getdate(&fecha); printf("La fecha del sistema es: %d / %d / %d\n",fecha.da_day,fecha.da_mon,fecha.da_year); regs.x.cx = 0x004c; regs.x.dx = 0x4b40; regs.h.ah = 0x86; /* 004c4b40h = 5000000 microsegundos */ int86(0x15,®s,®s); /* Interrupcion 15h suspension de sistema */ gettime(&hora); printf("la hora del sistema es: %d : %d : %d\n",hora.ti_hour,hora.ti_min,hora.ti_sec); getche(); clrscr(); return 0; }
Standard Output Stream (cout) in C++
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.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. 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. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Math Library Cosine cos() Function in C++
Compute cosine. Returns the cosine of an angle of x radians. cos() function is a library function of cmath header, it is used to find the cosine of the given number (angle), it accepts a number (x) and returns the cosine of angle x radians. In trigonometry, the cos function of a right-angled triangle is defined as the length of the adjacent side over the longest side, i.e., the hypotenuse. The cos function in C++ works precisely like the cosine function in trigonometry. The return value of the cos function is the cosine of an angle given in radian.
Syntax for Math Cosine cos() Function in C++
#include <cmath> double cos (double x); float cos (float x); long double cos (long double x); double cos (T x); // additional overloads for integral types
x
Value representing an angle expressed in radians. One radian is equivalent to 180/PI degrees. Function returns cosine of x radians. Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). This function is also overloaded in <complex> and <valarray> (see complex cos and valarray cos).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* cos() function is a library function of cmath header, it is used to find the cosine of the given number (angle), it accepts a number (x) and returns the cosine of angle x radians. */ /* find the cosine of an angle expressed in terms of radian by cos() function code example. */ #include <iostream> #include <cmath> using namespace std; int main() { double x = 0.5, result; result = cos(x); cout << "cos(x) = " << result << endl; double xDegrees = 25; // converting degrees to radians x = xDegrees*3.14159/180; result = cos(x); cout << "cos(x) = " << result << endl; return 0; }
Math Library Sine sin() Function in C++
Compute sine. Returns the sine of an angle of x radians. sin() function is a library function of cmath header, it is used to find the sine of the given number (angle), it accepts a number (x) and returns the sine of angle x radians. Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). This function is also overloaded in <complex> and <valarray> (see complex sin and valarray sin).
Syntax for Math sin() Function in C++
#include <cmath> double sin (double x); float sin (float x); long double sin (long double x); double sin (T x); // additional overloads for integral types
x
Value representing an angle expressed in radians. One radian is equivalent to 180/PI degrees. Function returns double type value that is the sine of given angle x radians.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* compute the sine of an angle of x radians by sin() math function code example. */ /* C++ sin() function returns sine of an angle given in radians. Angle is passed as an argument to sin(). */ #include <iostream> #include <cmath> using namespace std; int main() { double x = 0.439203, result; result = sin(x); cout << "sin(x) = " << result << endl; double xDegrees = 90.0; // converting degrees to radians x = xDegrees*3.14159/180; result = sin(x); cout << "sin(x) = " << result << endl; return 0; }
getch() Function in C++
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.
Syntax for getch() Function in C++
#include <conio.h> int getch(void);
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. We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc. • getch() method pauses the Output Console until a key is pressed. • It does not use any buffer to store the input character. • The entered character is immediately returned without waiting for the enter key. • The entered character does not show up on the console. • The getch() method can be used to accept hidden inputs like password, ATM pin numbers, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */ // C code to illustrate working of // getch() to accept hidden inputs #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); sum=a+b; cout<<"Sum: "<<sum; getch(); // use getch() befor end of main() }
main() Function in C++
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.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
While Loop Statement in C++
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.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }


C++ Program to check whether an undirected 'graph is tree' or not. Graph is tree if it doesn't contain cycles. A recursive function that uses visited[] & parent to detect cycle in subgraph
The first program uses temporary variable to swap numbers, whereas the second program doesn't use temporary variables. To perform 'swapping' in above example, three variables
The Fibonacci sequence is a series where the next term is the "sum of pervious two terms". The first two terms of the Fibonacci sequence is 0 followed by 1. Fibonacci Numbers: 0, 1, 1,
Insert x. Remove x (unimplemented). Return item that matches x. Return "smallest item". Return largest item. Return true if empty or else false. Print tree in sorted order. Return