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

A simple rotation of an ellipse by different angle values.

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
/* A simple rotation of an ellipse by different angle values. Atomic model by 2-D transformation */ //#include "winbgim.h" #include <graphics.h> #include <math.h> void Translation(int X,int Y,int Tx,int Ty,int *Xp,int *Yp) { *Xp=X+Tx; *Yp=Y+Ty; } void Scaling(int X,int Y,float Sx,float Sy,int R,int P,int *Xp,int *Yp) { *Xp=(int)(Sx*(X-R)+0.5)+R; *Yp=(int)(Sy*(Y-P)+0.5)+P; } void Rotation(int X,int Y,float S,float C,int R,int P,int *Xp,int *Yp) { int Xx,Yy; Xx=X-R; Yy=Y-P; *Xp=(int)(Xx*C-Yy*S+0.5)+R; *Yp=(int)(Xx*S+Yy*C+0.5)+P; } int main(){ int X[361],Y[361],Xp,Yp,I,J,K,Tx,Ty; float T,C,S,Pi; initwindow(450,450); int i, x, y, color,MaxColors; //srand( seed ); /* Restart random # function */ MaxColors=getmaxcolor()-1; for( i=0 ; i<1500 ; ++i ){ /* Put 5000 pixels on screen */ x = 1 + random( 450 - 1 ); /* Generate a random location */ y = 1 + random( 450 - 1 ); color = random( MaxColors ); putpixel( x, y, color ); } Pi=4*atan(1); for(J=0;J<=360;J++) { T=J*Pi/180; S=sin(T); C=cos(T) ; X[J]=(int)(200.0+150.0*C+0.5); Y[J]=(int)(180.0+100.0*S+0.5); //setcolor(4); setfillstyle(12,1); fillellipse(92,80,4,4); fillellipse(324,200,4,4); } for(J=0;J<9;J++) { setcolor(6+J); T=J*45*Pi/180; S=sin(T); C=cos(T); for(I=0;I<=360;I++) { Rotation(X[I],Y[I],S,C,200,180,&Xp,&Yp); if(I==0) moveto(Xp,Yp); else lineto(Xp,Yp); } setfillstyle(12,1); fillellipse(192,82,4,4); fillellipse(200,281,4,4); } //setfillstyle(13,2); fillellipse(200,180,10,10); getch(); closegraph(); return 0; }
Math Library Tangent tan() Function in C++
Compute tangent. Returns the tangent of an angle of x radians. tan() function is a library function of cmath header, it is used to find the tangent of the given number (angle), it accepts a number (x) and returns the tangent of angle x radians. In trigonometry, the tangent function of a right-angled triangle is the ratio between the adjacent and opposite sides of a right triangle. The tan function in C++ works precisely like the tangent in trigonometry. The return value of the tan function is the tangent of an angle given in radian.
Syntax for Math Tangent tan() Function in C++
#include <cmath> double tan (double x); float tan (float x); long double tan (long double x); double tan (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 tangent 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 tan and valarray tan).
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
/* tan() function is a library function of cmath header, it is used to find the tangent of the given number (angle), it accepts a number (x) and returns the tangent of angle x radians.*/ /* find the tangent of an angle specified in terms of radian by math tan() function code example. */ #include <iostream> #include <cmath> using namespace std; int main() { long double x = 0.99999, result; result = tan(x); cout << "tan(x) = " << result << endl; double xDegrees = 60.0; // converting degree to radians and using tan() fucntion result = tan(xDegrees*3.14159/180); cout << "tan(x) = " << result << endl; return 0; }
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; }
#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; }
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; }
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; }
lineto() Function in C++
Function lineto() draws a line from the current position (CP) to the point (x, y), you can get current position using getx and gety function. Where, (x, y) are the coordinates upto which the line will be drawn from previous point.
Syntax for lineto() Function in C++
#include<graphics.h> lineto(int x, int y);
x
X coordinate of the point
y
Y coordinate of the point Use getx() and gety() to get the current position.
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
/* lineto() function draws a line from current position to the point(x, y). */ /* draws a line by lineto() function 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(); }
putpixel() Function in C++
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.
Syntax for putpixel() Function in C++
#include <graphics.h> void putpixel(int x, int y, int color);
x
X coordinate of the point
y
Y coordinate of the point
color
specifies the color of the pixel To use these function in your program, we would need to include graphics.h file in your program. You should also use getch() function to make the screen freeze.
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
/* putpixel() function writes a pixel to the specified position in the bitmap, using the current drawing mode and the bitmap's clipping rectangle. */ /* plot a point in the color defined by color at (x,y) by putpixel() function code example. */ #include <graphics.h> #include <stdio.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, color; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // putpixel function putpixel(85, 35, GREEN); putpixel(30, 40, RED); putpixel(115, 50, YELLOW); putpixel(135, 50, CYAN); putpixel(45, 60, BLUE); putpixel(20, 100, WHITE); putpixel(200, 100, LIGHTBLUE); putpixel(150, 100, LIGHTGREEN); putpixel(200, 50, YELLOW); putpixel(120, 70, RED); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
getmaxcolor() Function in C++
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 ) .
Syntax for getmaxcolor() Function in C++
#include<graphics.h> int getmaxcolor();
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: • 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/* The getmaxcolor() function returns the largest valid color value for the current video mode. For example, for 4-color CGA mode, this number would be 3. (Color values for this mode range from 0 to 3.) */ /* return maximum color value by getmaxcolor() function code example */ #include <graphics.h> #include <stdio.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; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for "String print". // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Maximum number of colors for " "current graphics mode and " "driver = %d", getmaxcolor() + 1); // outtext function displays text // at current position. outtextxy(20, 100, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
Nested Loop Statement in C++
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C++
Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
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
/* nested loop statement in C++ language */ // C++ program that uses nested for loop to print a 2D matrix #include <bits/stdc++.h> using namespace std; #define ROW 3 #define COL 3 // Driver program int main() { int i, j; // Declare the matrix int matrix[ROW][COL] = { { 4, 8, 12 }, { 16, 20, 24 }, { 28, 32, 36 } }; cout << "Given matrix is \n"; // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) cout << matrix[i][j]; cout << "\n"; } 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() }
fillellipse() Function in C++
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.
Syntax for fillellipse() Function in C++
#include <graphics.h> void fillellipse(int x, int y, int xradius, int yradius);
x
x coordinate of center of the ellipse
y
y coordinate of center of the ellipse
xradius
horizontal axes of the ellipse
yradius
vertical axes of the ellipse 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
/* fillellipse() function draws an ellipse and fill it with current drawing color and pattern. */ /* draws an ellipse and fill it by fillellipse() function code example */ #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, ""); // fillellipse fuction fillellipse(200, 200, 50, 90); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
srand() Function in C++
Initialize random number generator. The pseudo-random number generator is initialized using the argument passed as seed. The C++ <cstdlib> srand() function seeds the pseudo-random number generator used by rand() function. If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand. Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand. If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand. In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
Syntax for srand() Function in C++
#include<cstdlib> void srand (unsigned int seed);
seed
An integer value to be used as seed by the pseudo-random number generator algorithm. This function does not return any value.
Data races
The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand. Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: rand_r (non-portable). C++ library implementations are allowed to guarantee no data races for calling this function.
Exceptions
No-throw guarantee: this function never throws exceptions.
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
/* srand() function is an inbuilt function in C++ STL, which is defined in <cstdlib> header file. srand() is used to initialise random number generators. This function gives a starting point for producing the pseudo-random integer series. The argument is passed as a seed for generating a pseudo-random number. Whenever a different seed value is used in srand the pseudo number generator can be expected to generate different series of results the same as rand(). */ /* Initialize random number generator by srand() function code example */ #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main (){ int rand_num; //initialize random seed srand (time(NULL)); //generating 20 random number between 1 and 100 cout<<"Random numbers in [1, 100]:\n"; for(int i = 0; i < 20; i++) { rand_num = rand() % 100 + 1; cout<<rand_num<<" "; } return 0; }
closegraph() Function in C++
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.
Syntax for closegraph() Function in C++
#include <graphics.h> void closegraph();
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
/* 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 by closegraph function code example. */ #include <graphics.h> int main() { int gdrive, gmode; char *drvpath = "c:\\bc\\bgi"; detectgraph(&gdrive, &gmode); initgraph(&gdrive, &gmode, drvpath); setbkcolor(0); setcolor(2); cleardevice(); MyOwnFan(320, 230, 0); getch(); closegraph(); return 0; }
For Loop Statement in C++
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.
Syntax of For Loop Statement in C++
for (initialization; condition; update) { // body of-loop }
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition. A new range-based for loop was introduced to work with collections such as arrays and vectors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* For Loop Statement in C++ Language */ // C++ program to find the sum of first n natural numbers // positive integers such as 1,2,3,...n are known as natural numbers #include <iostream> using namespace std; int main() { int num, sum; sum = 0; cout << "Enter a positive integer: "; cin >> num; for (int i = 1; i <= num; ++i) { sum += i; } cout << "Sum = " << sum << 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; }
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; }
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(); }
moveto() Function in C++
Function moves the current position(cp) to (x,y). The header file graphics.h contains moveto() function which changes the current position to (x, y). Means if you want to move a point from the current position to a new position then you can use this function. outtext is the function used to display the given string on graphics mode. It uses the font style set by settextstyle and the current position. The current position can be changed with moveto function. Alternatively you can use outtextxy function which takes xpos, ypos and string for displaying at a particular location. outtextxy does the work of both moveto and outtext functions.
Syntax for moveto() Function in C++
#include <graphics.h> void moveto(int x, int y);
x
X coordinate of the point
y
Y coordinate of the point moveto() function moves the current position to the x, y position relative to the current viewport.
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
/* First thing is to initiate a graph. Then set the current position to a location by using the function moveto(). moveto() function takes up the x and y co-ordinate which define the location.*/ /* set the current position to a location by moveto() function code example. */ #include <graphics.h> #include <conio.h> void main() { int d,m; d = DETECT; char msg[80]; initgraph(&d, &m, "d:\\tc\\bgi"); //move the C.P. to location (50, 80) moveto(50, 80); // plot a pixel putpixel(getx(), gety(), getmaxcolor()); //output a message at (50, 80) sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(50, 80, msg); /* move to (200, 100) */ moveto(200, 100); // plot a pixel putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at C.P. */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); getch(); closegraph(); }
Math Arc Tangent atan() Function in C++
Compute arc tangent. Function returns the principal value of the arc tangent of x, expressed in radians. In trigonometrics, arc tangent is the inverse operation of tangent. Notice that because of the sign ambiguity, the function cannot determine with certainty in which quadrant the angle falls only by its tangent value. See atan2 for an alternative that takes a fractional argument instead.
Syntax for Arc Tangent atan() Function in C++
#include <cmath> double atan (double x); float atan (float x); long double atan (long double x); double atan (T x); // additional overloads for integral types
x
Value whose arc tangent is computed. Function returns principal arc tangent of x, in the interval [-pi/2,+pi/2] radians. One radian is equivalent to 180/PI degrees. The atan() function returns the inverse tangent of a number. To be more specific, it returns the inverse tangent of a number in radians. atan() function is used to find the arc tangent of a number means gives a tangent value to this function it will return the angle in radians corresponding to that value. arc tangent is the inverse operation of tangent. This function accepts all the real numbers and atan() function returns the values in the range of [-?/2, ?/2]. Function atan() takes a single argument as a double and returns the value in 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 atan and valarray atan).
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
/* The atan() function in C++ returns the inverse tangent of a number (argument) in radians. */ /* compute the inverse tangent of a number given in radian by atan() function code example. */ #include <iostream> #include <cmath> using namespace std; // main() section int main() { float x; x = -1.0; cout<<"atan("<<x<<"): "<<atan(x)<<endl; x = -0.89; cout<<"atan("<<x<<"): "<<atan(x)<<endl; x = 0.65; cout<<"atan("<<x<<"): "<<atan(x)<<endl; x = 1; cout<<"atan("<<x<<"): "<<atan(x)<<endl; return 0; }


Make the "Tree Logically" empty, insert data and get "height of node". Function to max of left/right node, insert data recursively. Rotate binary tree node with left child. Rotate binary
C++ Program perform LU Decomposition of a matrix. LU decomposition factors a matrix as the product of a Lower Triangular Matrix and an upper 'triangular matrix'. Code sometimes
We already known that if reverse of a number is equal to the same number, it is Palindrome number. Remember it: certain variables and a loop use to get the reverse of a number which
This C++ Program checks whether a directed graph is weakly connected or not. We can do "DFS" V times starting from every vertex. If any DFS, doesn't visit all vertices, then graph