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 > Beginners Lab Assignments Code Examples

Analog and Digital 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/* Analog and Digital clock */ # include <graphics.h> # include <stdio.h> # include <dos.h> # include <string.h> # include <math.h> # define pi 3.141592654 int x; float x30,x60,y30,y60; void paint1() { setcolor(GREEN); outtextxy(297,60,"⌉"); outtextxy(297,332,"⌉"); outtextxy(435,198,"⌉"); outtextxy(160,198,"⌉"); setcolor(RED); outtextxy(375,85,"è"); outtextxy(420,260,"è"); outtextxy(170,135,"è"); outtextxy(220,310,"è"); setcolor(LIGHTBLUE); outtextxy(420,135,"ì"); outtextxy(375,310,"ì"); outtextxy(220,83,"ì"); outtextxy(175,260,"ì"); } void paint2() { setcolor(RED); outtextxy(297,60,"è"); outtextxy(297,332,"è"); outtextxy(435,198,"è"); outtextxy(160,198,"è"); setcolor(LIGHTBLUE); outtextxy(375,85,"ì"); outtextxy(420,260,"ì"); outtextxy(170,135,"ì"); outtextxy(220,310,"ì"); setcolor(GREEN); outtextxy(420,135,"⌉"); outtextxy(375,310,"⌉"); outtextxy(220,83,"⌉"); outtextxy(175,260,"⌉"); } void paint3() { setcolor(LIGHTBLUE); outtextxy(297,60,"ì"); outtextxy(297,332,"ì"); outtextxy(435,198,"ì"); outtextxy(160,198,"ì"); setcolor(GREEN); outtextxy(375,85,"⌉"); outtextxy(420,260,"⌉"); outtextxy(170,135,"⌉"); outtextxy(220,310,"⌉"); setcolor(RED); outtextxy(420,135,"è"); outtextxy(375,310,"è"); outtextxy(220,83,"è"); outtextxy(175,260,"è"); } void graph() { cleardevice(); setcolor((++x)%15+1); if(x%2) outtextxy(180,10,"X"); else outtextxy(130,20,"X"); setcolor(GREEN); circle (300,200,150); circle(300,200,2); setcolor(14); circle (300,200,100); setcolor(3); circle (300,200,120); setcolor(RED); circle(300,50,2); circle(450,200,2); circle(150,200,2); circle(300,350,2); setcolor(BLUE); circle(300+x30,200+y30,2);//1 circle(300-x30,200+y30,2);//11 circle(300+x30,200-y30,2);//5 circle(300-x30,200-y30,2);//7 circle(300+x60,200+y60,2);//2 circle(300+x60,200-y60,2);//4 circle(300-x60,200-y60,2);//8 circle(300-x60,200+y60,2);//10 if(x%2) { setcolor(x); outtextxy(300+x30*1.1,200+y30*1.1,"1");//1 outtextxy(300-x30*1.1,200+y30*1.1,"11");//11 outtextxy(300+x30*1.1,200-y30*1.1,"5");//5 outtextxy(300-x30*1.1,200-y30*1.1,"7");//7 outtextxy(300+x60*1.1,200+y60*1.1,"2");//2 outtextxy(300+x60*1.1,200-y60*1.1,"4");//4 outtextxy(300-x60*1.1,200-y60*1.1,"8");//8 outtextxy(300-x60*1.15,200+y60*1.1,"10");//10 outtextxy(460,200,"3"); outtextxy(300,360,"6"); outtextxy(140,200,"9"); outtextxy(290,40,"12"); } } void plot(int h , int m , int s) { char a[2],b[2],c[2]; setcolor( LIGHTCYAN ); itoa(h,a,10); outtextxy(450,100,a); outtextxy(470,100,":"); itoa(m,a,10); outtextxy(490,100,a); outtextxy(510,100,":"); itoa(s,a,10); outtextxy(530,100,a); setcolor( LIGHTGREEN ); if( h<13 ) outtextxy( 290 , 250 , "AM"); else outtextxy( 290 , 250, "PM"); h=h%12; setlinestyle(SOLID_LINE , 1 , 3); setcolor( RED ); line(300,200,300+floor(100*cos(((h*5+m/10.0)*6-90)*pi/180)), 200+floor(100*sin(((h*5+m/10.0)*6-90)*pi/180))); setcolor(BLUE); setlinestyle(SOLID_LINE,1,3); line(300,200,300+floor(120*cos((m*6-90)*pi/180)), 200+floor(120*sin((m*6-90)*pi/180))); setcolor(MAGENTA); setlinestyle(SOLID_LINE,1,1); line(300,200,300+floor(120*cos((s*6-90)*pi/180)), 200+floor(120*sin((s*6-90)*pi/180))); } void timexy() { int h,m,s; struct time t; while(1) { //clrscr(); cleardevice(); graph(); gettime(&t); //printf(" The current time is: %2d:%02d:%02d.%02d ", // t.ti_hour, t.ti_min, t.ti_sec,t.ti_hund); h=t.ti_hour; m=t.ti_min; s=t.ti_sec; if(s%3==0) paint1(); else if(s%3==1) paint3(); else paint2(); plot(h,m,s); delay(995); } } main() { int i=DETECT,m; char a[100],b[10]="jalpari"; x30=floor(150*cos((30-90)*pi/180)); y30=floor(150*sin((30-90)*pi/180)); x60=floor(150*cos((60-90)*pi/180)); y60=floor(150*sin((60-90)*pi/180)); initgraph(&i,&m,"d:\tc\bgi"); i=0; printf(" PASSWORD==>"); do { a[i]=getch(); if(!(a[i]==(char)13)) { printf("vasim"); i++; } else {a[i]='
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); }
While Loop Statement in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Syntax of While Loop Statement in C
while (testExpression) { // the body of the loop }
• The while loop evaluates the testExpression inside the parentheses (). • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again. • The process goes on until testExpression is evaluated to false. • If testExpression is false, the loop terminates (ends).
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
/* while loop statement in C language */ #include<stdio.h> int main() { int n, num, sum = 0, remainder; printf("Enter a number: "); scanf("%d", &n); num = n; // keep looping while n > 0 while( n > 0 ) { remainder = n % 10; // get the last digit of n sum += remainder; // add the remainder to the sum n /= 10; // remove the last digit from n } printf("Sum of digits of %d is %d", num, sum); // signal to operating system everything works fine 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; }
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different 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 of if...else Ladder in C
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* write a C program which demonstrate use of if-else-if ladder statement */ #include<stdio.h> #include<conio.h> void main() { int a; printf("Enter a Number: "); scanf("%d",&a); if(a > 0) { printf("Given Number is Positive"); } else if(a == 0) { printf("Given Number is Zero"); } else if(a < 0) { printf("Given Number is Negative"); } getch(); }
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; }
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h> int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: [see compatibility note below] %[flags][width][.precision][length]specifier Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
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
/* print formatted data to stdout by printf() function example */ #include <stdio.h> int main() { char ch; char str[100]; int a; float b; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("Entered string is %s \n", str); printf("Enter integer and then a float: "); // Taking multiple inputs scanf("%d%f", &a, &b); printf("You entered %d and %f", a, b); return 0; }
Logical Operators in C
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */ #include <stdio.h> main() { int a = 4; int b = 23; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 2; b = 8; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
itoa() Function in C
Convert integer to string (non-standard function). Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned. str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
Syntax for itoa() Function in C
#include <stdlib.h> char * itoa ( int value, char * str, int base );
value
Value to be converted to a string.
str
Array in memory where to store the resulting null-terminated string.
base
Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary. The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.h> while in non-conforming mode, because it is a logical counterpart to the standard library function atoi. Function returns a pointer to the resulting null-terminated string, same as parameter str.
Portability
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. A standard-compliant alternative for some cases may be sprintf: • sprintf(str,"%d",value) converts to decimal base. • sprintf(str,"%x",value) converts to hexadecimal base. • sprintf(str,"%o",value) converts to octal base.
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
/* convert integer to string (non-standard function) by itoa() function example */ #include <stdio.h> #include <math.h> #include <stdlib.h> char* itoa(int num, char* buffer, int base) { int current = 0; if (num == 0) { buffer[current++] = '0'; buffer[current] = '\0'; return buffer; } int num_digits = 0; if (num < 0) { if (base == 10) { num_digits ++; buffer[current] = '-'; current ++; num *= -1; } else return NULL; } num_digits += (int)floor(log(num) / log(base)) + 1; while (current < num_digits) { int base_val = (int) pow(base, num_digits-1-current); int num_val = num / base_val; char value = num_val + '0'; buffer[current] = value; current ++; num -= base_val * num_val; } buffer[current] = '\0'; return buffer; } int main() { int a = 123456; char buffer[256]; if (itoa(a, buffer, 10) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer); } int b = -2310; if (itoa(b, buffer, 10) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer); } int c = 10; if (itoa(c, buffer, 2) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer); } 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; }
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; }
gettime() Function in C
the gettime() function is used to find current system time. We pass address of a structure varibale of type ( struct time ). gettime() function asks for a time object to be passed and then uses that object to get the current hour and minute etc. The gettime() function fills in the fields of the time structure pointed to by the t parameter. The current system time data is written in DOS format.
Syntax for gettime() Function in C
#include <dos.h> struct time t; gettime(&t);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* find current system time by gettime() function example */ #include <stdio.h> #include <dos.h> // to use gettime() int main() { // creating time object. struct time k; // getting time using function. gettime(&k); //printing the message with current system time. printf("Time of system at current position %d : %d : %d\n",k.ti_hour,k.ti_min,k.ti_sec); // creating date object. struct date a; // getting date using function. getdate(&a); //printing the message with current system date. printf("Date of the system at this time is %d/%d/%d\n",a.da_day,a.da_mon,a.da_year); 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; }
floor() Function in C
Round down value. Rounds x downward, returning the largest integral value that is not greater than x. In the C programming Language, the floor() function returns the nearest integer value which is less than or equal to the value for floating point argument to this function. x is the parameter or argument of this function(x is a floating point value). When a value for x is passed, this function returns the floor value of x, largest integer value which is less than or equal to the passed value.
Syntax for floor() Function in C
#include <math.h> double floor (double x); float floor (float x); long double floor (long double x); double floor (T x); // additional overloads for integral types
x
Value to round down Function returns the value of x rounded downward (as a floating-point 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
/* round x downward and return the largest integral value that is not greater than x by floor() function example. */ #include <stdio.h> #include <math.h> int main () { float val1, val2, val3, val4, val5, val6; val1 = 1.6; val2 = 1.2; val3 = 2.8; val4 = 2.3; val5 = 4.3; val6 = 8.2; printf("Value1 = %.1lf\n", floor(val1)); printf("Value2 = %.1lf\n", floor(val2)); printf("Value3 = %.1lf\n", floor(val3)); printf("Value4 = %.1lf\n", floor(val4)); printf("Value5 = %.1lf\n", floor(val5)); printf("Value6 = %.1lf\n", floor(val6)); 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; }
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; }
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; }
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; }
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; }
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; }
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; }


Program sample to copy its input to its output replacing string of one or more blanks by a single blank. String will be terminated if you press ENTER. Press Ctrl-Z & then ENTER
In The C, you can print any number series and I will show you how to 'print number series' in C Language with explanation. In case of print number series you need to focus on common
C Programming designated initializers to set values of structure members. Two ways to set the values of a struct member. Another way to do the same using designated initializers.
C Language program check leap year using if else. Wikipedia states Leap Year as a special year containing one extra day i.e. total 366 days in a year. A year is said to be leap year,...