C Language Programes
C Language Programes
C Language Programes
This page contains examples on basic concepts of C programming like: loops, functions, pointers, structures etc. All the examples in this page are tested and verified on GNU GCC compiler, although almost every program on in this website will work on any compiler you use. Feel free to copy the source code and execute it in your device. C Programming Examples and Source Code
1) C Program to Print a Sentence 2) C Program to Print a Integer Entered by a User 3) C Program to Add Two Integers 4) C Program to Multiply two Floating Point Numbers 5) C Program to Find ASCII Value of a Character 6) C Program to Find Quotient and Remainder of Two Integers Entered by User 7) C Program to Find Size of int, float, double and char of Your System 8) C Program to Demonstrate the Working of Keyword long 9) C Program to Swap Two Numbers 10) C Program to Check Whether a Number is Even or Odd 11) C Program to Check Vowel or Consonant 12) C Program to Find the Largest Number Among Three Numbers 13) C program to Find all Roots of a Quadratic equation 14) C Program to Check Leap Year 15) C Program to Check Whether a Number is Positive or Negative or Zero. 16) C Program to Check Whether a Character is an Alphabet or not 17) C Program to Calculate Sum of Natural Numbers 18) C Program to Find Factorial of a Number 19) C program to Generate Multiplication Table 20) C Program to Display Fibonacci Series 21) C Program to Find HCF of two Numbers
22) C Program to Find LCM of two Numbers 23) C Program to Count Number of Digits of an Integer 24) C Program to Reverse a Number 25) C program to Calculate the Power of a Number 26) C Program to Check Whether a Number is Palindrome or Not 27) C Program to Check Whether a Number is Prime or Not 28) C Program to Display Prime Numbers Between Two Intervals 29) C program to Check Armstrong Number 30) C Program to Display Armstrong Number Between Two Intervals 31) C program to Display Factors of a Number 32) C program to Print Pyramids and Triangles in C programming using Loops 33) C program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case 34) C Program to Display Prime Numbers Between Intervals by Making Function 35) C Program to Check Prime and Armstrong Number by Making Function 36) C program to Check Whether a Number can be Express as Sum of Two Prime Numbers 37) C program to Find Sum of Natural Numbers using Recursion. 38) C program to Calculate Factorial of a Number Using Recursion 39) C Program to Find H.C.F Using Recursion 40) C program to Reverse a Sentence Using Recusrion 41) C program to Calculate the Power of a Number Using Recursion 42) C Program to Convert Binary Number to Decimal and Decimal to Binary 43) C Program to Convert Octal Number to Decimal and Decimal to Octal 44) C Program to Convert Binary Number to Octal and Octal to Binary 45) C Program to Calculate Average Using Arrays
46) C Program to Find Largest Element of an Array 47) C Program to Calculate Standard Deviation 48) C Program to Add Two Matrix Using Multi-dimensional Arryas 49) C Program to Multiply to Matrix Using Multi-dimensional Arrays 50) C Program to Find Transpose of a Matrix 51) C Program to Multiply two Matrices by Passing Matrix to Function 52) C Program to Sort Elements of an Array 53) C Program to Access Elements of an Array Using Pointer 54) C Program Swap Numbers in Cyclic Order Using Call by Reference 55) C Program to Find Largest Number Using Dynamic Memory Allocation 56) C Program to Find the Frequency of Characters in a String 57) C Program to Find the Number of Vowels, Consonants, Digits and White space in a String 58) C Program to Remove all Characters in a String Except Alphabet 59) C Program to Reverse a String by Passing it to Function 60) C Program to Find the Length of a String 61) C program to Concatenate Two Strings 62) C Program to Copy a String 63) C Program to Sort Elements in Lexicographical Order (Dictionary Order) 64) C Program to Change Decimal to Hexadecimal Number and Vice Versa 65) C Program to Convert Hexadecimal to Octal and Vice Versa 66) C Program to Convert Binary Number to Hexadecimal Vice Versa 67) C Program to Store Information(name, roll and marks) of a Student Using Structure 68) C Program to Add Two Distances (in inch-feet) System Using Structures 69) C Program to Add Two Complex Numbers by Passing Structure to a Function
70) C Program to Calculate Difference Between Two Time Period 71) C Program to Store Information of 10 Students Using Structure 72) C Program to Store Information Using Structures for n Elements Dynamically 73) C Program to Write to a Sentence to a File 74) C Program to Read a String of Text from File 75) C Program to Display its own Source Code as Output
Keywords:
Keywords are the reserved words used in programming. Each keywords has fixed meaning and that cannot be changed by user. For example:
int money;
Here, int is a keyword that indicates, 'money' is of type integer. As, C programming is case sensitive, all keywords must be written in lowercase. Here is the list of all keywords predefined by ASCII C. Keywords in C Language auto double int struct break else long switch case enum register typedef char extern return union continue for signed void do if static while default goto sizeof volatile const float short unsigned Besides these keywords, there are some additional keywords supported by Turbo C. Additional Keywords for Borland C asm far interrupt pascal near huge cdecl All these keywords, their syntax and application will be discussed in their respective topics. However, if you want brief information about these keywords without going further visit page: list of all C keywords.
Identifiers
In C programming, identifiers are names given to C entities, such as variables, functions, structures etc. Identifier are created to give unique name to C entities to identify it during the execution of program. For example: int money; int mango_tree; Here, money is a identifier which denotes a variable of type integer. Similarly, mango_tree is another identifier, which denotes another variable of type integer. Rules for writing identifier 1. An identifier can be composed of letters (both uppercase and lowercase letters), digits and underscore '_' only. 2. The first letter of identifier should be either a letter or an underscore. But, it is discouraged to start an identifier name with an underscore though it is legal. It is because, identifier that starts with underscore can conflict with system names. In such cases, compiler will complain about it. Some system names that start with underscore are _fileno, _iob, _wfopen etc.
3. There is no rule for the length of an identifier. However, the first 31 characters of an identifier are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be different. Tips for Good Programming Practice : Programmer can choose the name of identifier whatever they want. However, if the programmer choose meaningful name for an identifier, it will be easy to understand and work on, particularly in case of large program.
Constants
Constants are the terms that can't be changed during the execution of a program. For example: 1, 2.5, "Programming is easy." etc. In C, constants can be classified as:
Integer constants
Integer constants are the numeric constants(constant associated with number) without any fractional part or exponential part. There are three types of integer constants in C language: decimal constant(base 10), octal constant(base 8) and hexadecimal constant(base 16) .
Decimal digits: 0 1 2 3 4 5 6 7 8 9 Octal digits: 0 1 2 3 4 5 6 7 Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F. For example: Decimal constants: 0, -9, 22 etc Octal constants: 021, 077, 033 etc Hexadecimal constants: 0x7f, 0x2a, 0x521 etc Notes: 1. You can use small caps a, b, c, d, e, f instead of uppercase letters while writing a hexadecimal constant. 2. Every octal constant starts with 0 and hexadecimal constant starts with 0x in C programming.
Floating-point constants
Floating point constants are the numeric constants that has either fractional form or exponent form. For example: -2.0 0.0000234 -0.22E-5 Note:Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.
Character constants
Character constants are the constant which use single quotation around characters. For example: 'a', 'l', 'm', 'F' etc.
Escape Sequences
Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program which either cannot be typed or has special meaning in C programming. In such cases, escape sequence are used. For example: \n is used for newline. The backslash( \ ) causes "escape" from the normal way the characters are interpreted by the compiler. Escape Sequences Escape Sequences Character \b Backspace \f Form feed \n Newline \r Return \t Horizontal tab \v Vertical tab \\ Backslash \' Single quotation mark
Escape Sequences Escape Sequences Character \" Double quotation mark \? Question mark \0 Null character
String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For example: "good" //string constant "" //null string constant " " //string constant of six white space "x" //string constant having single character. "Earth is round\n" //prints string with newline
Enumeration constants
Keyword enum is used to declare enumeration types. For example: enum color {yellow, green, black, white}; Here, the variable name is color and yellow, green, black and white are the enumeration constants having value 0, 1, 2 and 3 respectively by default. For more information about enumeration, visit page: Enumeration Types.
Data types in C
1. Fundamental Data Types Integer types Floating Type Character types 2. Derived Data Types Arrays
Here, var1 is a variable of type integer. The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of 4 byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2, 231-1 Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1. If you try to store larger number than 231-1, i.e,+2147483647 and smaller number than -231, i.e, -2147483648, program will not run correctly.
Floating types
Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc. Keywords either float or double is used for declaring floating type variable. For example: float var2; double var3; Here, both var2 and var3 are floating type variables. In C, floating values can be represented in exponential form as well. For example: float var3=22.442e2
Character types
Keyword char is used for declaring the variable of character type. For example: char var4='h';
The size of char is 1 byte. The character data type consists of ASCII characters. Each character is given a specific value. For example: For, 'a', value =97 For, 'b', value=98 For, 'A', value=65 For, '&', value=33 For, '2', value=49 Here is the list of all ASCII characters in C language.
Qualifiers
Qualifiers alters the meaning of base data types to yield a new data type. Size qualifiers: Size qualifiers alters the size of basic data type. The keywords long and short are two size qualifiers. For example: long int i;
The size of int is either 2 bytes or 4 bytes but, when long keyword is used, that variable will be either 4 bytes of 8 bytes. Learn more about long keyword in C programming. If the larger size of variable is not needed then, short keyword can be used in similar manner as long keyword. Sign qualifiers: Whether a variable can hold only positive value or both values is specified by sign qualifiers. Keywords signed and unsigned are used for sign qualifiers. unsigned int a; // unsigned variable can hold zero and positive values only It is not necessary to define variable using keyword signed because, a variable is signed by default. Sign qualifiers can be applied to only int and char data types. For a int variable of size 4 bytes it can hold data from -231 to 231-1 but, if that variable is defined unsigned, it can hold data from 0 to 232 -1. Constant qualifiers Constant qualifiers can be declared with keyword const. An object declared by const cannot be modified. const int p=20; The value of p cannot be changed in the program.
Volatile qualifiers: A variable should be declared volatile whenever its value can be changed by some external sources outside program. Keyword volatile is used to indicate volatile variable.
I/O of integers in C
#include<stdio.h>
int main() { int c=5; printf()("Number=%d",c); return 0; } Output Number=5 Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this conversion format string matches with remaining argument,i.e, c in this case, value of c is displayed.
#include<stdio.h>
int main() { int c; printf()("Enter a number\n"); scanf()("%d",&c); printf()("Number=%d",c); return 0; } Output Enter a number 4 Number=4 The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and value is stored in that address.
I/O of floats in C
#include <stdio.h> int main(){ float a; printf("Enter value: "); scanf("%f",&a); printf("Value=%f",a); //%f is used for floats instead of %d return 0; }
Output Enter value: 23.45 Value=23.450000 Conversion format string "%f" is used for floats to take input and to display floating value of a variable.
ASCII code
When character is typed in the above program, the character itself is not recorded a numeric value(ASCII value) is stored. And when we displayed that value by using "%c", that character is displayed. #include <stdio.h> int main(){ char var1; printf("Enter character: "); scanf("%c",&var1); printf("You entered %c.\n",var1); /* \n prints the next line(performs work of enter). */ printf("ASCII value of %d",var1); return 0; } Output Enter character: g 103 When, 'g' is entered, ASCII value 103 is stored instead of g. You can display character if you know ASCII code only. This is shown by following example. #include <stdio.h> int main(){ int var1=69; printf("Character of ASCII value 69: %c",var1); return 0; } Output Character of ASCII value 69: E The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122. Click here to learn about complete reference of ASCII code.
C Programming Operators
Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition.
C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as: Operators in C programming Arithmetic Operators Increment and Decrement Operators Assignment Operators Relational Operators Logical Operators Conditional Operators Bitwise Operators Special Operators
Arithmetic Operators
Operator + * / % Meaning of Operator addition or unary plus subtraction or unary minus multiplication division remainder after division( modulo division)
/* Program to demonstrate the working of arithmetic operators in C. */ #include <stdio.h> int main(){ int a=9,b=4,c; c=a+b; printf("a+b=%d\n",c); c=a-b; printf("a-b=%d\n",c); c=a*b; printf("a*b=%d\n",c); c=a/b; printf("a/b=%d\n",c); c=a%b;
Suppose a=5.0, b=2.0, c=5 and d=2 In C programming, a/b=2.5 a/d=2.5 c/b=2.5 c/d=2
Note: % operator can only be used with integers.
Let a=5 and b=10 a++; //a becomes a--; //a becomes ++a; //a becomes --a; //a becomes
6 5 6 5
Difference between ++ and -- operator as postfix and prefix When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:
#include <stdio.h> int main(){ int c=2,d=2; printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3. printf("%d",++c); //this statement increments 1 to c then, only c is displayed. return 0; }
Output
2 4
Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to the left side. For example:
Relational Operator
Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0. Relational operators are used in decision making and loops in C programming. Operator == > < != >= <= Meaning of Operator Equal to Greater than Less than Not equal to Greater than or equal to Less than or equal to Example 5==3 returns false (0) 5>3 returns true (1) 5<3 returns false (0) 5!=3 returns true(1) 5>=3 returns true (1) 5<=3 return false (0)
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators: Operator Meaning of Operator Logial AND Logical OR Logical NOT Example If c=5 and d=2 then,((c==5) && (d>5)) returns false. If c=5 and d=2 then, ((c==5) || (d>5)) returns true. If c=5 then, !(c==5) returns false.
&& || !
Explanation For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming. Operators & | ^ ~ << >> Meaning of operators Bitwise AND Bitwise OR Bitwise exclusive OR Bitwise complement Shift left Shift right
Bitwise operator is advance topic in programming . Learn more about bitwise operator in C programming.
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
#include <stdio.h> int main(){ int a; float b; double c; char d; printf("Size of int=%d bytes\n",sizeof(a)); printf("Size of float=%d bytes\n",sizeof(b)); printf("Size of double=%d bytes\n",sizeof(c)); printf("Size of char=%d byte\n",sizeof(d)); return 0;
}
Output
of of of of
Example of conditional operator #include <stdio.h> int main(){ char feb; int days; printf("Enter l if the year is leap year otherwise enter 0: "); scanf("%c",&feb); days=(feb=='l')?29:28; /*If test condition (feb=='l') is true, days will be equal to 29. */ /*If test condition (feb=='l') is false, days will be equal to 28. */
Enter l if the year is leap year otherwise enter n: l Number of days in February = 29
Other operators such as &(reference operator), *(dereference operator) and ->(member selection) operator will be discussed in pointer chapter.
(a>b+c&&d) This expression is equivalent to: ((a>(b+c))&&d) i.e, (b+c) executes first then, (a>(b+c)) executes then, (a>(b+c))&&d) executes
Associativity of operators
Associativity indicates in which order two operators of same precedence(priority) executes. Let us suppose an expression:
a==b!=c
Here, operators == and != have same precedence. The associativity of both == and != is left to right, i.e, the expression in left is executed first and execution take pale towards right. Thus, a==b!=c equivalent to :
(a==b)!=c
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
Operator () [] -> . ! ~ + ++
Summary of C operators with precedence and associativity Meaning of operator Associativity Functional call Array element reference Indirect member selection Direct member selection Logical negation Bitwise(1 's) complement Unary plus Unary minus Increment Left to right
Right to left
Operator -& * sizeof (type) * / % + << >> < <= > >= == != & ^ | && || ?: = *= /= %= -= &= ^= |= <<= >>=
Summary of C operators with precedence and associativity Meaning of operator Associativity Decrement Dereference Operator(Address) Pointer reference Returns the size of an object Type cast(conversion) Multiply Divide Remainder Binary plus(Addition) Binary minus(subtraction) Left shift Right shift Less than Less than or equal Greater than Greater than or equal Equal to Not equal to Bitwise AND Bitwise exclusive OR Bitwise OR Logical AND Logical OR Conditional Operator Simple assignment Assign product Assign quotient Assign remainder Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift Separator of expressions
Left to right
Left to right Left Left Left Left Left Left to to to to to to right right right right right right
Right to left
Left to right
C Introduction Examples
C Programming Introduction Examples
C Programming Introduction Examples C Program to Print a Sentence C Program to Print a Integer Entered by a User C Program to Add Two Integers Entered by User C Program to Multiply two Floating Point Numbers C Program to Find ASCII Value of Character Entered by User C Program to Find Quotient and Remainder of Two Integers Entered by User C Program to Find Size of int, float, double and char of Your System C Program to Demonstrate the Working of Keyword long C Program to Swap Two numbers Entered by User
C Programming
Explanation Every C program starts executing code from main( ) function. Inside main( ), there is a printf( ) function which prints the content inside the quotation mark which is "C Programming" in this case. Learn more about output in C programming language.
Explanation In this program, a variable num is declared of type integer using keyword int. Then, printf() function prints the content inside quotation mark which is "Enter a integer: ". Then, the scanf() takes integer value from user and stores it in variable num. Finally, the value entered by user is displayed in the screen using printf(). Learn more about how printf() and scanf() works in C programming.
Source Code
/*C programming source code to add and display the sum of two integers entered by user */ #include <stdio.h> int main( ) { int num1, num2, sum; printf("Enter two integers: "); scanf("%d %d",&num1,&num2); /* Stores the two integer entered by user in variable num1 and num2 */ sum=num1+num2; /* Performs addition and stores it in variable sum */ printf("Sum: %d",sum); /* Displays sum */ return 0;
}
Output
There are three variables used for performing this task but, you can perform this same task using 2 variables only. It can done by assiging the sum of num1 and num2 to one of these variables as shown in figure below.
/* C programming source code to add and display the sum of two integers entered by user using two variables only. */ #include <stdio.h> int main( ) { int num1, num2, sum; printf("Enter a two integers: "); scanf("%d %d",&num1,&num2); num1=num1+num2; /* Adds variables num1 and num2 and stores it in num1 */ printf("Sum: %d",num1); /* Displays value of num1 */ return 0;
}
This source code calculates the sum of two integers and displays it but, this program uses only two variables.
Source Code
/*C program to multiply and display the product of two floating point numbers entered by user. */ #include <stdio.h> int main( ) { float num1, num2, product; printf("Enter two numbers: "); scanf("%f %f",&num1,&num2); /* Stores the two floating point numbers entered by user in variable num1 and num2 respectively */ product=num1*num2; /* Performs multiplication and stores it */ printf("Product: %f",product); return 0;
}
Output
Source Code
/* Source code to find ASCII value of a character entered by user */ #include <stdio.h> int main(){ char c; printf("Enter a character: "); scanf("%c",&c); /* Takes a character from user */ printf("ASCII value of %c = %d",c,c); return 0;
}
Output
In this program, user is asked to enter a character and this character will be stored in variable c, i.e., the ASCII value of that character is stored in variable c. When, this value is displayed using conversion format string %c, the actual variable is displayed but, when this variable is displayed using format string %d, the ASCII value of that character is displayed.
Source Code
/* C Program to compute remainder and quotient */ #include <stdio.h> int main(){ int dividend, divisor, quotient, remainder; printf("Enter dividend: "); scanf("%d",÷nd); printf("Enter divisor: "); scanf("%d",&divisor); quotient=dividend/divisor; /* Computes quotient */ remainder=dividend%divisor; /* Computes remainder */ printf("Quotient = %d\n",quotient); printf("Remainder = %d",remainder); return 0;
}
Output
/* C Program to compute and display remainder and quotient using only two variables */ #include <stdio.h> int main(){
int dividend, divisor; printf("Enter dividend: "); scanf("%d",÷nd); printf("Enter divisor: "); scanf("%d",&divisor); printf("Quotient = %d\n",dividend/divisor);/* Computes and displays quotient */ printf("Remainder = %d",dividend%divisor); /* Computes and displays remainder */ return 0;
}
Output of this program is same as program above but, only two variables are used in this case instead of four variables.
C Program to Find Size of int, float, double and char of Your System
The size of a character is always 1 byte but, size of int, float and double variables differs from system to system. This program will compute the size of int, float, double and char of you system using sizeof operator. The syntax of size of operator is:
temp = sizeof(operand); /* Here, temp is a variable of type integer,i.e, sizeof() operator returns integer value. */
Source Code
/* This program computes the size of variable using sizeof operator.*/ #include <stdio.h> int main(){ int a; float b; double c; char d; printf("Size of int: %d bytes\n",sizeof(a)); printf("Size of float: %d bytes\n",sizeof(b)); printf("Size of double: %d bytes\n",sizeof(c)); printf("Size of char: %d byte\n",sizeof(d)); return 0;
}
Output
Note: You may get different output depending upon your system.
Explanation In this program, 4 variables a, b, c and d are declared of type int, float, double and char respectively. Then, the size of these variables is computed using sizeof operator and displayed.
Source Code
#include <stdio.h> int main(){ int a; long int b; /* int is optional. */ long long int c; /* int is optional. */ printf("Size of int = %d bytes\n",sizeof(a)); printf("Size of long int = %ld bytes\n",sizeof(b)); printf("Size of long long int = %ld bytes",sizeof(c)); return 0;
}
Output
Size of int = 4 bytes Size of long int = 4 bytes Size of long long int = 8 bytes
In this program, the sizeof operator is used for finding the size of int, long int and long long int. Thus, int and long int for my system can hold values from -231 to 231-1. If I have to work on data outside this range, I have to use long
long int, which can hold values from -263 to 263-1 .
Similarly, the long keyword can be used double and floats types.
int main(){ float a, b, temp; printf("Enter value of a: "); scanf("%f",&a); printf("Enter value of b: "); scanf("%f",&b); temp = a; /* Value of a is stored in variable temp */ a = b; /* Value of b is stored in variable a */ b = temp; /* Value of temp(which contains initial value of a) is stored in variable b*/ printf("\nAfter swapping, value of a = %.2f\n", a); printf("After swapping, value of b = %.2f", b); return 0; }
Output
Enter value of a: 1.20 Enter value of b: 2.45 After swapping, value of a = 2.45 After swapping, value of b = 1.2
if statement syntax
if (test expression){ statement/s to be executed if test expression is true; }
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed. But, if the test expression is false, the execution of the statements for the body of if statements are skipped.
Flowchart of if statement
Example of if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h> int main(){ int num; printf("Enter a number to check.\n"); scanf("%d",&num); if(num<0) /* checking whether number is less than 0 or not. */ printf("Number=%d\n",num); /*If test condition is true, statement above will be executed, otherwise it will not be executed */ printf("The if statement in C programming is easy."); return 0;
}
Output 1
if...else statement
The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false.
Syntax of if...else
if (test expression) statements to be executed if test expression is true; else statements to be executed if test expression is false;
#include <stdio.h> int main(){ int num; printf("Enter a number you want to check.\n"); scanf("%d",&num); if((num%2)==0) //checking whether remainder is 0 or not. printf("%d is even.",num); else printf("%d is odd.",num); return 0;
}
Output 1
2 2 is even.
#include <stdio.h> int main(){ int numb1, numb2; printf("Enter two integers to check".\n); scanf("%d %d",&numb1,&numb2); if(numb1==numb2) //checking whether two integers are equal. printf("Result: %d=%d",numb1,numb2); else if(numb1>numb2) //checking whether numb1 is greater than numb2. printf("Result: %d>%d",numb1,numb2); else printf("Result: %d>%d",numb2,numb1); return 0;
}
Output 1
Result: 5>3
Output 2
Check whether an alphabet is vowel or consonant Program to find largest number among three numbers Program to Compute roots of quadratic equation Program to Check Leap Year
This program also can be solved using conditional operator which is shorthand notation for if else statement.
/* C program to check whether a character is vowel or consonant using conditional operator */ #include <stdio.h> int main(){ char c; printf("Enter an alphabet: ");
Source Code 1
/* C program to find largest number using if statement only */ #include <stdio.h> int main(){ float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>=b && a>=c) printf("Largest number = %.2f", a); if(b>=a && b>=c) printf("Largest number = %.2f", b); if(c>=a && c>=b) printf("Largest number = %.2f", c); return 0;
}
Source Code 2
/* C program to find largest number using if...else statement */ #include <stdio.h> int main(){ float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if (a>=b) { if(a>=c) printf("Largest number = %.2f",a); else printf("Largest number = %.2f",c); } else { if(b>=c) printf("Largest number = %.2f",b);
Source Code 3
/* C Program to find largest number using nested if...else statement */ #include <stdio.h> int main(){ float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>=b && a>=c) printf("Largest number = %.2f", a); else if(b>=a && b>=c) printf("Largest number = %.2f", b); else printf("Largest number = %.2f", c); return 0;
}
Though the technique to solve this problem is different in these three examples, output of all these program is same.
r2= (-b-sqrt(determinant))/(2*a); printf("Roots are: %.2f and %.2f",r1 , r2); } else if (determinant==0) { r1 = r2 = -b/(2*a); printf("Roots are: %.2f and %.2f", r1, r2); } else { real= -b/(2*a); imag = sqrt(-determinant)/(2*a); printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag); } return 0;
}
Output 1
Enter coefficients a, b and c: 2.3 4 5.6 Roots are: -0.87+1.30i and -0.87-1.30i
Output 2
This program asks user to enter a year and this program checks whether that year is leap year or not.
/* C program to check whether a year is leap year or not using if else statement.*/ #include <stdio.h> int main(){ int year; printf("Enter a year: "); scanf("%d",&year); if(year%4 == 0) { if( year%100 == 0) /* Checking for a century year */
{ if ( year%400 == 0) printf("%d is a leap year.", year); else printf("%d is not a leap year.", year); } else printf("%d is a leap year.", year ); } else printf("%d is not a leap year.", year); return 0;
}
Output 1
#include <stdio.h> int main(){ int n, count, sum=0; printf("Enter the value of n.\n"); scanf("%d",&n); for(count=1;count<=n;++count) //for loop terminates if count>n { sum+=count; /* this statement is equivalent to sum=sum+count */
} printf("Sum=%d",sum); return 0; }
Output
Program to generate multiplication table Program to display all factors of a number Program to find G.C.D or H.C.F of two numbers Program to calculate factorial of a number
#include <stdio.h> int main() { int n, range, i; printf("Enter an integer to find multiplication table: "); scanf("%d",&n); printf("Enter range of multiplication table: "); scanf("%d",&range); for(i=1;i<=range;++i) { printf("%d * %d = %d\n", n, i, n*i); } return 0;
}
Output
Enter Enter 6 * 1 6 * 2 6 * 3 6 * 4
C Program to Find Size of int, float, double and char of Your System
The size of a character is always 1 byte but, size of int, float and double variables differs from system to system. This program will compute the size of int, float, double and char of you system using sizeof operator. The syntax of size of operator is:
temp = sizeof(operand); /* Here, temp is a variable of type integer,i.e, sizeof() operator returns integer value. */
Source Code
/* This program computes the size of variable using sizeof operator.*/ #include <stdio.h> int main(){ int a; float b; double c; char d; printf("Size of int: %d bytes\n",sizeof(a)); printf("Size of float: %d bytes\n",sizeof(b)); printf("Size of double: %d bytes\n",sizeof(c)); printf("Size of char: %d byte\n",sizeof(d)); return 0;
}
Output
Note: You may get different output depending upon your system.
Explanation In this program, 4 variables a, b, c and d are declared of type int, float, double and char respectively. Then, the size of these variables is computed using sizeof operator and displayed.
}
Output
In this program, two integers are taken from user and stored in variable num1 and num2. Then i is initialized to 1 and for loop is executed until i becomes equal to smallest of two numbers. In each looping iteration, it is checked whether i is factor of both numbers or not. If i is factor of both numbers, it is stored to hcf. When for loop is completed, the H.C.F of those two numbers will be stored in variable hcf.
{ int num1, num2, min,i; printf("Enter two integers: "); scanf("%d %d", &num1, &num2); min=(num1>num2)?num2:num1; /* minimum value is stored in variable min */ for(i=min;i>=1;--i) { if(num1%i==0 && num2%i==0) { printf("HCF of %d and %d is %d", num1, num2,i); break; } } return 0; }
This program is little optimized than the program above to find H.C.F. In this program, smallest of two integers entered by user is stored in variable min. Then i is initialized to min and for loop is executed. In each looping iteration, whether i is factor of these two numbers is checked. If i is a factor of these two numbers then, i will be the highest common divisor and loop is terminated using break statement.
35 HCF or 14 and 35 is 7
factorial = 1*2*3*4....n
If a number is negative, factorial does not exist and factorial of 0 is 1. This program takes an integer from a user. If user enters negative integer, this program will display error message and if user enters non-negative integer, this program will display the factorial of that number.
Here the type of factorial variable is declared as: unsigned long long. It is because, the factorial is always positive, so unsigned keyword is used and the factorial of a number can be pretty large. For example: the factorial of 10 is 3628800 thus, long long keyword is used. To solve this program, we have used for loop but, this program also can be solved in similar way using while loop.
LCM=(num1*num2)/GCD
Visit this page to learn different methods for finding GCD of two numbers.
#include<stdio.h> int main() { int n1,n2,temp1,temp2; printf("Enter two positive integers: "); scanf("%d %d",&n1,&n2); temp1=n1;
temp2=n2; while(temp1!=temp2) { if(temp1>temp2) temp1-=temp2; else temp2-=temp1; } printf("LCM of two numbers %d and %d is %d", n1, n2, (n1*n2)/temp1); return 0; }
/* If inch is greater than 12, changing it to feet. */ if (sum.inch>12.0) { sum.inch=sum.inch-12.0; ++sum.feet; } printf("\nSum of distances=%d\'-%.1f\"",sum.feet,sum.inch); return 0;
}
Output
In this program, a structure(Distance) is defined with inch and feet as its members. Then, three variables( d1, d2 and sum) of struct
Distance type is created. Two variables(d1 and d2) are used for taking distance from user and the sum of two distance is stored in
In the beginning of while loop, test expression is checked. If it is true, codes inside the body of while loop,i.e, code/s inside parentheses are executed and again the test expression is checked and process continues until the test expression becomes false.
/*C program to demonstrate the working of while loop*/ #include <stdio.h> int main(){ int number,factorial; printf("Enter a number.\n"); scanf("%d",&number); factorial=1; while (number>0){ /* while loop continues util test condition number>0 is true */ factorial=factorial*number; --number; } printf("Factorial=%d",factorial); return 0;
}
Output
do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.
/*C program to demonstrate the working of do...while statement*/ #include <stdio.h> int main(){ int sum=0,num; do /* Codes inside the body of do...while loops are at least executed once. */ { printf("Enter a number\n"); scanf("%d",&num); sum+=num; } while(num!=0); printf("sum=%d",sum); return 0; }
Output
- Program to reverse a integer - Program to Calculate the power of a number - Program to Check Armstrong number
/* C program to calculate the power of an integer*/ #include <stdio.h> int main() { int base, exp; long long int value=1; printf("Enter base number and exponent respectively: ");
scanf("%d%d", &base, &exp); while (exp!=0) { value*=base; /* value = value*base; */ --exp; } printf("Answer = %d", value);
}
Output
This program can only calculate the power if base power and exponent are integers. If you need to the calculate power of a floating point number then, you can use pow() function.
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number. 12 is not equal to 1*1*1+2*2*2 // 12 is not an Armstrong number.
break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break statement is used with conditional if statement.
The figure below explains the working of break statement in all three type of loops.
/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative number*/ # include <stdio.h> int main(){ float num,average,sum; int i,n; printf("Maximum no. of inputs\n"); scanf("%d",&n); for(i=1;i<=n;++i){
printf("Enter n%d: ",i); scanf("%f",&num); if(num<0.0) break; //for loop breaks if num<0.0 sum=sum+num; } average=sum/(i-1); printf("Average=%.2f",average); return 0;
}
Output
Maximum no. of inputs 4 Enter n1: 1.5 Enter n2: 12.5 Enter n3: 7.2 Enter n4: -1 Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using break statement with executing the statement below it i.e., without executing sum=sum+num. In C, break statements are also used in switch...case statement. You will study it in C switch...case statement chapter.
continue Statement
continue;
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.
For better understanding of how continue statements works in C programming. Analyze the figure below which bypasses some code/s inside loops using continue statement.
//program to demonstrate the working of continue statement in C programming # include <stdio.h> int main(){ int i,num,product; for(i=1,product=1;i<=4;++i){ printf("Enter num%d:",i); scanf("%d",&num); if(num==0) continue; / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */ product*=num; } printf("product=%d",product); return 0; }
Output
Syntax of switch...case
switch (expression) { case constant1: codes to be executed if expression equals to constant1; break; case constant2: codes to be executed if expression equals to constant3; break; . . . default: codes to be executed if expression doesn't match to any cases; }
In switch...case, expression is either an integer or a character. If the value of switch expression matches any of the constant in case, the relevant codes are executed and control moves out of the switch...case statement. If the expression doesn't matches any of the constant in case, then the default statement is executed.
/* C program to demonstrate the working of switch...case statement */ /* Program to create a simple calculator for addition, subtraction, multiplication and division */ # include <stdio.h> int main(){ char operator; float num1,num2; printf("Enter operator +, - , * or / :\n"); operator=getche(); printf("\nEnter two operands:\n"); scanf("%f%f",&num1,&num2); switch(operator) { case '+': printf("num1+num2=%.2f",num1+num2); break; case '-': printf("num1-num2=%.2f",num1-num2); break; case '*': printf("num1*num2=%.2f",num1*num2); break; case '/':
printf("num2/num1=%.2f",num1/num2); break; default: /* if operator is other than +, -, * or /, error message is shown */ printf(Error! operator is not correct"); break; } return 0;
}
Output
Maximum no. of inputs: 4 Enter n1: 1.5 Enter n2: 12.5 Enter n3: 7.2 Enter n4: -1 Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.
The goto statement can be replaced in most of C program with the use of break and continue statements. In fact, any program in C programming can be perfectly written without the use of goto statement. All programmer should try to avoid goto statement as possible as they can.
C Programming Examples and Source Code C Program to Find LCM of two numbers entered by user C Program to Count Number of Digits of an Integer C Program to Reverse a Number C program to Calculate the Power of a Number C Program to Check Whether a Number is Palindrome or Not C Program to Check Whether a Number is Prime or Not C Program to Display Prime Numbers Between Two Intervals C program to Check Armstrong Number C Program to Display Armstrong Number Between Two Intervals C program to Display Factors of a Number C program to Print Pyramids and Triangles in C programming using Loops C program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case
googleplus
In this program, user is asked to enter an integer which is stored in variable num. Then, the remainder is found when that number is divided by 2 and checked whether remainder is 0 or not. If remainder is 0 then, that number is even otherwise that number is odd. This task is performed using if...else statement in C programming and the result is displayed accordingly. This program also can be solved using conditional operator[ ?: ] which is the shorthand notation for if...else statement.
/* C program to check whether an integer is odd or even using conditional operator */ #include <stdio.h> int main(){ int num; printf("Enter an integer you want to check: "); scanf("%d",&num); ((num%2)==0) ? printf("%d is even.",num) : printf("%d is odd.",num); return 0;
}
The output of this program same as above program.
Source Code
#include <stdio.h> int main() { float num; printf("Enter a number: "); scanf("%f",&num); if (num<=0) { if (num==0) printf("You entered zero."); else printf("%.2f is negative.",num); } else printf("%.2f is positive.",num); return 0; }
/* C programming code to check whether a number is negative or positive or zero using nested if...else statement. */ #include <stdio.h> int main() { float num; printf("Enter a number: "); scanf("%f",&num); if (num<0) /* Checking whether num is less than 0*/ printf("%.2f is negative.",num); else if (num>0) /* Checking whether num is greater than zero*/ printf("%.2f is positive.",num); else printf("You entered zero."); return 0;
}
Output 1
scanf("%c",&c); if( (c>='a'&& c<='z') || (c>='A' && c<='Z')) printf("%c is an alphabet.",c); else printf("%c is not an alphabet.",c); return 0; }
Output 1
Output
/* This program displays error message when user enters negative number or 0 and displays the sum of natural numbers if user enters positive number. */ #include <stdio.h> int main() { int n, count, sum=0; printf("Enter an integer: "); scanf("%d",&n); if ( n<= 0) printf("Error!!!!"); else {
for(count=1;count<=n;++count) /* for loop terminates if count>n */ { sum+=count; /* sum=sum+count */ } printf("Sum = %d",sum); } return 0; }
#include <stdio.h> int main() { int t1=0, t2=1, display=0, num; printf("Enter an integer: "); scanf("%d",&num); printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */ display=t1+t2; while(display<num) { printf("%d+",display); t1=t2; t2=display; display=t1+t2; } return 0;
}
Output
Explanation This program takes an integer from user and stores that number in variable n. Suppose, user entered 34523. Then, while loop is executed because n!=0 will be true in first iteration. The codes inside while loop will be executed. After first iteration, value of n will be 3452 and count will be 1. Similarly, in second iteration n will be equal to 345 and count will be equal to 2. This process goes on and after fourth iteration, n will be equal to 3 and count will be equal to 4. Then, in next iteration n will be equal to 0 and count will be equal to 5 and program will be terminated as n!=0 becomes false.
int main() { int n1, n2, i, j, flag; printf("Enter two numbers(intevals): "); scanf("%d %d", &n1, &n2); printf("Prime numbers between %d and %d are: ", n1, n2); for(i=n1+1; i<n2; ++i) { flag=0; for(j=2; j<=i/2; ++j) { if(i%j==0) { flag=1; break; } } if(flag==0) printf("%d ",i); } return 0;
}
Output
int main() { int n1, n2, i, temp, num, rem; printf("Enter two numbers(intervals): "); scanf("%d %d", &n1, &n2); printf("Armstrong numbers between %d an %d are: ", n1, n2); for(i=n1+1; i<n2; ++i) { temp=i; num=0; while(temp!=0) { rem=(temp%10); num+=rem*rem*rem; temp/=10; } if(i==num) { printf("%d ",i); } } return 0;
}
Output
Enter two numbers(intervals): 100 400 Armstrong numbers between 100 and 400 are: 153 370 371
In this program, it is assumed that, the user always enters smaller number first. This program will not perform the task intended if user enters larger number first. You can add the code to swap two numbers entered by user if user enters larger number first to make this program work properly.
* * * * * *
* * * * * * * * *
#include <stdio.h> int main() { int i,j,rows; printf("Enter the number of rows: "); scanf("%d",&rows); for(i=1;i<=rows;++i) { for(j=1;j<=i;++j) { printf("* "); } printf("\n"); } return 0;
}
Write a C Program to print half pyramid as using numbers as shown in figure below.
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
#include <stdio.h> int main() { int i,j,rows; printf("Enter the number of rows: "); scanf("%d",&rows); for(i=1;i<=rows;++i) { for(j=1;j<=i;++j) { printf("%d ",j); } printf("\n"); } return 0;
}
Write a C Program to print triangle of characters as below
A B B C C C D D D D E E E E E
int i,j; char input,temp='A'; printf("Enter uppercase character you want in triangle at last row: "); scanf("%c",&input); for(i=1;i<=(input-'A'+1);++i) { for(j=1;j<=i;++j) printf("%c",temp); ++temp; printf("\n"); } return 0;
}
* * * *
* * * * * * * * * * *
#include <stdio.h> int main() { int i,j,rows; printf("Enter the number of rows: "); scanf("%d",&rows); for(i=rows;i>=1;--i) { for(j=1;j<=i;++j) { printf("* "); } printf("\n"); } return 0;
1 1 1 1 } 2 3 4 5 2 3 4 2 3 2 1
Write a C Program to print inverted half pyramid as using numbers as shown below.
#include <stdio.h> int main() { int i,j,rows; printf("Enter the number of rows: "); scanf("%d",&rows);
* * * * * * * * *
* * * * *
* * * * * * * * * * *
#include <stdio.h> int main() { int i,space,rows,k=0; printf("Enter the number of rows: "); scanf("%d",&rows); for(i=1;i<=rows;++i) { for(space=1;space<=rows-i;++space) { printf(" "); } while(k!=2*i-1) { printf("* "); ++k; } k=0; printf("\n"); } return 0;
}
Write a C program to print the pyramid of digits in pattern as below.
2 3 4 4 5 6 5 6 7
1 3 5 7 8
2 4 3 6 5 4 9 8 7 6 5
#include <stdio.h> int main() { int i,space,rows,k=0,count=0,count1=0; printf("Enter the number of rows: "); scanf("%d",&rows); for(i=1;i<=rows;++i) { for(space=1;space<=rows-i;++space) { printf(" "); ++count; } while(k!=2*i-1) { if (count<=rows-1) { printf("%d ",(i+k)); ++count; } else { ++count1; printf("%d ", (i+k-2*count1)); } ++k; } count1=count=k=0; printf("\n"); } return 0;
}
#include<stdio.h> int main() { int rows,i,j,space; printf("Enter number of rows: "); scanf("%d",&rows); for(i=rows;i>=1;--i) { for(space=0;space<rows-i;++space) printf(" ");
#include<stdio.h> int main() { int rows,coef=1,space,i,j; printf("Enter number of rows: "); scanf("%d",&rows); for(i=0;i<rows;i++) { for(space=1;space<=rows-i;space++) printf(" "); for(j=0;j<=i;j++) { if (j==0||i==0) coef=1; else coef=coef*(i-j+1)/j; printf("%4d",coef); } printf("\n"); }
}
,
Comments
Submitted by shahirharahim (not verified) on Mon, 2012-12-17 07:25 its a nice one to practice and make your concepts clear regardings loops....:) \
reply
C program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case
This program takes an arithmetic operator (+, -, *, /) and two operands from an user and performs the operation on those two operands depending upon the operator entered by user. This program can be solved using switch....case statement as:
/* Source code to create a simple calculator for addition, subtraction, multiplication and division using switch...case statement in C programming. */ # include <stdio.h> int main() { char operator; float num1,num2; printf("Enter operator either + or - or * or divide : "); scanf("%c",&operator); printf("Enter two operands: "); scanf("%f%f",&num1,&num2); switch(operator) { case '+': printf("num1+num2=%.2f",num1+num2); break; case '-': printf("num1-num2=%.2f",num1-num2); break; case '*': printf("num1*num2=%.2f",num1*num2); break; case '/': printf("num2/num1 = %.2f",num1/num2);
break; default: /* If operator is other than +, -, * or /, error message is shown */ printf("Error! operator is not correct"); break; } return 0;
}
Output
Enter operator either + or - or * or divide: / Enter two operands: 13.456 4.56 num2/num1 = 2.95
Explanation This program takes an operator and two operands from user. The operator is stored in variable operator and two operands are stored in num1 and num2 respectively. Then, switch...case statement is used for checking the operator entered by user. If user enters + then, statements for case: '+' is executed and program is terminated. If user enters - then, statements for
case: '-' is executed and program is terminated. This program works similarly for * and / operator. But, if the operator
doesn't matches any of the four character [ +, -, * and / ], default statement is executed which displays error message.
C Programming Functions
Function in programming is a segment that groups a number of program statements to perform specific task. A C program has at least one function main( ). Without main() function, there is technically no C program.
Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
Library function
Library functions are the in-built function in C programming system. For example:
main()
- The execution of every C program starts from this main() function.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C. Visit this page to learn more about library functions in C programming language.
/*Program to demonstrate the working of user defined function*/ #include <stdio.h> int add(int a, int b); //function prototype(declaration) int main(){ int num1,num2,sum; printf("Enters two number to add\n"); scanf("%d %d",&num1,&num2); sum=add(num1,num2); //function call printf("sum=%d",sum); return 0; } int add(int a,int b) //function declarator { /* Start of function definition. */ int add; add=a+b; return add; //return statement of function /* End of function definition. */ }
Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type.
Function prototype are not needed if user-definition function is written before main() function.
Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked).
Function definition
Function definition contains programming codes to perform specific task.
1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function.
Syntax of function declaration and declarator are almost same except, there is no semicolon at the end of declarator and function declarator is followed by function body. In above example, int add(int a,int b) in line 12 is a function declarator.
2. Function body
Function declarator is followed by body of function which is composed of statements.
Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example: If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same. A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling function.
For better understanding of arguments and return in functions, user-defined functions can be categorised as: 1. 2. 3. 4. Function with no arguments and no return value Function with no arguments and return value Function with arguments but no return value Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 cateogories of user defined functions.
return 0; } void check_display(int n){ /* There is no return value to calling function. Hence, return type of function is void. */ int i,flag; for(i=2,flag=i;i<=n/2;++i,flag=i){ if(n%i==0){ printf("%d is not prime",n); ++flag; break; } } if(flag==i) printf("%d is prime",n);
}
Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to userdefined function but, value is not returned from it to calling function.
Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function
check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.
C Programming Recursion
A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.
#include <stdio.h> int sum(int n); int main(){ int num,add; printf("Enter a positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add); } int sum(int n){ if(n==0) return n; else return n+sum(n-1); /*self call to function sum() */
}
Output
sum(5) =5+sum(4) =5+4+sum(3) =5+4+3+sum(2) =5+4+3+2+sum(1) =5+4+3+2+1+sum(0) =5+4+3+2+1+0 =5+4+3+2+1 =5+4+3+3 =5+4+6 =5+10 =15
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to 0, there is no recursive call and recursion ends.
Program to calculate factorial using recursion Program to reverse sentence using recursion Program to find H.C.F using recursive function
function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.
External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables. In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.
a=10
register int a;
Register variables are similar to automatic variable and exists inside that particular function only. If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Value stored in register are much faster than that of memory. In case of larger program, variables that are used in loops and function parameters are declared register variables. Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it in memory.
static int i;
Here, i is a static variable.
10
During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third call. If variable c had been automatic variable, the output would have been:
C Function Examples
C Programming Examples and Source Code C Program to Display Prime Numbers Between Intervals by Making Function C Program to Check Prime and Armstrong Number by Making Function C program to Check Whether a Number can be Express as Sum of Two Prime Numbers C program to Find Sum of Natural Numbers using Recursion. C program to Calculate Factorial of a Number Using Recursion C Program to Find H.C.F Using Recursion C program to Reverse a Sentence Using Recursion
C Programming Examples and Source Code C program to Calculate the Power of a Number Using Recursion C Program to Convert Binary Number to Decimal and Decimal to Binary C Program to Convert Octal Number to Decimal and Decimal to Octal C Program to Convert Binary Number to Octal and Octal to Binary
/* C program to check either prime number or Armstrong number depending upon the data entered by user. */ #include <stdio.h> int prime(int n); int armstrong(int n); int main() { char c; int n,temp=0; printf("Eneter a positive integer: "); scanf("%d",&n); printf("Enter P to check prime and A to check Armstrong number: "); c=getche(); if (c=='p' || c=='P') { temp=prime(n); if(temp==1) printf("\n%d is a prime number.", n); else printf("\n%d is not a prime number.", n); } if (c=='a' || c=='A') { temp=armstrong(n); if(temp==1) printf("\n%d is an Armstrong number.", n); else printf("\n%d is not an Armstrong number.",n); } return 0; } int prime(int n) { int i, flag=1; for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=0; break;
} } return flag; } int armstrong(int n) { int num=0, temp, flag=0; temp=n; while(n!=0) { num+=(n%10)*(n%10)*(n%10); n/=10; } if (num==temp) flag=1; return flag;
}
Output
Eneter a positive integer: 371 Enter P to check prime and A to check Armstrong number: p 371 is not a prime number.
C program to Check Whether a Number can be Express as Sum of Two Prime Numbers
This program takes a positive integer from user and checks whether that number can be expressed as the sum of two prime numbers. If that number can be expressed as sum of two prime numbers then, that number is expressed as sum of two prime numbers in output. To perform this task, a user-defined function is created to check prime number.
#include <stdio.h> int prime(int n); int main() { int n, i, flag=0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=n/2; ++i) { if (prime(i)!=0) { if ( prime(n-i)!=0) { printf("%d = %d + %d\n", n, i, n-i); flag=1; } }
} if (flag==0) printf("%d can't be expressed as sum of two prime numbers.",n); return 0; } int prime(int n) /* Function to check prime number */ { int i, flag=1; for(i=2; i<=n/2; ++i) if(n%i==0) flag=0; return flag;
}
Output
int hcf(int n1, int n2) { if (n2!=0) return hcf(n2, n1%n2); else return n1;
}
Output
Reverse() function and the Reverse() function before is same although they both have same name. Also, the variables are also
different, i.e., c variable in both functions are also different. Then, the second character is stored in variable c of second Reverse function. This process goes on until user enters '\n'. When, user enters '\n', the last function Reverse() function returns to second last
Reverse() function and prints the last character. Second last Reverse() function returns to the third last Reverse() function and prints
second last character. This process goes on and the final output will be the reversed sentence.
Source Code to Convert Either Binary Number to Decimal or Decimal Number to Binary
/* C programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */ #include <stdio.h> #include <math.h> int binary_decimal(int n); int decimal_binary(int n); int main() { int n; char c; printf("Instructions:\n"); printf("1. Enter alphabet 'd' to convert binary to decimal.\n"); printf("2. Enter alphabet 'b' to convert decimal to binary.\n"); scanf("%c",&c); if (c =='d' || c == 'D') { printf("Enter a binary number: "); scanf("%d", &n); printf("%d in binary = %d in decimal", n, binary_decimal(n)); } if (c =='b' || c == 'B') { printf("Enter a decimal number: "); scanf("%d", &n); printf("%d in decimal = %d in binary", n, decimal_binary(n)); } return 0; } int decimal_binary(int n) /* Function to convert decimal to binary.*/ { int rem, i=1, binary=0; while (n!=0) { rem=n%2; n/=2; binary+=rem*i; i*=10;
} return binary; } int binary_decimal(int n) /* Function to convert binary to decimal.*/ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(2,i); ++i; } return decimal;
}
Output
Explanation This program asks user to enter alphabet 'b' to convert decimal number to binary and alphabet 'd' to convert binary number to decimal. In accordance with the character entered, user is asked to enter either binary value to convert to decimal or decimal value to convert to binary. To perform conversion, two functions are made decimal_binary(); to convert decimal to binary and binary_decimal(); to convert binary to decimal. Decimal number entered by user is passed to decimal_binary() and this function computes the binary value of that number and returns it main() function. Similarly, binary number is passed to function binary_decimal() and this function computes decimal value of that number and returns it to main() function.
/* C programming source code to convert either octal to decimal or decimal to octal according to data entered by user. */ #include <stdio.h> #include <math.h> int decimal_octal(int n); int octal_deciaml(int n); int main() { int n; char c; printf("Instructions:\n"); printf("1. Enter alphabet 'o' to convert decimal to octal.\n"); printf("2. Enter alphabet 'd' to convert octal to decimal.\n"); scanf("%c",&c); if (c =='d' || c == 'D') { printf("Enter an octal number: "); scanf("%d", &n); printf("%d in octal = %d in decimal", n, octal_decimal(n)); } if (c =='o' || c == 'O') { printf("Enter a decimal number: "); scanf("%d", &n); printf("%d in decimal = %d in octal", n, decimal_octal(n)); } return 0; } int decimal_octal(int n) /* Function to convert decimal to octal */ { int rem, i=1, octal=0; while (n!=0) { rem=n%8; n/=8; octal+=rem*i; i*=10; } return octal; } int octal_decimal(int n) /* Function to convert octal to decimal */ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(8,i);
This program asks user to enter a character and in accordance with that character user is asked to enter either octal number or decimal number. If user chooses to convert octal number to decimal then, that number is passed to function octal_decimal(). This function will convert the octal number passed by user to decimal number and returns it to main function. Similarly, if user chooses to convert decimal number to octal then, that number is passed to function decimal_octal(). This function will convert decimal number to octal number and returns it to main function.
/* C program to take and display number in octal form */ #include <stdio.h> int main() { int n; printf("Enter a decimal number: "); scanf("%d",&n); /* %o will display the integer in corresponding octal form */ printf("%d in decimal = %o in octal", n, n); printf("\nEnter an octal number: "); scanf("%o",&n); /* Takes number in octal form.*/ printf("%o in octol = %d in decimal", n, n); return 0;
}
return octal; } int octal_binary(int n) /* Function to convert octal to binary.*/ { int decimal=0, binary=0, i=0; while (n!=0) { decimal+=(n%10)*pow(8,i); ++i; n/=10; } /* At this point, the decimal variable contains corresponding decimal value of that octal number. */ i=1; while(decimal!=0) { binary+=(decimal%2)*i; decimal/=2; i*=10; } return binary;
}
Output
This program asks user to enter alphabet 'b' to convert octal number to binary or alphabet 'o' to convert binary number to octal. In accordance with the character entered, user is asked to enter either binary value to convert to octal or octal value to convert to binary. To perform conversion, two functions are made octal_binary(); to convert octal to binary and binary_octal(); to convert binary to octal. Octal number entered by user is passed to octal_binary() and this function computes the binary value of that octal number number and returns it main() function. Similarly, binary number is passed to function binary_octal() and this function computes octal value of that number and return it main() function.
C Programming Arrays
In C programming, one of the frequently arising problem is to handle similar types of data. For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays. An array is a sequence of data item of homogeneous value(same type).
Arrays are of two types: 1. 2. One-dimensional arrays Multidimensional arrays( will be discussed in next chapter )
Array elements
Size of array defines the number of elements in an array. Each element of array can be accessed and used by user according to the need of program. For example:
int age[5];
Note that, the first element is numbered 0 and so on. Here, the size of array age is 5 times the size of int because there are 5 elements. Suppose, the starting addres of age[0] is 2120d and the size of int be 4 bytes. Then, the next address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of an array.
scanf("%d",&age[2]); /* statement to insert value in the third element of array age[]. */ scanf("%d",&age[i]); /* Statement to insert value in (i+1)th element of array age[]. */ /* Because, the first element of array is age[0], second is age[1], ith is age[i-1] and (i+1)th is age[i]. */ printf("%d",age[0]); /* statement to print first element of an array. */ printf("%d",age[i]); /* statement to print (i+1)th element of an array. */
Output
Enter number of students: 3 Enter marks of student1: 12 Enter marks of student2: 31 Enter marks of student3: 2 sum=45
float a[2][6];
Here, a is an array of two dimension, which is an example of multidimensional array. This array has 2 rows and 6 columns For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:
double cprogram[3][2][4]={ {{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}}, {{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}}, {{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}} };
Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers of data. Similarly, the array of any dimension can be initialized in C programming.
#include <stdio.h> int main(){ float a[2][2], b[2][2], c[2][2]; int i,j; printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/ for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("Enter a%d%d: ",i+1,j+1); scanf("%f",&a[i][j]); } printf("Enter the elements of 2nd matrix\n"); for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("Enter b%d%d: ",i+1,j+1); scanf("%f",&b[i][j]); } for(i=0;i<2;++i) for(j=0;j<2;++j){ /* Writing the elements of multidimensional array using loop. */ c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */ } printf("\nSum Of Matrix:"); for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("%.1f\t",c[i][j]); if(j==1) /* To display matrix sum in order. */ printf("\n"); } return 0; }
Ouput
Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter
the elements of 1st matrix a11: 2; a12: 0.5; a21: -1.1; a22: 2; the elements of 2nd matrix b11: 0.2; b12: 0; b21: 0.23; b22: 23;
#include <stdio.h> void display(int a) { printf("%d",a); } int main(){ int c[]={2,3,4}; display(c[2]); //Passing array element c[2] only. return 0;
}
Output
4
Single element of an array can be passed in similar manner as passing variable to a function.
#include <stdio.h> float average(float a[]); int main(){ float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18}; avg=average(c); /* Only name of array is passed as argument. */ printf("Average age=%.2f",avg); return 0; } float average(float a[]){ int i; float avg, sum=0.0; for(i=0;i<6;++i){ sum+=a[i]; } avg =(sum/6); return avg;
}
Output
Average age=27.08
C Programming Pointers
Pointers are the powerful feature of C and (C++) programming, which differs it from other popular programming languages like: java and Visual Basic. Pointers are used in C program to access the memory and manipulate the address.
Reference operator(&)
/* Example to demonstrate use of reference operator in C programming. */ #include <stdio.h> int main(){ int var=5; printf("Value: %d\n",var); printf("Address: %d",&var); //Notice, the ampersand(&) before var. return 0;
}
Output
In above source code, value 5 is stored in the memory location 2686778. var is just the name given to that location. You, have already used reference operator in C program while using scanf() function.
scanf("%d",&var);
Declaration of Pointer
Dereference operator(*) are used to identify an operator as a pointer.
printf("Address of pointer pc:%d\n",pc); printf("Content of pointer pc:%d\n\n",*pc); c=11; printf("Address of pointer pc:%d\n",pc); printf("Content of pointer pc:%d\n\n",*pc); *pc=2; printf("Address of c:%d\n",&c); printf("Value of c:%d\n\n",c); return 0; }
Output
Address of c: 2686784 Value of c: 22 Address of pointer pc: 2686784 Content of pointer pc: 22 Address of pointer pc: 2686784 Content of pointer pc: 11 Address of c: 2686784 Value of c: 2
Explanation of program and figure 1. 2. 3. 4. 5. Code int *pc, p; creates a pointer pc and a variable c. Pointer pc points to some address and that address has garbage value. Similarly, variable c also has garbage value at this point. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable c. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable c (because c is normal variable) and pc is the address of pc (because pc is the pointer variable). Since the address of pc and address of c is same, *pc (value of pointer pc) will be equal to the value of c. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value of *pc will also be 11. Code *pc=2; change the address pointed by pointer pc to change to 2. Since, address of pointer pc is same as address of c, value of c also changes to 2.
int c, *pc; pc=c; /* pc is address whereas, c is not an address. */ *pc=&c; /* &c is address whereas, *pc is not an address. */
#include <stdio.h> int main(){ char c[4]; int i; for(i=0;i<4;++i){ printf("Address of c[%d]=%x\n",i,&c[i]); } return 0;
} Address of Address of Address of Address c[0]=28ff44 c[1]=28ff45 c[2]=28ff46 of c[3]=28ff47
Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements of array.
Note: You may get different address of an array.
int arr[4];
In arrays of C programming, name of the array always points to the first element of an array. Here, address of first element of an array is &arr[0]. Also, arr represents the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr. Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr. Similarly,
AND, a[1] is equivalent to *(a+1). AND, a[2] is equivalent to *(a+2). AND, a[3] is equivalent to *(a+3).
In C, you can declare an array and can use pointer to alter the data of an array.
//Program to find the sum of six numbers with arrays and pointers. #include <stdio.h> int main(){ int i,class[6],sum=0; printf("Enter 6 numbers:\n"); for(i=0;i<6;++i){ scanf("%d",(class+i)); // (class+i) is equivalent to &class[i] sum += *(class+i); // *(class+i) is equivalent to class[i] } printf("Sum=%d",sum); return 0;
}
Output
/* C Program to swap two numbers using pointers and function. */ #include <stdio.h> void swap(int *a,int *b); int main(){ int num1=5,num2=10; swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */ printf("Number1 = %d\n",num1); printf("Number2 = %d",num2); return 0; } void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */ int temp; temp=*a; *a=*b; *b=temp;
}
Output
Number1 = 10 Number2 = 5
Explanation The address of memory location num1 and num2 are passed to function and the pointers *a and *b accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer are changed, the value in memory location also changed correspondingly. Hence, change made to *a and *b was reflected in num1 and num2 in main function. This technique is known as call by reference in C programming.
Use of Function Allocates requested size of bytes and returns a pointer first byte of allocated space Allocates space for an array elements, initializes to zero and then returns a pointer to memory dellocate the previously allocated space Change the size of previously allocated space
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
#include <stdio.h> #include <stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr);
return 0; }
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.
#include <stdio.h> #include <stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); if(ptr==NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr); return 0;
}
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.
#include <stdio.h> #include <stdlib.h> int main() { int *ptr,i,n1,n2; printf("Enter size of array: "); scanf("%d",&n1); ptr=(int*)malloc(n1*sizeof(int)); printf("Address of previously allocated memory: "); for(i=0;i<n1;++i)
printf("%u\t",ptr+i); printf("\nEnter new size of array: "); scanf("%d",&n2); ptr=realloc(ptr,n2); for(i=0;i<n2;++i) printf("%u\t",ptr+i); return 0;
}
#include <stdio.h> int main(){ int i,n; float arr[100]; printf("Enter total number of elements(1 to 100): "); scanf("%d",&n); printf("\n"); for(i=0;i<n;++i) /* Stores number entered by user. */ { printf("Enter Number %d: ",i+1); scanf("%f",&arr[i]); } for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */ { if(arr[0]<arr[i]) /* Change < to > if you want to find smallest element*/ arr[0]=arr[i]; } printf("Largest element = %.2f",arr[0]); return 0;
}
Output
Explanation This program takes n number of elements from user and stores it in array arr[]. To find the largest element, the first two elements of array are checked and largest of these two element is placed in arr[0]. Then, the first and third elements are checked and largest of these two element is placed in arr[0]. This process continues until and first and last elements are checked. After this process, the largest element of an array will be in arr[0] position.
In this program, elements of arrays are used for storing the data and this array is passed to function which calculates standard deviation and finally the result(standard deviation) is displayed in main() function.
This program asks user to enter the size of the matrix (rows and column) then, it asks the user to enter the elements of two matrices and finally it adds two matrix and displays the result.
}
Output
scanf("%d%d",&r2, &c2); } /* Storing elements of first matrix. */ printf("\nEnter elements of matrix 1:\n"); for(i=0; i<r1; ++i) for(j=0; j<c1; ++j) { printf("Enter elements a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]); } /* Storing elements of second matrix. */ printf("\nEnter elements of matrix 2:\n"); for(i=0; i<r2; ++i) for(j=0; j<c2; ++j) { printf("Enter elements b%d%d: ",i+1,j+1); scanf("%d",&b[i][j]); } /* Initializing elements of matrix mult to 0.*/ for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { mult[i][j]=0; } /* Multiplying matrix a and b and storing in array mult. */ for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { mult[i][j]+=a[i][k]*b[k][j]; } /* Displaying the multiplication of two matrix. */ printf("\nOutput Matrix:\n"); for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { printf("%d ",mult[i][j]); if(j==c2-1) printf("\n\n"); } return 0;
}
Output
In this program, user is asked to enter the size of two matrix at first. The column of first matrix should be equal to row of second matrix for multiplication. If this condition is not satisfied then, the size of matrix is again asked using while loop. Then, user is asked to enter two matrix and finally the output of two matrix is calculated and displayed. This program is little bit larger and it is better to solve this program by passing it to a function. Visit this page to learn about multiplying matrices by passing arrays to a function.
printf("Enter elements a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]); } /* Displaying the matrix a[][] */ printf("\nEntered Matrix: \n"); for(i=0; i<r; ++i) for(j=0; j<c; ++j) { printf("%d ",a[i][j]); if(j==c-1) printf("\n\n"); } /* Finding transpose of matrix a[][] and storing it in array trans[][]. */ for(i=0; i<r; ++i) for(j=0; j<c; ++j) { trans[j][i]=a[i][j]; } /* Displaying the transpose,i.e, Displaying array trans[][]. */ printf("\nTranspose of Matrix:\n"); for(i=0; i<c; ++i) for(j=0; j<r; ++j) { printf("%d ",trans[i][j]); if(j==r-1) printf("\n\n"); } return 0;
}
Output
while (c1!=r2) { printf("Error! column of first matrix not equal to row of second.\n"); printf("Enter rows and column for first matrix: "); scanf("%d%d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d%d",&r2, &c2); } take_data(a,b,r1,c1,r2,c2); /* Function to take matices data */ multiplication(a,b,mult,r1,c1,r2,c2); /* Function to multiply two matrices. */ display(mult,r1,c2); /* Function to display resultant matrix after multiplication. */ return 0; } void take_data(int a[][10], int b[][10], int r1,int c1, int r2, int c2) { int i,j; printf("\nEnter elements of matrix 1:\n"); for(i=0; i<r1; ++i) for(j=0; j<c1; ++j) { printf("Enter elements a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]); } printf("\nEnter elements of matrix 2:\n"); for(i=0; i<r2; ++i) for(j=0; j<c2; ++j) { printf("Enter elements b%d%d: ",i+1,j+1); scanf("%d",&b[i][j]); } } void multiplication(int a[][10],int b[][10],int mult[][10],int r1,int c1,int r2,int c2) { int i,j,k; /* Initializing elements of matrix mult to 0.*/ for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { mult[i][j]=0; } /* Multiplying matrix a and b and storing in array mult. */ for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { mult[i][j]+=a[i][k]*b[k][j]; }
} void display(int mult[][10], int r1, int c2) { int i, j; printf("\nOutput Matrix:\n"); for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { printf("%d ",mult[i][j]); if(j==c2-1) printf("\n\n"); }
}
Output
swapped if it is necessary and this process go on until last and second last element is compared and swapped. This completes the first step of bubble sort. If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required result. But, for better performance, in second step, last and second last elements are not compared becuase, the proper element is automatically placed at last after first step. Similarly, in third step, last and second last and second last and third last elements are not compared and so on. A figure is worth a thousand words so, acknowledge this figure for better understanding of bubble sort.
Here, there are 5 elements to the sorted. So, there are 4 steps.
1. 2. 3. 4. 5. 6.
Enter the number of elements to be sorted: 6 Enter element: 12 Enter element: 3 Enter element: 0 Enter element: -3 Enter element: 1 Enter element: -9 In ascending order: -9 -3 0 1 3 13
Note: Though this code is in C programming, this technique can be applied in any programming to sort elements of an array.
Though bubble sort algorithm is quite popular, there are many other better algorithm than bubble sort. Specially, bubble sort should be used to sort large data if performance matters in that program.
Enter elements: 1 2 3 5
4 You entered: 1 2 3 5 4
Visit this page to learn about relationship between pointer and arrays.
Enter value of a, b and c respectively: 1 2 3 Value before swapping: a=1 b=2 c=3 Value after swapping numbers in cycle: a=3 b=1 c=2
Output
C Programming String
In C programming, array of character are called strings. A string is terminated by null character /0. For example:
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];
char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR, char c[5]="abcd"; OR, char c[]={'a','b','c','d','\0'}; OR; char c[5]={'a','b','c','d','\0'};
char *c="abcd";
#include <stdio.h> int main(){ char name[20]; printf("Enter name: "); scanf("%s",name); printf("Your name is %s.",name); return 0;
}
Output
#include <stdio.h> int main(){ char name[30],ch; int i=0; printf("Enter name: "); while(ch!='\n') // terminates if user hit enter { ch=getchar(); name[i]=ch; i++; } name[i]='\0'; // inserting null character at end
int main(){ char name[30]; printf("Enter name: "); gets(name); //Function to read string from user. printf("Name: "); puts(name); //Function to display string. return 0;
}
Both, the above program has same output below: Output
#include <stdio.h> void Display(char ch[]); int main(){ char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. return 0; } void Display(char ch[]){ printf("String Output: "); puts(ch);
}
Here, string c is passed from main() function to user-defined function Display(). In function declaration, ch[] is the formal argument.
Strings handling functions are defined under "string.h" header file, i.e, you have to include the code below to run string handling functions.
#include <string.h>
#include<stdio.h> int main(){ char name[30]; printf("Enter name: "); gets(name); //Function to read string from user. printf("Name: "); puts(name); //Function to display string. return 0;
}
Though, gets() and puts() function handle string, both these functions are defined in "stdio.h" header file.
This program asks user to enter a string and a character and this program checks how many times that character is repeated in the string entered by user.
Enter a string: This website is awesome. Enter a frequency to find frequency: e Frequency of e = 4
C Program to Find the Number of Vowels, Consonants, Digits and White space in a String
This program takes a string from user and finds the total number of vowels, consonants, digits and white space present in that string.
Source Code to Find Number of Vowels, Consonants, Digits and White Space Character
#include<stdio.h> int main(){ char line[150]; int i,v,c,ch,d,s,o; o=v=c=ch=d=s=0; printf("Enter a line of string:\n"); gets(line); for(i=0;line[i]!='\0';++i) { if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') ++v; else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c; else if(line[i]>='0'&&c<='9') ++d; else if (line[i]==' ') ++s; } printf("Vowels: %d",v); printf("\nConsonants: %d",c); printf("\nDigits: %d",d); printf("\nWhite spaces: %d",s); return 0;
}
Output
Enter a line of string: This program is easy 2 understand Vowels: 9 Consonants: 18 Digits: 1 White spaces: 5
Output
scanf("%s",s2); for(i=0; s1[i]!='\0'; ++i); /* i contains length of string s1. */ for(j=0; s2[j]!='\0'; ++j, ++i) { s1[i]=s2[j]; } s1[i]='\0'; printf("After concatenation: %s",s1); return 0;
}
Output
Enter first string: lol Enter second string: :) After concatenation: lol:)
#include <string.h> int main(){ int i,j; char str[10][50],temp[50]; printf("Enter 10 words:\n"); for(i=0;i<10;++i) gets(str[i]); for(i=0;i<9;++i) for(j=i+1;j<10 ;++j){ if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } printf("In lexicographical order: \n"); for(i=0;i<10;++i){ puts(str[i]); } return 0;
}
Output
case 13: hex[i]='D'; break; case 14: hex[i]='E'; break; case 15: hex[i]='F'; break; default: hex[i]=rem+'0'; break; } ++i; n/=16; } hex[i]='\0'; strrev(hex); /* Reverse string */ } int hex_decimal(char hex[]) /* Function to convert hexadecimal to decimal. */ { int i, length, sum=0; for(length=0; hex[length]!='\0'; ++length); for(i=0; hex[i]!='\0'; ++i, --length) { if(hex[i]>='0' && hex[i]<='9') sum+=(hex[i]-'0')*pow(16,length-1); if(hex[i]>='A' && hex[i]<='F') sum+=(hex[i]-55)*pow(16,length-1); if(hex[i]>='a' && hex[i]<='f') sum+=(hex[i]-87)*pow(16,length-1); } return sum;
}
Note: If strrev() function doesn't work on your system, you have to write code to reverse string on your own.
Output
This program asks user to enter alphabet 'd' to convert hexadecimal number to binary or alphabet 'h' to convert decimal number to hexadecimal number. In accordance with the character entered, user is asked to enter either hexadecimal value to convert to decimal or decimal value to convert to hexadecimal.
To perform conversion, two functions are made decimal_hex(); to convert decimal to hexadecimal and hex_decimal(); to convert hexadecimal to decimal. Hexadecimal number entered by user is passed to hex_decimal() and this function computes the decimal value of that hexadecimal number. Similarly, decimal number is passed to function decimal_hex() and this function computes hexadecimal number of that decimal number.
/* C program to take and display number in hexadecimal */ #include <stdio.h> int main() { int n; printf("Enter a decimal number: "); scanf("%d",&n); /* %x will display the integer in corresponding hexadecimal value */ printf("%d in decimal = %x in hexadecimal", n, n); printf("\nEnter an hexadecimal number: "); scanf("%x",&n); /* Takes number in hexadecimal.*/ printf("%x in octal = %d in decimal", n, n); return 0;
}
/* C program to take and display number in hexadecimal format and octal format. */ #include <stdio.h> int main() { int n; printf("Enter an octal number: "); scanf("%o",&n); /*Takes number in octal format. */ /* %o and %x will display the number is octal format and hexadecimal form respectively. */ printf("%o in octal = %x in hexadecimal", n, n); printf("\nEnter an hexadecimal number: "); scanf("%x",&n); /* Takes number in hexadecimal format.*/ printf("%x in hexadecimal = %o in octal", n, n); return 0;
} /* At this point, decimal contains the decimal value of given octal number. */ i=0; while (decimal!=0) { rem=decimal%16; switch(rem) { case 10: hex[i]='A'; break; case 11: hex[i]='B'; break; case 12: hex[i]='C'; break; case 13: hex[i]='D'; break; case 14: hex[i]='E'; break; case 15: hex[i]='F'; break; default: hex[i]=rem+'0'; break; } ++i; decimal/=16; } hex[i]='\0'; strrev(hex); /* Function to reverse string. */ } int hex_octal(char hex[]) /* Function to convert hexadecimal to octal. */ { int i, length, decimal=0, octal=0; for(length=0; hex[length]!='\0'; ++length); for(i=0; hex[i]!='\0'; ++i, --length) { if(hex[i]>='0' && hex[i]<='9') decimal+=(hex[i]-'0')*pow(16,length-1); if(hex[i]>='A' && hex[i]<='F') decimal+=(hex[i]-55)*pow(16,length-1); if(hex[i]>='a' && hex[i]<='f') decimal+=(hex[i]-87)*pow(16,length-1); }
/* At this point decimal contains the decimal value of given hexadecimal number. */ i=1; while (decimal!=0) { octal+=(decimal%8)*i; decimal/=8; i*=10; } return octal;
}
Note: If strrev() function doesn't work on your system, you have to write code to reverse string on your own.
Output
This program asks user to enter a character and in accordance with that character user is asked to enter either octal number or hexadecimal number to convert it. In this program, two user defined functions are defined: octal_hex() to convert number in octal format to hexadecimal and hex_octal to convert number in hexadecimal format to octal.
{ printf("Enter binary number: "); scanf("%d",&n); binary_hex(n,hex); printf("Hexadecimal number: %s",hex); } if (c=='b' || c=='B') { printf("Enter hexadecimal number: "); scanf("%s",hex); printf("Binary number: %d",hex_binary(hex)); } return 0; } void binary_hex(int n, char hex[]) /* Function to convert binary to hexadecimal. */ { int i=0,decimal=0, rem; while (n!=0) { decimal += (n%10)*pow(2,i); n/=10; ++i; } /* At this point, variable decimal contains binary number in decimal format. */ i=0; while (decimal!=0) { rem=decimal%16; switch(rem) { case 10: hex[i]='A'; break; case 11: hex[i]='B'; break; case 12: hex[i]='C'; break; case 13: hex[i]='D'; break; case 14: hex[i]='E'; break; case 15: hex[i]='F'; break;
default: hex[i]=rem+'0'; break; } ++i; decimal/=16; } hex[i]='\0'; strrev(hex); } int hex_binary(char hex[]) /* Function to convert hexadecimal to binary. */ { int i, length, decimal=0, binary=0; for(length=0; hex[length]!='\0'; ++length); for(i=0; hex[i]!='\0'; ++i, --length) { if(hex[i]>='0' && hex[i]<='9') decimal+=(hex[i]-'0')*pow(16,length-1); if(hex[i]>='A' && hex[i]<='F') decimal+=(hex[i]-55)*pow(16,length-1); if(hex[i]>='a' && hex[i]<='f') decimal+=(hex[i]-87)*pow(16,length-1); } /* At this point, variable decimal contains the hexadecimal number in decimal format. */ i=1; while (decimal!=0) { binary+=(decimal%2)*i; decimal/=2; i*=10; } return binary;
}
Note: If strrev() function doesn't work on your system, you have to write code to reverse string on your own.
Output
This program asks user to enter a character and in accordance with that character, user is asked to enter either hexadecimal number or binary number to convert it. In this program, two user defined functions are defined: binary_hex() to convert number in binary format to hexadecimal and hex_binary to convert number in hexadecimal format to binary.
C Programming Structure
Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.
Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name { data_type member1; data_type member2; . . data_type memeber; };
We can create the structure for a person as mentioned above as:
struct person { char name[50]; int cit_no; float salary; }; Inside main function: struct person p1, p2, p[20];
Another way of creating sturcture variable is:
Any member of a structure can be accessed as: structure_variable_name.member_name Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot)
#include <stdio.h> struct Distance{ int feet; float inch; }d1,d2,sum; int main(){ printf("1st distance\n"); printf("Enter feet: "); scanf("%d",&d1.feet); /* input of feet for structure variable d1 */ printf("Enter inch: "); scanf("%f",&d1.inch); /* input of inch for structure variable d1 */ printf("2nd distance\n"); printf("Enter feet: "); scanf("%d",&d2.feet); /* input of feet for structure variable d2 */ printf("Enter inch: "); scanf("%f",&d2.inch); /* input of inch for structure variable d2 */ sum.feet=d1.feet+d2.feet; sum.inch=d1.inch+d2.inch; if (sum.inch>12){ //If inch is greater than 12, changing it to feet. ++sum.feet; sum.inch=sum.inch-12; } printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); /* printing sum of distance d1 and d2 */ return 0;
}
Output
1st distance Enter feet: 12 Enter inch: 7.9 2nd distance Enter feet: 2 Enter inch: 9.8 Sum of distances= 15'-5.7"
typedef struct complex{ int imag; float real; }comp; Inside main: comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1 and c2 are created by this comp type.
struct complex { int imag_value; float real_value; }; struct number{ struct complex c1; int real; }n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure member n1.c1.imag_value is used.
struct name { member1; member2; . . }; -------- Inside function ------struct name *ptr;
Here, the pointer variable of type struct name is created. Structure's member through pointer can be used in two ways: 1. 2. Referencing pointer to another address to access memory Using dynamic memory allocation
#include <stdio.h> struct name{ int a; float b; }; int main(){ struct name *ptr,p; ptr=&p; /* Referencing pointer to memory address of p */ printf("Enter integer: "); scanf("%d",&(*ptr).a); printf("Enter number: "); scanf("%f",&(*ptr).b); printf("Displaying: "); printf("%d%f",(*ptr).a,(*ptr).b); return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed. Structure pointer member can also be accessed using -> operator.
}; int main(){ struct name *ptr; int i,n; printf("Enter n: "); scanf("%d",&n); ptr=(struct name*)malloc(n*sizeof(struct name)); /* Above statement allocates the memory for n structures with pointer ptr pointing to base address */ for(i=0;i<n;++i){ printf("Enter string, integer and floating number respectively:\n"); scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b); } printf("Displaying Infromation:\n"); for(i=0;i<n;++i) printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b); return 0;
}
Output
Enter n: 2 Enter string, integer and floating number Programming 2 3.2 Enter string, integer and floating number Structure 6 2.3 Displaying Information Programming 2 3.20 Structure 6 2.30
respectively:
respectively:
int roll; }; void Display(struct student stu); /* function prototype should be below to the structure declaration otherwise compiler shows error */ int main(){ struct student s1; printf("Enter student's name: "); scanf("%s",&s1.name); printf("Enter roll number:"); scanf("%d",&s1.roll); Display(s1); // passing structure variable s1 as argument return 0; } void Display(struct student stu){ printf("Output\nName: %s",stu.name); printf("\nRoll: %d",stu.roll);
}
Output
Enter student's name: Kevin Amla Enter roll number: 149 Output Name: Kevin Amla Roll: 149
#include <stdio.h> struct distance{ int feet; float inch; }; void Add(struct distance d1,struct distance d2, struct distance *d3); int main() { struct distance dist1, dist2, dist3; printf("First distance\n"); printf("Enter feet: "); scanf("%d",&dist1.feet); printf("Enter inch: "); scanf("%f",&dist1.inch); printf("Second distance\n"); printf("Enter feet: ");
scanf("%d",&dist2.feet); printf("Enter inch: "); scanf("%f",&dist2.inch); Add(dist1, dist2, &dist3); /*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference */ printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch); return 0; } void Add(struct distance d1,struct distance d2, struct distance *d3) { /* Adding distances d1 and d2 and storing it in d3 */ d3->feet=d1.feet+d2.feet; d3->inch=d1.inch+d2.inch; if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */ d3->inch-=12; ++d3->feet; }
}
Output
First distance Enter feet: 12 Enter inch: 6.8 Second distance Enter feet: 5 Enter inch: 7.5 Sum of distances = 18'-2.3"
Explaination In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3 variable in main function.
C Programming Unions
Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct.
int price; }c1, c2, *c3; OR; union car{ char name[50]; int price; }; -------Inside Function----------union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union car is created.
#include <stdio.h> union job { //defining a union char name[32]; float salary; int worker_no; }u; struct job1 { char name[32]; float salary; int worker_no; }s; int main(){ printf("size of union = %d",sizeof(u)); printf("\nsize of structure = %d", sizeof(s)); return 0;
}
Output
But, the memory required to store a union variable is the memory required for largest element of an union.
What difference does it make between structure and union? As you know, all members of structure can be accessed at any time. But, only one member of union can be accessed at a time in case of union and other members will contain garbage value.
#include <stdio.h> union job { char name[32]; float salary; int worker_no; }u; int main(){ printf("Enter name:\n"); scanf("%s",&u.name); printf("Enter salary: \n"); scanf("%f",&u.salary); printf("Displaying\nName :%s\n",u.name); printf("Salary: %.1f",u.salary); return 0; }
Output
Enter name Hillary Enter salary 1234.23 Displaying Name: f%Bary Salary: 1234.2
Note: You may get different garbage value of name.
Initially, Hillary will be stored in u.name and other members of union will contain garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary and other members will contain garbage value. Thus in output, salary is printed accurately but, name displays some random string.
In this program, a structure(Distance) is defined with inch and feet as its members. Then, three variables( d1, d2 and sum) of struct
Distance type is created. Two variables(d1 and d2) are used for taking distance from user and the sum of two distance is stored in
In this program structures n1 and n2 are passed as an argument of function add(). This function computes the sum and returns the structure variable temp to the main() function.
differ->minutes=t1.minutes-t2.minutes; differ->hours=t1.hours-t2.hours;
}
Output
For roll number 1 Enter name: Tom Enter marks: 98 For roll number 2 Enter name: Jerry Enter marks: 89 . . . Displaying information of students: Information for roll number 1: Name: Tom Marks: 98 . . .
Output
Enter n: 2 Enter string and integer respectively: Programming 22 Enter string, integer and floating number Structure 33 Displaying Information: Programming 22 Structure 33
respectively:
C Programming Unions
Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct.
union car{ char name[50]; int price; }c1, c2, *c3; OR; union car{ char name[50]; int price; }; -------Inside Function----------union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union car is created.
Though unions are similar to structure in so many ways, the difference between them is crucial to understand. This can be demonstrated by this example:
#include <stdio.h> union job { //defining a union char name[32]; float salary; int worker_no; }u; struct job1 { char name[32]; float salary; int worker_no; }s; int main(){ printf("size of union = %d",sizeof(u)); printf("\nsize of structure = %d", sizeof(s)); return 0;
}
Output
But, the memory required to store a union variable is the memory required for largest element of an union.
What difference does it make between structure and union? As you know, all members of structure can be accessed at any time. But, only one member of union can be accessed at a time in case of union and other members will contain garbage value.
#include <stdio.h> union job { char name[32]; float salary; int worker_no; }u; int main(){ printf("Enter name:\n"); scanf("%s",&u.name); printf("Enter salary: \n"); scanf("%f",&u.salary); printf("Displaying\nName :%s\n",u.name); printf("Salary: %.1f",u.salary); return 0; }
Output
Enter name Hillary Enter salary 1234.23 Displaying Name: f%Bary Salary: 1234.2
Note: You may get different garbage value of name.
Why this output? Initially, Hillary will be stored in u.name and other members of union will contain garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary and other members will contain garbage value. Thus in output, salary is printed accurately but, name displays some random string.
C Programming Files
In C programming, file is a place on disk where a group of related data is stored.
High level file I/O functions can be categorized as: 1. 2. Text file Binary file
File Operations
1. 2. 3. 4. Creating a new file Opening an existing file Reading from and writing information to a file Closing a file
FILE *ptr;
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
ptr=fopen("fileopen","mode") For Example: fopen("E:\\cprogram\program.txt","w"); /* --------------------------------------------------------- */ E:\\cprogram\program.txt is the location to create file. "w" represents the mode for writing. /* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode. Opening Modes in Standard I/O File Mode Meaning of Mode During Inexistence of file r w a r+ w+ a+ Open for reading. Open for writing. If the file does not exist, fopen() returns NULL. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
Open for append. i.e, Data is added If the file does not exists, it will be created. to end of file. Open for both reading and writing. If the file does not exist, fopen() returns NULL. If the file exists, its contents are overwritten. If the file does Open for both reading and writing. not exist, it will be created. Open for both reading and If the file does not exists, it will be created. appending.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().
Writing to a file
#include <stdio.h> int main() { int n; FILE *fptr; fptr=fopen("C:\\program.txt","w"); if(fptr==NULL){ printf("Error!"); exit(1); } printf("Enter n: "); scanf("%d",&n); fprintf(fptr,"%d",n); fclose(fptr); return 0;
}
This program takes the number from user and stores in file. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open that file, you can see the integer you entered. Similarly, fscanf() can be used to read data from file.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary file. If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used. Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.
File Examples
Examples of files in C Programming C Program to read name and marks of students and store it in file C Program to read name and marks of students and store it in file. If file already exists, add information to it. C Program to write members of arrays to a file using fwrite()
Write a C program to read name and marks of n number of students from user and store them in a file
#include <stdio.h> int main(){ char name[50]; int marks,i,n; printf("Enter number of students: "); scanf("%d",&n); FILE *fptr; fptr=(fopen("C:\\student.txt","w")); if(fptr==NULL){ printf("Error!"); exit(1); } for(i=0;i<n;++i) {
printf("For student%d\nEnter name: ",i+1); scanf("%s",name); printf("Enter marks: "); scanf("%d",&marks); fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks); } fclose(fptr); return 0; }
Write a C program to read name and marks of n number of students from user and store them in a file. If the file previously exits, add the information of n students.
#include <stdio.h> int main(){ char name[50]; int marks,i,n; printf("Enter number of students: "); scanf("%d",&n); FILE *fptr; fptr=(fopen("C:\\student.txt","a")); if(fptr==NULL){ printf("Error!"); exit(1); } for(i=0;i<n;++i) { printf("For student%d\nEnter name: ",i+1); scanf("%s",name); printf("Enter marks: "); scanf("%d",&marks); fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks); } fclose(fptr); return 0; }
Write a C program to write all the members of an array of strcures to a file using fwrite(). Read the array from the file and display on the screen.
#include <stdio.h> struct s { char name[50]; int height; }; int main(){ struct s a[5],b[5]; FILE *fptr; int i; fptr=fopen("file.txt","wb"); for(i=0;i<5;++i) { fflush(stdin); printf("Enter name: "); gets(a[i].name); printf("Enter height: "); scanf("%d",&a[i].height); }
C Programming Enumeration
Enumeration type allows programmer to define their own data type . Keyword enum is used to defined enumerated data type.
4 day
You can write any program in C language without the help of enumerations but, enumerations helps in writing clear codes and simplify programming.
Use of #include
Let us consider very common preprocessing directive as below:
#include <stdio.h>
Here, "stdio.h" is a header file and the preprocessor replace the above line with the contents of header file.
Use of #define
Preprocessing directive #define has two forms. The first form is:
Example of #define
#define c 299792458 /*speed of light in m/s */
The token string in above line 2299792458 is replaced in every occurance of symbolic constant c. C Program to find area of a cricle. [Area of circle=r2]
#include <stdio.h> #define PI 3.1415 int main(){ int radius; float area; printf("Enter the radius: "); scanf("%d",&radius); area=PI*radius*radius; printf("Area=%.2f",area); return 0;
}
Output
Syntactic Sugar
Syntactic sugar is the alteration of programming syntax according to the will of programmer. For example:
#define LT <
Every time the program encounters LT, it will be replaced by <. Second form of preprocessing directive with #define is:
#include <stdio.h> #define PI 3.1415 #define area(r) (PI*r*r) int main(){ int radius; float area; printf("Enter the radius: "); scanf("%d",&radius); area=area(radius); printf("Area=%.2f",area); return 0;
}
#include <stdio.h> int main(){ printf("Current time: %s",__TIME__); //calculate the current time
}
Output
#include <stdio.h> int main() { /* If you write printf() statement without including header file, this program will show error. */ printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which is also a library function). This program is called at program starts. There are many library functions available in C programming to help the programmer to write a good efficient program. Suppose, you want to find the square root of a number. You can write your own piece of code to find square root but, this process is time consuming and the code you have written may not be the most efficient process to find square root. But, in C programming you can find the square root by just using sqrt() function which is defined under header file "math.h"
#include <stdio.h> #include <stdlib.h> /* For exit() function */ int main() { char c[1000]; FILE *fptr; fptr=fopen("program.txt","w"); if(fptr==NULL){ printf("Error!"); exit(1); } printf("Enter a sentence:\n"); gets(c); fprintf(fptr,"%s",c); fclose(fptr); return 0;
}
Output
/* Source Code to read a text of string from a file. */ #include <stdio.h> #include <stdlib.h> /* For exit() function*/ int main() { char c[1000]; FILE *fptr; if ((fptr=fopen("program.txt","r"))==NULL){ printf("Error! opening file"); exit(1); /* Program exits if file pointer returns NULL. */ } fscanf(fptr,"%[^\n]",c); printf("Data from file:\n%s",c); fclose(fptr); return 0;
}
This program reads the content of program.txt file and stores it in a string c if of this file and this c program is same and the name of file matches but, if this there is no file named program.txt then, this program displays Error! opening file and program will be terminated.
Enter two numbers(intervals): 100 400 Armstrong numbers between 100 and 400 are: 153 370 371
In this program, it is assumed that, the user always enters smaller number first. This program will not perform the task intended if user enters larger number first. You can add the code to swap two numbers entered by user if user enters larger number first to make this program work properly.