Happy Codings - Programming Code Examples

C Programming Code Examples

C > Games and Graphics Code Examples

Analogue Clock

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
/* Analogue Clock */ #include<graphics.h> #include<time.h> #include<math.h> #include<dos.h> #include<stdio.h> #define PI 3.14569 void sounder(); void bibin(); void main() { int gd=DETECT,gm; time_t start, finish, now; struct tm *ptr; char *c, buf1[80],h[3],m[3],s[3]; double duration; int i=0,j,k,x,y,xm,ym,xh,yh; /* Record the time the program starts execution. */ initgraph(&gd,&gm,"e:\tc\bgi"); clrscr(); setfillstyle(SOLID_FILL,BLUE); bar3d(170,100,470,400,10,1); setcolor(GREEN); circle(320,250,100);//for outercircle inner radius circle(320,250,125);//for outercircle outer radius circle(320,250,1);//for innercircle inner radius circle(320,250,7);//for innercircle outer radius setfillstyle(SOLID_FILL,RED); //for outercircle filling red color floodfill(430,250,GREEN);//filling outercircle with green border floodfill(320,250,GREEN); setfillstyle(SOLID_FILL,MAGENTA); //for innercircle filling mangenta floodfill(325,250,GREEN); //filling innercilling with green border settextstyle(1,0,1); setcolor(15); outtextxy(318,352,"6"); outtextxy(376,334,"5"); outtextxy(410,294,"4"); outtextxy(430,237,"3"); outtextxy(417,186,"2"); outtextxy(376,144,"1"); outtextxy(310,127,"12"); outtextxy(254,140,"11"); outtextxy(213,182,"10"); outtextxy(206,237,"9"); outtextxy(221,301,"8"); outtextxy(261,338,"7"); /* Record the current time, using the alternate method of */ /* calling time(). */ time(&now); /* Convert the time_t value into a type tm structure. */ ptr = localtime(&now); /* Create and display a formatted string containing */ /* the current time. */ c = asctime(ptr); h[0]=c[11]; h[1]=c[12]; m[0]=c[14]; m[1]=c[15]; s[0]=c[17]; s[1]=c[18]; i=atoi(h); if(i>11) i=i-12; j=atoi(m); xm=320+80*(sin(PI/30*j)); ym=250-80*(cos(PI/30*j)); xh=320+60*sin(PI/6*i+PI/360*j); yh=250-60*cos(PI/6*i+PI/360*j); setlinestyle(SOLID_LINE,1,3); setcolor(BROWN); line(320,250,xm,ym); setcolor(MAGENTA); line(320,250,xh,yh); setbkcolor(GREEN); sounder(); getch(); bibin(); closegraph(); restorecrtmode(); } void sounder() { int frequency; for(frequency=4000;frequency<5000;frequency++) sound(frequency); nosound(); return; } void bibin() { int midx=320,midy=230; cleardevice(); delay(4000); return ; }
Math sin() Function in C
Compute sine. Returns the sine of an angle of x radians. The C sin Function is a C Math Library Function, used to calculate the Trigonometry Sine value for the specified expression.
Syntax for sin() Function in C
#include <math.h> 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. This function returns the sine of the radian angle x. The sin function accepts an angle in radians and gives its sine value, which can be confirmed using a sine curve.
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
/* compute the sine of an angle of x radians by sin() function example. */ #include<stdio.h> #include<math.h> #define PI 3.1415926 int main() { double x ; x = 45; //calculation of sine printf("\nsin( %.3lf ) = %.3lf\n", x, sin( (x * PI) / 180 )); x = 90; //calculation of sine printf("\nsin( %.3lf ) = %.3lf\n", x, sin( (x * PI) / 180 )); x = 120; //calculation of sine printf("\nsin( %.3lf ) = %.3lf\n", x, sin( (x * PI) / 180 )); return 0; }
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 30 31 32 33
/* draw a circle with center at (x, y) and given radius by circle() function example. */ // C Implementation for drawing circle #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, ""); // circle function circle(250, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); 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. Note: The EMPTY_FILL style is like a solid fill using the current background color (which is set by setbkcolor).
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
/* set the current fill pattern and fill color by setfillstyle() function example */ #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT, gm,bkcolor; initgraph(&gd,&gm," "); setfillstyle(EMPTY_FILL,YELLOW); bar3d(2,150,100,200,25,1); setfillstyle(SOLID_FILL,RED); bar3d(150,150,250,200,25,1); setfillstyle(LINE_FILL,BLUE); bar3d(300,150,400,200,25,1); setfillstyle(LTSLASH_FILL,GREEN); bar3d(450,150,550,200,25,1); setfillstyle(SLASH_FILL,CYAN); bar3d(2,250,100,300,25,1); setfillstyle(BKSLASH_FILL,BROWN); bar3d(150,250,250,300,25,1); setfillstyle(LTBKSLASH_FILL,MAGENTA); bar3d(300,250,400,300,25,1); setfillstyle(HATCH_FILL,LIGHTRED); bar3d(450,250,550,300,25,1); setfillstyle(XHATCH_FILL,DARKGRAY); bar3d(2,350,100,400,25,1); setfillstyle(INTERLEAVE_FILL,YELLOW); bar3d(150,350,250,400,25,1); setfillstyle(WIDE_DOT_FILL,LIGHTMAGENTA); bar3d(300,350,400,400,25,1); setfillstyle(CLOSE_DOT_FILL,LIGHTGRAY); bar3d(450,350,550,400,25,1); getch(); closegraph(); }
initgraph() Function in C
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. Normally, initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem), then loading the appropriate .BGI file from disk. As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file.
Syntax for initgraph() Function in C
#include <graphics.h> void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
pathtodriver
pathtodriver specifies the directory path where initgraph looks for graphics drivers. initgraph first looks in the path specified in pathtodriver, then (if they are not there) in the current directory. Accordingly, if pathtodriver is null, the driver files (*.BGI) must be in the current directory. This is also the path settextstyle searches for the stroked character font files (*.CHR).
graphdriver
graphdriver is an integer that specifies the graphics driver to be used. You can give it a value using a constant of the graphics_drivers enumeration type, which is defined in graphics.h and listed below. • DETECT – 0 (requests autodetect) • CGA – 1 • MCGA – 2 • EGA – 3 • EGA64 – 4 • EGAMONO – 5 • IBM8514 – 6 • HERCMONO – 7 • ATT400 – 8 • VGA – 9 • PC3270 – 10
graphmode
graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT; in which case, *graphmode is set by initgraph to the highest resolution available for the detected driver). You can give *graphmode a value using a constant of the graphics_modes enumeration type, which is defined in graphics.h and listed below. 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 27 28 29 30 31 32 33 34 35
/* initgraph initializes the graphics system by loading a graphics driver by initgraph() function example*/ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; }
restorecrtmode() Function in C
restorecrtmode restores the original video mode detected by initgraph. This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes. Textmode should not be used for this purpose; use it only when the screen is in text mode, to change to a different text mode.
Syntax for restorecrtmode() Function in C
#include <graphics.h> void restorecrtmode(void);
restorecrtmode() restores the original screen mode that existed prior to calling initgraph(). Most often, this represents the text mode. restorecrtmode() and setgraphmode() can be alternately called to switch between text and graphics mode. Function returns nothing.
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
/* restore the original video mode detected by initgraph by restorecrtmode() function example. */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request auto detection */ int gd = DETECT, gmode, err; int midx, midy; /* initialize graphics and local variables */ initgraph(&gd, &gmode, "C:/TURBOC3/BGI"); /* read result of initialization */ err = graphresult(); if (err != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(err)); getch(); return 0; } /* mid position in x and y-axis */ midx = getmaxx() / 2; midy = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy - 100, "GRAPHICS MODE"); /* draw a rectange at the given position */ rectangle(midx - 50, midy - 50, midx + 50, midy + 50); getch(); /* restore system to text mode */ restorecrtmode(); printf("Restored system to text mode"); getch(); /* return to graphics mode */ setgraphmode(getgraphmode()); /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy - 100, "BACK TO GRAPHIC MODE!!"); /* draws a rectangle at the given postion */ rectangle(midx - 50, midy - 50, midx + 50, midy + 50); /* clean up */ getch(); closegraph(); return 0; }
#define Directive in C
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/ // Or #define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators. In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution. The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code. This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables. The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions. The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error. The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
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
/* #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. */ #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "XCoder"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); 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. Here are the two types of file that can be included using #include: • 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); 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 *textstring);
x
x-coordinate of the point
y
y-coordinate of the point
textstring
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 28 29 30 31 32 33 34
/* display the text or string at a specified point (x, y) on the screen by outtextxy() function example */ // C Implementation for outtextxy() #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, ""); // outtextxy function outtextxy(200, 150, "Hello, Have a good day !"); 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 34 35 36 37 38 39 40
/* nested loop statement in C language */ // C Program to print all prime factors // of a number using nested loop #include <math.h> #include <stdio.h> // A function to print all prime factors of a given number n void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { printf("%d ", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf("%d ", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf("%d ", n); } /* Driver program to test above function */ int main() { int n = 315; primeFactors(n); return 0; }
time() Function in C
The time() function is defined in time.h header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
Syntax for time() Function in C
#include <time.h> time_t time( time_t *second )
second
This function accepts single parameter second. This parameter is used to set the time_t object which store the time. This function returns current calender time as a object of type time_t. It is used to get current system time as structure. time() function is a useful utility function that we can use to measure the elapsed time of our program.
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
/* return the time since 00:00:00 UTC, January 1, 1970 by time() function example */ #include <time.h> #include <stdlib.h> #include <stdio.h> int main(void) { time_t current_time; char* c_time_string; /* Obtain current time. */ current_time = time(NULL); if (current_time == ((time_t)-1)) { (void) fprintf(stderr, "Failure to obtain the current time.\n"); exit(EXIT_FAILURE); } /* Convert to local time format. */ c_time_string = ctime(¤t_time); if (c_time_string == NULL) { (void) fprintf(stderr, "Failure to convert the current time.\n"); exit(EXIT_FAILURE); } /* Print to stdout. ctime() has already added a terminating newline character. */ (void) printf("Current time is %s", c_time_string); exit(EXIT_SUCCESS); }
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. 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.
Syntax for floodfill() Function in C
#include <graphics.h> void floodfill(int x, int y, int border);
x
X coordinate of point on the screen
y
Y coordinate of point on the screen
border
specifies the color of border of the enclosed area. 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 If an error occurs while flooding a region, graphresult returns a value of -7.
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
/* fill an enclosed area on bitmap devices by floodfill() 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, " "); // 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; }
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.
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 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* deallocate all memory allocated by the graphics system by closegraph() function example */ // C Implementation for closegraph() #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, ""); // outtext function displays // text at current position. outtext("Press any key to close" " the graphics mode !!"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
nosound() Function in C
The nosound() function in C language is used to stop the sound played by sound() function. nosound() function is simply silent the system. Sound function produces the sound of a specified frequency and nosound function turn off the PC speaker.
Syntax for nosound() Function in C
#include <dos.h> void nosound();
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
/* silent the system by nosound() function example */ #include <stdio.h> //to use 'sound()', 'delay()' functions #include <dos.h> int main() { //calling the function for producing //the sound of frequency 400. sound(400); //function to delay the sound for //half of second. delay(500); //calling the function for producing //the sound of frequency 250. sound(250); //function to delay the sound for //half of second. delay(500); //calling the function to stop the //system sound. nosound(); return 0; }
localtime() Function in C
Convert time_t to tm as local time. Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone. The localtime() function returns a pointer to the broken-down form of time in the form of a tm structure. The time is represented in local time. The time pointer is usually obtained through a call to time(). The structure used by localtime() to hold the broken-down time is statically allocated and is overwritten each time the function is called. If you wish to save the contents of the structure, you must copy it elsewhere.
Syntax for localtime() Function in C
#include <time.h> struct tm * localtime (const time_t * timer);
timer
Pointer to an object of type time_t that contains a time value. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time. Function returns a pointer to a tm structure with its members filled with the values that correspond to the local time representation of timer. The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime. Following is the tm structure information:
struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ };
Data races
The function accesses the object pointed by timer. The function also accesses and modifies a shared internal object, which may introduce data races on concurrent calls to gmtime and localtime. Some libraries provide an alternative function that avoids this data race: localtime_r (non-portable).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* convert a time value to a broken-down local time by localtime() function example */ #include<time.h> #include<stdio.h> #include<conio.h> /* Print local and UTC time. */ void main() { clrscr(); struct tm *local; time_t t; t = time(NULL); local = localtime(&t); printf("Local time and date: %s\n", asctime(local)); local = gmtime(&t); printf("UTC time and date: %s\n", asctime(local)); getch(); }
Math cos() Function in C
Compute cosine. Returns the cosine of an angle of x radians. The C cos Function is a C Math Library Function, used to calculate the Trigonometry Cosine value for the specified expression.
Syntax for cos() Function in C
#include <math.h> 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. This function returns cosine of x radians. The value returned by cos() is always in the range: -1 to 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* compute the cosine of an angle of x radians by cos() function example. */ #include <stdio.h> #include <math.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ double value; double result; /* Assign the value we will find the cos of */ value = 0.5; /* Calculate the Cosine of value */ result = cos(value); /* Display the result of the calculation */ printf("The Cosine of %f is %f\n", value, result); return 0; }
line() Function in C
line() is a library function of graphics.c in c programming language which is used to draw a line from two coordinates. line() function 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.
Syntax for line() Function in C
#include <graphics.h> 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. This is a predefined function named line which is used to draw a line on the output screen. It takes 4 arguments, first two parameters represent an initial point and the last two arguments are for the final points of the line.
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
/* draw a line from a point(x1,y1) to point(x2,y2) by line() function example */ /*C graphics program to draw a line.*/ #include <graphics.h> #include <conio.h> main() { int gd = DETECT, gm; //init graphics initgraph(&gd, &gm, "C:/TURBOC3/BGI"); /* if you are using turboc2 use below line to init graphics: initgraph(&gd, &gm, "C:/TC/BGI"); */ //draw a line /* line() function description parameter left to right x1: 100 y1: 100 x2: 200 y2: 100 */ line(100,100,200,100); //will draw a horizontal line line(10,10,200,10); //will draw another horizonatl line getch(); closegraph(); 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
#include <graphics.h> void setcolor(int color);
Each color is assigned a number. 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 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.
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
/* set the current drawing color to color, which can range from 0 to getmaxcolor by setcolor() function example */ // C Implementation for setcolor() #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, ""); // Draws circle in white color // center at (100, 100) and radius // as 50 circle(100, 100, 50); // setcolor function setcolor(GREEN); // Draws circle in green color // center at (200, 200) and radius // as 50 circle(200, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
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. In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
For Loop Statement in C
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
Syntax of For Loop Statement in C
for (initialization; condition test; increment or decrement) { //Statements to be executed repeatedly }
Step 1
First initialization happens and the counter variable gets initialized.
Step 2
In the second step the condition is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed, if the condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3
After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* for loop statement in C language */ // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }
sound() Function in C
Our system can create various sounds on different frequencies. The sound() is very useful as it can create very nice music with the help of programming and our user can enjoy music during working in out the program. Sound function produces the sound of a specified frequency. Used for adding music to a C program, try to use some random values in loop, vary delay and enjoy.
Syntax for sound() Function in C
#include <dos.h> void sound(unsigned frequency);
The delay() function has been used in this function to delay for the next sound. The Second thing is the nosound() function, which simply silent the system. These two functions are from file dos.h, which should be included in the program.
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
/* produce the sound of a specified frequency by sound() function example */ #include <stdio.h> //to use 'sound()', 'delay()' functions #include <dos.h> int main() { //calling the function for producing //the sound of frequency 400. sound(400); //function to delay the sound for //half of second. delay(500); //the sound of frequency 200. sound(200); //the sound of frequency 500. sound(500); //calling the function to stop the //system sound. nosound(); return 0; }
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.
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. • 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
/* set the style for all lines drawn by line, lineto, rectangle, drawpoly by setlinestyle() function example */ // 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; }
cleardevice() Function in C
The header file graphics.h contains cleardevice() function. cleardevice() is a function which is used to clear the screen by filling the whole screen with the current background color. It means that cleardevice() function is used to clear the whole screen with the current background color and it also sets the current position to (0,0). . Both clrscr() and cleardevice() functions are used to clear the screen but clrscr() is used in text mode and cleardevice function is used in the graphics mode.
Syntax for cleardevice() Function in C
#include <graphics.h> void cleardevice();
Clearing the screen is always an issue for developers, because now and then we want to show the user some useful or important data, which should be highlighted or at least have user's attention. It is important to note that, after clearing the device, we will lose all our drawing, shapes or images. It is useful but be little cautious.
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
/* clear the screen in graphics mode and set the current position to (0,0) by cleardevice() function example.*/ #include <graphics.h> #include <conio.h> int main() { //initilizing graphic driver and //graphic mode variable int graphicdriver=DETECT,graphicmode; //calling initgraph initgraph(&graphicdriver,&graphicmode,"c:\\turboc3\\bgi"); //Printing message for user outtextxy(20, 20 + 20, "Program to use graph default in C graphics"); //message to clear screen outtextxy(20, 50 + 30, "Press any key to clear screen"); //getting character and clear the device screen getch(); cleardevice(); //message to press key to get exit from program outtextxy(20, 20 + 20, "Press any key to exit..."); getch(); return 0; }
ctime() Function in C
Convert time_t value to string. Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year. The string is followed by a new-line character ('\n') and terminated with a null-character. This function is equivalent to: asctime(localtime(timer)) The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy, where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. The ctime() function is define in the time.h header file. The ctime() function returns the string representing the localtime based on the argument timer.
Syntax for ctime() Function in C
#include <time.h> char *ctime(const time_t *timer)
timer
Pointer to an object of type time_t that contains a time value. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time. A C-string containing the date and time information in a human-readable format. The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime.
Www
Day of week
Mmm
Month name
dd
Day of month
hh
Hour digit
mm
Minute digit
ss
Second digit
yyyy
Year digit
Data races
The function accesses the object pointed by timer. The function also accesses and modifies a shared internal buffer, which may cause data races on concurrent calls to asctime or ctime. Some libraries provide an alternative function that avoids this data race: ctime_r (non-portable).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* get the string representing the localtime based on the argument timer by ctime() function example */ #include <stdio.h> /* printf */ #include <time.h> /* time_t, time, ctime */ int main () { time_t rawtime; time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); return 0; }
atoi() Function in C
Convert string to integer. Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int. The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
Syntax for atoi() Function in C
#include <stdlib.h> int atoi (const char * str);
str
C-string beginning with the representation of an integral number. The atoi() function converts a string of characters representing a numeral into a number of int. Similarly, atol() returns a long integer, and in C99, the atoll() function converts a string into an integer of type long long. The conversion ignores any leading whitespace characters (spaces, tabs, newlines). A leading plus sign is permissible; a minus sign makes the return value negative. Any character that cannot be interpreted as part of an integer, such as a decimal point or exponent sign, has the effect of terminating the numeral input, so that atoi() converts only the partial string to the left of that character. If under these conditions the string still does not appear to represent a numeral, then atoi() returns 0. On success, the function returns the converted integral number as an int value. If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.
Data races
The array pointed by str is accessed.
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
/* convert string to integer by atoi() function example */ #include <stdio.h> // Iterative function to implement `atoi()` function in C long atoi(const char* S) { long num = 0; int i = 0; // run till the end of the string is reached, or the // current character is non-numeric while (S[i] && (S[i] >= '0' && S[i] <= '9')) { num = num * 10 + (S[i] - '0'); i++; } return num; } // Implement `atoi()` function in C int main(void) { char S[] = "12345"; printf("%ld ", atoi(S)); return 0; }
clrscr() Function in C
Function clrscr() clears the screen and moves the cursor to the upper left-hand corner of the screen. If you are using the GCC compiler, use system function to execute the clear/cls command. clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
Syntax to Clear the Console in C
#include<conio.h> clrscr(); OR system("cls"); OR system("clear");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* clear the screen and moves the cursor to the upper left-hand corner of the screen by clrscr() function example. */ #include <stdio.h> // clrscr() function definition void clrscr(void) { system("clear"); } int main() { clrscr(); //clear output screen printf("Hello World!!!"); //print message 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 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
/* wait for any character input from keyboard by getch() function example. */ // C code to illustrate working of // getch() to accept hidden inputs #include <conio.h> #include <dos.h> // delay() #include <stdio.h> #include <string.h> void main() { // Taking the password of 8 characters char pwd[9]; int i; // To clear the screen clrscr(); printf("Enter Password: "); for (i = 0; i < 8; i++) { // Get the hidden input // using getch() method pwd[i] = getch(); // Print * to show that // a character is entered printf("*"); } pwd[i] = '\0'; printf("\n"); // Now the hidden input is stored in pwd[] // So any operation can be done on it // Here we are just printing printf("Entered password: "); for (i = 0; pwd[i] != '\0'; i++) printf("%c", pwd[i]); // Now the console will wait // for a key to be pressed getch(); }
delay() Function in C
Delay function is used to suspend execution of a program for a particular time. delay() function requires a parameter which should be a number, defining the milliseconds for the delay. To use delay function in your program you should include the "dos.h" header file which is not a part of standard C library. Here unsigned int is the number of milliseconds (remember 1 second = 1000 milliseconds).
Syntax for delay() Function in C
#include<stdio.h> void delay(unsigned int);
sleep() function requires a parameter which should be a number, defining the seconds to sleep. These functions are pretty useful when you want to show the user multiple outputs, for a given period of time. The nice thing about this is that we can also make alarm and reminder for the user in our program. Hence, these two functions are pretty handy, if you are planning to make a real-world application.
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
/* suspend execution of a program for a particular time by delay() function example */ #include <stdio.h> //to use 'delay()' #include <dos.h> int main() { // message for user printf("After printing this message the program will get end in next 5 seconds \n"); // delay the process for 5 seconds as it takes integer value in milliseconds. delay(5000); // message for user. printf("After printing this message the program will get delay for next 15 seconds\n"); // to terminate the process for next 15 seconds. sleep(15); // message for user printf("After printing this message the program will get end in next 2 seconds \n"); // delay the process for 2 seconds as it takes integer value in milliseconds. delay(2000); return 0; }
asctime() Function in C
Convert tm structure to string. Interprets the contents of the tm structure pointed by timeptr as a calendar time and converts it to a C-string containing a human-readable version of the corresponding date and time. Converts a date and time structure to string form. The single argument of the asctime() function is a pointer to a structure of type struct tm, in which a date and time is represented by elements for the year, month, day, hour, and so on. The asctime() function returns a pointer to a string of 26 bytes containing the date and time in a timestamp format. The day of the week and the month are abbreviated with the first three letters of their English names, with no period. If the day of the month is a single digit, an additional space fills the place of its tens digit. If the hour is less than ten, it is represented with a leading zero.
Syntax for asctime() Function in C
#include <time.h> char* asctime (const struct tm * timeptr);
timeptr
Pointer to a tm structure that contains a calendar time broken down into its components (see struct tm). The timeptr is a pointer to tm structure that contains a calendar time broken down into its components as shown below
struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ };
Function returns a C-string containing the date and time information in a human-readable format. The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year. • Www: represents the day in three letter abbreviated (Mon, Tue, Wed.., ) • Mmm: represents the month in three letter abbreviated (Jan, Feb, Mar.., ) • dd: represents the date in two digits (01, 02, 10, 21, 31.., ) • hh: represents the hour (11, 12, 13, 22..., ) • mm: represents the minutes (10, 11, 12, 45..., ) • ss: represents the seconds (10, 20, 30..., ) • yyyy: represents the year in four digits (2000, 2001, 2019, 2020..., ) The string is followed by a new-line character ('\n') and terminated with a null-character.
Data races
The function accesses the object pointed by timeptr. The function also accesses and modifies a shared internal buffer, which may cause data races on concurrent calls to asctime or ctime. Some libraries provide an alternative function that avoids this data race: asctime_r (non-portable).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* convert tm structure to string by asctime() function code example */ #include <stdio.h> #include <time.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ time_t current_time; struct tm *local_time; /* Retrieve the current time */ current_time = time(NULL); /* Get the local time using the current time */ local_time = localtime(¤t_time); /* Display the local time */ printf("The time at www is: %s", asctime(local_time)); return 0; }
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.
Syntax for setbkcolor() Function in C
#include <graphics.h> void setbkcolor(int color);
possible color values
• 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 On CGA and EGA systems, setbkcolor changes the background color by changing the first entry in the palette. If you use an EGA or a VGA, and you change the palette colors with setpalette or setallpalette, the defined symbolic constants might not give you the correct color. This is because the parameter to setbkcolor indicates the entry number in the current palette rather than a specific color (unless the parameter passed is 0, which always sets the background color to black).
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
/* set the background to the color specified by color by setbkcolor() function example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* _select driver and mode that supports multiple background colors*/ int gdriver = EGA, gmode = EGAHI, errorcode; int bkcol, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (bkcol=0; bkcol<=maxcolor; bkcol++) { /* clear the screen */ cleardevice(); /* select a new background color */ setbkcolor(bkcol); /* output a messsage */ if (bkcol == WHITE) setcolor(EGA_BLUE); sprintf(msg, "Background color: %d", bkcol); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; }
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 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
/* set the text font, the direction in which text is displayed, and the size of the characters by settextstyle() function example. */ // C++ implementation for // settextstyle() function #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, ""); // location of text int x = 150; int y = 150; // font style int font = 8; // font direction int direction = 0; // font size int font_size = 5; // for setting text style settextstyle(font, direction, font_size); // for printing text in graphics window outtextxy(x, y, "Happy Codings"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by graphics // system . closegraph(); return 0; }
bar3d() Function in C
bar3d draws a three-dimensional rectangular bar, then fills it using the current fill pattern and fill color. The three-dimensional outline of the bar is drawn in the current line style and color. The bar's depth in pixels is given by depth. The topflag parameter governs whether a three-dimensional top is put on the bar. If topflag is nonzero, a top is put on; otherwise, no top is put on the bar (making it possible to stack several bars on top of one another). The upper left and lower right corners of the rectangle are given by (left, top) and (right, bottom), respectively.
Syntax for bar3d() Function in C
#include<graphics.h> void bar3d(int left, int top, int right, int bottom, int depth, int topflag);
left
specifies the X-coordinate of top left corner
top
specifies the Y-coordinate of top left corner
right
specifies the X-coordinate of right bottom corner
bottom
specifies the Y-coordinate of right bottom corner
depth
specifies the depth of bar in pixels
topflag
determines whether a 3 dimensional top is put on the bar or not ( if it's non-zero then it's put otherwise not ). bar3d function is used to draw a 2-dimensional, rectangular filled in bar. Coordinates of left top and right bottom corner of bar are required to draw the bar. Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle. 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 52 53 54 55 56 57 58 59
/* draw a 2-dimensional, rectangular filled in bar by bar3d() graphic 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, ""); // location of sides int left, top, right, bottom; // depth of the bar int depth; // top flag denotes top line. int topflag; // left, top, right, bottom, // depth, topflag location's bar3d(left = 150, top = 250, right = 190, bottom = 350, depth = 20, topflag = 1); bar3d(left = 220, top = 150, right = 260, bottom = 350, depth = 20, topflag = 0); bar3d(left = 290, top = 200, right = 330, bottom = 350, depth = 20, topflag = 1); // y axis line line(100, 50, 100, 350); // x axis line line(100, 350, 400, 350); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }


Percent means per cent (hundreds), a ratio of the parts out of 100. The symbol of percent is %. We count 'Percentage of Marks Obtained', return on investment and Percentage can go
C program to 'input any string' from user and find the 'first occurrence' of a given character in the string. Input string from user and store it in a variable say "str". Run a loop from start
C Code example of Infinite While Loop. Since the value of the variable var is same (there is no ++ or -- operator used on variable, inside the body of loop) the condition var<=2 will be
C Compare two binary files, printing the first byte position where they differ. Compare two binary files character by character. Character by character comparision. If equal, continue
Take a decimal number as input. Check if the number is greater than 1000 or 900 or 500 or 400 or 100 or 90 or 50 or 40 or 10 or 9 or 5 or 4 or 1. If it is, then store its equivalent roman...
'Scalene Triangle' does not have sides having Equal Length & No angles of Scalene Triangle are equal. To calculate Area, we need at least two sides and the angle included by them. So
The 'smallest element' is exchanged with the first element of the unsorted list of elements. The "second smallest element" is Exchanged with the 'second element' of the unsorted list