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 > Miscellaneous Code Examples

C Program to Illustrate how User Authentication is Done

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
/* C Program to Illustrate how User Authentication is Done This C program asks for the user name & password and displays the same to illustrate user authentication. - Take the user name & password as input. - Print the each character of password as * while receiving it. - Now print the original password and exit. */ #include <stdio.h> void main() { char password[20], username[20], ch; int j; printf("Enter User name: "); gets(username); printf("Enter the password < any 8 characters>: "); for (j = 0; j < 8; j++) { ch = getchar(); password[j] = ch; ch = '*' ; printf("%c", ch); } password[j] = '\0'; /* Original password can be printed, if needed */ printf("\n Your password is :"); for (j = 0; j < 8; j++) { printf("%c", password[j]); } }
getchar() Function in C
Get character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. A getchar() function is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single input from the user. In other words, it is the C library function that gets a single character (unsigned char) from the stdin. However, the getchar() function is similar to the getc() function, but there is a small difference between the getchar() and getc() function of the C programming language. A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream.
Syntax for getchar() Function in C
#include <stdio.h> int getchar ( void );
On success, the character read is returned (promoted to an int value). The return type is int to accommodate for the special value EOF, which indicates failure: If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* gets a single character (unsigned char) from the stdin by getchar() function example */ #include <stdio.h> #include <ctype.h> int main() { int ch, i = 0; char str[150]; printf (" Enter the characters from the keyboard (Press Enter button to stop).\n"); // use do while loop to define the condition do { ch = getchar(); // takes character, number, etc from the user str[i] = ch; // store the ch into str[i] i++; // increment loop by 1 } while (ch != '\n'); // ch is not equal to '\n' printf("Entered characters are %s ", str); 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; }
gets() Function in C
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows). The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax for gets() Function in C
#include<stdio.h> char * gets ( char * str );
Pointer to a block of memory (array of char) where the string read is copied as a C string. On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* read characters from the standard input (stdin) and stores them as a C string */ #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { clrscr(); FILE *fp; char fname[20]; printf("Enter filename : "); gets(fname); fp=fopen(fname, "r"); if(fp==NULL) { printf("Error in opening the file..!!\n"); printf("Press any key to exit..\n"); getch(); exit(1); } fclose(fp); getch(); }
#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; }
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; }
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, ... );
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:
a conversion format specifier.
d or i
Signed decimal integer
Unsigned decimal integer
Unsigned octal
Unsigned hexadecimal integer
Unsigned hexadecimal integer (uppercase)
Decimal floating point, lowercase
Decimal floating point, uppercase
Scientific notation (mantissa/exponent), lowercase
Scientific notation (mantissa/exponent), uppercase
Use the shortest representation: %e or %f
Use the shortest representation: %E or %F
Hexadecimal floating point, lowercase
Hexadecimal floating point, uppercase
String of characters
Pointer address
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:
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.
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.
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
an optional * or integer value used to specify minimum width field.
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.
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
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.
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; }

The formula used to find the surface area and volume of the cube is surface_area = 6 * (a*a) and volume = a*a*a. Library Function is used in header file to compute Math Functions. We
C program print all prime numbers between 1 to n. Input upper & lower limit to print prime. Find Prime numbers between 1 to n. Assume that the current number is Prime and check if
C program to compare two strings using loop character by character. Logic to compare two strings. Input two strings from user and Store it in some variable say str1 and str2. Compare
Add a node to the linked list. Preform merge sort on the linked list. Merge the lists. Insert some numbers into the linked list. Sort the list. Print the list. Free the list. Add a node to