Happy Codings - Programming Code Examples

C Programming Code Examples

C > Code Snippets Code Examples

Colored menu in C

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
/* Colored menu in C */ #include <conio.h> int menu(void); void setcolor(unsigned short color); main() { while(1) { /*get selection and execute the relevant statement*/ switch(menu()) { case 1: { setcolor(8); puts("You selected menu item 1\n"); puts("Finished item 1 task\n"); break; } case 2: { setcolor(11); puts("You selected menu item 2\n"); puts("Finished item 2 task\n"); break; } case 3: { setcolor(12); puts("You are quitting\n"); exit(0); break; } default: { puts("Invalid menu choice\n"); break; } } } return 0; } void setcolor(unsigned short color) { HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hcon,color); } /*menu function*/ int menu(void) { int reply; /*display menu options*/ setcolor(6); puts("Enter 1 for task 1.\n"); setcolor(9); puts("Enter 2 for task 2.\n"); setcolor(2); puts("Enter 3 to quit.\n"); /*scan for user entry*/ scanf("%d", &reply); return reply; }
puts() Function in C
Write string to stdout. Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n'). The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not). The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.
Syntax for puts() Function in C
#include <stdio.h> int puts(const char *str)
C string to be printed. On success, a non-negative value is returned. On error, the function returns EOF and sets the error indicator (ferror).
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
/* write string to stdout by puts() function example */ #include <stdio.h> #include <string.h> int main() { char name[50]; printf("Enter your name "); gets(name); int age[50]; printf("Enter your age "); gets(age); char address[50]; printf("Enter your address "); gets(address); int pincode[50]; printf("Enter your pincode "); gets(pincode); printf("Entered Name is: "); puts(name); printf("Entered age is: "); puts(age); printf("Entered address is: "); puts(address); printf("Entered pincode is: "); puts(pincode); getch(); return 0; }
Switch Case Statement in C
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
Syntax for Switch Case Statement in C
switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }
• The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
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
/* switch case statement in C language*/ // Program to create a simple calculator #include <stdio.h> int main() { char operation; double n1, n2; printf("Enter an operator (+, -, *, /): "); scanf("%c", &operation); printf("Enter two operands: "); scanf("%lf %lf",&n1, &n2); switch(operation) { case '+': printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2); break; case '-': printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2); break; case '*': printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2); break; case '/': printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2); break; // operator doesn't match any case constant +, -, *, / default: printf("Error! operator is not correct"); } return 0; }
scanf() Function in C
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Syntax for scanf() Function in C
#include <stdio.h> int scanf ( const char * format, ... );
C string that contains a sequence of characters that control how characters extracted from the stream are treated: • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread. • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. A format specifier for scanf follows this prototype: %[*][width][length]specifier
Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:
i – integer
Any number of digits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f). Signed argument.
d or u – decimal integer
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
o – octal integer
Any number of octal digits (0-7), optionally preceded by a sign (+ or -). Unsigned argument.
x – hexadecimal integer
Any number of hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). Unsigned argument.
f, e, g – floating point number
A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
c – character
The next character. If a width other than 1 is specified, the function reads exactly width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s – string of characters
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
p – pointer address
A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprintf.
[characters] – scanset
Any number of the characters specified between the brackets. A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] – negated scanset
Any number of characters none of them specified as characters between the brackets.
n – count
No input is consumed. The number of characters read so far from stdin is stored in the pointed location.
A % followed by another % matches a single %. Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.
The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:
An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
Specifies the maximum number of characters to be read in the current reading operation (optional).
One of hh, h, l, ll, j, z, t, L (optional). This alters the expected type of the storage pointed by the corresponding argument (see below).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type. There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function. These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&) (see example). On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned. If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
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
/* read formatted data from stdin by scanf() function example */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ char name[10]; int age; int result; /* Ask the user to enter their first name and age */ printf("Please enter your first name and your age.\n"); /* Read a name and age from the user */ result = scanf("%s %d",name, &age); /* We were not able to parse the two required values */ if (result < 2) { /* Display an error and exit */ printf("Either name or age was not entered\n\n"); exit(0); } /* Display the values the user entered */ printf("Name: %s\n", name); printf("Age: %d\n", age); 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 ......... }
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.
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; }
#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; }
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; }
exit() Function in C
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.
Syntax for exit() Function in C
#include <stdlib.h> void exit(int status)
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. The exit function does not return anything. • We must include the stdlib.h header file while using the exit () function. • It is used to terminate the normal execution of the program while encountered the exit () function. • The exit () function calls the registered atexit() function in the reverse order of their registration. • We can use the exit() function to flush or clean all open stream data like read or write with unwritten buffered data. • It closed all opened files linked with a parent or another function or file and can remove all files created by the tmpfile function. • The program's behaviour is undefined if the user calls the exit function more than one time or calls the exit and quick_exit function. • The exit function is categorized into two parts: exit(0) and exit(1).
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
/* call all functions registered with atexit and terminates the program by exit() function example */ #include <stdio.h> #include <stdlib.h> int main () { // declaration of the variables int i, num; printf ( " Enter the last number: "); scanf ( " %d", &num); for ( i = 1; i<num; i++) { // use if statement to check the condition if ( i == 6 ) /* use exit () statement with passing 0 argument to show termination of the program without any error message. */ exit(0); else printf (" \n Number is %d", i); } 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; }
SetConsoleTextAttribute() Function in C
Sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function changes the dos text colors. Its like as if you went to the DOS properties and change the colors manually. But this function lets you set the text attributes for the program so you don't have to tell the player/user of it to change the colors.
Syntax for SetConsoleTextAttribute() Function in C
BOOL WINAPI SetConsoleTextAttribute(_In_ HANDLE hConsoleOutput , _In_ WORD wAttributes);
SetConsoleTextAttribute is the Windows API method to set output text colors using different parameters. This function sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole functions. The full description of the character attributes can be seen on this page.
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
/* set the attributes of characters written to the console screen by SetConsoleTextAttribute() function code example */ #include<stdio.h> #include<conio.h> #include<windowS.h> int main() { printf("\n\n\t\tTheSmolt-Learn for Free\n\n\n"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN); printf("This is Green Background!"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE|BACKGROUND_RED| BACKGROUND_INTENSITY); printf("\n\n This is Magenta?"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_INTENSITY|BACKGROUND_RED); printf("\n\n This color is Red color)\n"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN|BACKGROUND_INTENSITY); printf("\n\nThis is mix of two color"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE|BACKGROUND_GREEN); printf("\n\nCombination of Green & Blue"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE|BACKGROUND_RED|BACKGROUND_GREEN); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE|BACKGROUND_GREEN| BACKGROUND_INTENSITY); getch(); return 0; }

Take a string and a character as input. Store it in the array "str[]" & variable key respectively. Using for loop search for the variable key. If it is found then increment the variable count. If
In this program, we are doing the same thing that we have done in the above program, but here we're using functions in order to find the Quotient & Remainder. We have created two