C Programming
C Programming
C Programming
Introduction
C is a general purpose structured programming language. It is one of the most popular
programming languages.
C was invented and first implemented by Dennis Ritchie on a DEC PDP-II (Digital Equipment
Corporation Programmed Data Processor-II) machine using UNIX operating system in early
1970’s.
C was the result of a development process which started with an older language BCPL (Basic
Combined Programming Language) developed by Martin Richards. BCPL influence a
language called B which was invented by Ken Thompson and which led to development of C.
Features of C
C is a general purpose programming language. C was originally developed for systems
programming. But, later is also used for writing commercial as well as scientific applications.
C is a structured programming language. C provides fundamental flow control constructs
required for well structured programs. It allows developing well-defined, portable and easy to
maintain programs.
C is a middle level language because it combines the elements of high level language with the
functionalities of an assembly language.
C is a portable and efficient language. C programs written for one computer can be executed on
another with little or no modifications. C programs can be easily ported to new hardware or
operating system or both.
C is a modular language. We can break down the program into functional units, develop
independent code and then, integrate them to make a complete application. The different
modules can be present in different files and can be compiled separately, thereby facilitating
team participation in the development.
C allows code reusability. Besides the standard C function library, a programmer can create his
own functions and use them over and over again in different applications.
C Program Structure
a) Function Definition
Every C program is divided into units called functions. A Function is a set of instructions
aimed at achieving a predefined goal or objective.
Every C program must have main() from where the execution starts.
The function body comprises or two parts- variable declarations and executable statements. All
the variables required in the function must be declared before any executable statement.
b) Delimiters
All the statements belonging to a particular block or a function are placed between the opening
brace ‘{‘ and closing brace ‘}’.
c) Statement Terminator
Every statement in a C program is terminated with a semi colon (;)
d) Standard C library
All C compilers use as their first phase of compilation - a pre-processor, which performs
various manipulations on the source file before actually it is compiled.
Pre-processor directives are not actually a part of C program, but rather instructions from us to
the compiler.
The #include directive tells the pre-processor to read-in another file and include it in our
program. The most commonly required header file is ‘stdio.h’ which provides standard
input/output library functions. All header files end with .h extension.
e) Comment lines
Any comment in a C program is placed between ‘/*’ and ‘*/’.
Comments are not the party of the execution of the program.
Variable
A Variable is a named memory location where a value is stored. The value stored in the variable can
be changed during the execution of the program. The memory locations are identified by naming them
and these names are called as identifiers.
Rules for writing Variable names
A variable name can be made of A-Z, a-z, 0-9 and underscore ( _ ). Other than these, no
characters and symbols are allowed to write variable names.
Eg: a, xyz, sum, s123,K_5... are valid
a-b,a*bc, sum of numbers .. are invalid
The first character in the variable must start with an alphabet, not with a numeral.
Eg: 1ab, 123,1_ab .. are invalid
All variable names are case sensitive.
Eg: ABC, abc, Abc, ABc, .. are different from each other
Keywords (Reserved Words), which have a special meaning in C language cannot be used as
variable names. C provides 32 keywords. They are
int char float double unsigned signed long short
const if else switch case default for while
do auto static extern register break continue goto
struct union enum return volatile sizeof typedef void
Data Type
The data type of a variable specifies the type of value a variable can store. C provides four basic data
types – int, char,, float and double
Data Type Memory(in bytes) Storage
int 2 Integers
char 1 Single Character
float 4 Decimal numbers up to 6 digits of precision
Double 8 Decimal numbers up to 14 digits of precision
Modifiers
Modifiers are used to alter the meaning of the basic data type to fit for various situations more
precisely. They are short/long, signed/unsigned.
Type Size(in bits) Range
char or signed char 8 -128 to 127
unsigned char 8 0 to 255
short int or signed short int or int or signed int 16 -32768 to 32767
unsigned int or unsigned short int 16 0 to 65535
long int ot signed long int 32 -2147483648 to 2147483648
unsigned long int 32 0 to 4294967295
Float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 3.4E+4932
Format Specifiers
Format Specifiers determines the data type for the variable that is used in printf() and scanf()
statements. They are
Code Description Code Description
%c Single Character %s Group of Characters(String)
%d Decimal Integer %o Octal form
%x Hexa-Decimal form(lower case) %X Hexa-Decimal form(Upper case)
%f Signed floating point numbers %e Signed exponent notation(lower case)
%E Signed exponent notation %g,%G Most compact form of e, E, f
(Upper Case)
%u Unsigned decimal short int %U Unsigned decimal long int
Additional Modifiers
h -> for short int used along with d, i, o, x, X eg: %hd, %hi, ...
l -> for long int used along with d, i, o, x, X eg: %ld, %o, ...
for unsigned long int used long with U eg: %lU
for double used along with e, E, f, g, G eg: %le, %lE, %lg ...
L -> for long double used along with e, E, f, g, G eg: %le, %LE, %LG ...
/*C program to read and display a character using unformatted I/O functions*/
main()
{
char ch;
puts(“Enter a character:”);
ch=getchar();
putchar(ch);
puts(“Enter a character:”);
ch=getche();
putchar(ch);
puts(“Enter a character:”);
ch=getch();
putchar(ch);
}
Operators in C
C Provides potent set of operators to perform different operations. Operators act upon operands to
produce desired results.
Eg: c= a + b is an expression in which a, b, c are operands and =, + are operators.
Assignment Operator (=): The assignment operator ‘=’ is used to assign values to variables. The
value on the right side of the operator is assigned to the variable on its left.
Eg: pi=3.14; b=3+a; x=y+z;
Binary Operators
Binary operators act upon two operands
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division (remainder)
/*program to read two numbers and find their /*program to find the area and perimeter of
sum */ rectangle */
main() main()
{ {
int a,b,s; int l,b,p,a;
printf(“Enter two numbers:”); printf(“Enter length and breadth:”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&l,&b);
s=a+b; a=l*b;
printf(“Sum=%d”,s); p=2*(l+b);
} printf(“Area=%d Perimeter=%d”,a,p);
}
/*program to find the area and perimeter of /*program to find the area and circumference of a
square */ circle */
main() main()
{ {
int s,p,a; float r,a,c;
printf(“Enter side:”); const float pi=3.14;
scanf(“%d”,&s); printf(“Enter radius of circle:”);
a=s*s; scanf(“%f”,&r);
p=4*s; a=pi*r*r;;
printf(“Area=%d Perimeter=%d”,a,p); c=2*pi*r;
} printf(“Area=%f Circumference=%f”,a,c);
}
/*program to find the volume of a cuboid */ /*program to find the area of triangle */
main() main()
{ {
float l,b,h,v; float b,h,a;
printf(“Enter length breadth height of a cuboid:”); printf(“Enter base and height of triangle:”);
scanf(“%f%f%f”,&l,&b,&h); scanf(“%f%f”,&b,&h);
v=l*b*h; a=1/2*b*h;
printf(“Volume=%f”,v); printf(“Area=%f”,a);
} }
/*program to find the volume of a cube */ /*program to find Simple Interest */
main() main()
{ {
float s,v; float p,r,t,si;
printf(“Enter side of a cube:”); printf(“Enter Principle Rate and Time:”);
scanf(“%f”,&s); scanf(“%f%f%f”,&p,&r,&t);
v=s*s*s; si=p*t*r/100;
printf(“Volume=%f”,v); printf(“Simple Interest=%f”,v);
} }
Constant
To assign a value to a variable that cannot be changed during the execution of the program, precede its
definition with a keyword ‘const’ . Syntax:: const type variable=value;
Eg; const int i=10; const float pi=3.14; const char ch=’c’;
Relational Operators
Relational operators are used to compare two quantities. Comparison is made to take a certain decision
depending upon the relationship between two quantities.
An expression containing a relational operator is known as relational expression. It always evaluate to either
true (non-zero) or false (zero).
Logical operators
Logical operators are used to combine two or more relational expressions into one relational expression. An
expression of this kind which combines two or more relational expressions is termed as logical expression or
compound relational expression. Similar to simple relational expression, the logical expression also evaluates to
either true (non-zero) or false (zero)
Ternary Operator
Ternary operator is also known as Conditional Operator. This operator takes the form
Syntax:: <expression 1> ? <expression 2> : <expression 3>
Here, upon evaluation of expression 1, if the result is true, expression 2 is evaluated. Otherwise expression 3 is
evaluated.
/* program to check whether the given number is less /* program to check whether the given number
than 100 or not */ is Even or Odd */
main() main()
{ {
int n; int n;
printf(“\n enter a number:”); printf(“\n enter a number:”);
scanf(“%d”, &n); scanf(“%d”, &n);
n<100?printf(“Given number is less than 100”) : n%2==0?printf(“Given number EVEN”):
printf(“Given number is not less than 100”); printf(“Given number is ODD”);
} }
/* program to find the biggest of three different /* program to find the smallest of five numbers
numbers */ */
main() main()
{ {
int a,b,c; int a,b,c,d,e;
printf(“\n enter three different numbers:”); printf(“\n enter five different numbers:”);
scanf(“%d%d%d”, &a,&b,&c); scanf(“%d%d%d%d%d”, &a,&b,&c,&d,&e);
a>b && a>c ? printf(“%d is big”,a): b>c ? printf(“%d is a=a<b?a:b;
big”,b):printf(“%d is big”,c); a=a<c?a:c;
} a=a<d?a:d;
a=a<e?a:e;
printf(“Small=%d”,a);
}
Comma Operator
It can be used to link the related expressions together. A comma-linked list of expressions is evaluated left to
right. The value of the right most expression is the value of the combined expression.
Eg: in a, b, c;
c = (a=10, b=20,a+b); /* c is assigned with value 30 */
sizeof operator
It is used to return the size of operand in bytes
i) Selection Constructs
Selection Constructs are used whenever a selective part of the code is to be executed. C provides two types of
selection constructs a) if b) switch .. case
if constructs
The ‘if’ statement is used to test the validity of condition
Syntax: if(<condition>)
{
Statements;
}
In the above syntax, if the condition that is placed within the parenthesis is true, the set of statements placed
under it within the braces are executed. Otherwise, those statements are skipped and the control jumps to next
statement after the closing brace.
In the above syntax, if the condition is true, the statements written under the ‘if’ block is executed. Otherwise,
the statements written under ‘else’ block is executed.
/*Program to check whether a given number is less /*Program to check whether a given number is
than 100 or not */ EVEN or ODD */
main() main()
{ {
int i; int i;
printf(“Enter a number:”); printf(“Enter a number:”);
scanf(“%d”,&i); scanf(“%d”,&i);
if(i<100) if(i%2==0)
{ {
printf(“Given number is less than 100”); printf(“Given number is EVEN”);
} }
else else
{ {
printf(“Given number is not less than 100”); printf(“Given number is ODD”);
} }
} }
/*Program to read two different numbers and find /*Program to read two different numbers and find
the smallest */ whether first number is factor of second number */
main() main()
{ {
int i,j; int i,j;
printf(“Enter two different numbers:”); printf(“Enter two non-zero numbers:”);
scanf(“%d%d”,&i,&j); scanf(“%d%d”,&i,&j);
if(i<j) if(j%i==0)
{ {
printf(“%d is smallest”,i); printf(“%d is a factor of %d”,i,j);
} }
else else
{ {
printf(“%d is smallest”,j); printf(“%d is not a factor of %d”,i,j);
} }
} }
/*Program to read two numbers and find the quotient and remainder */
main()
{
int i,j;
printf(“Enter two different numbers:”);
scanf(“%d%d”,&i,&j);
if(j==0)
{
printf(“Division not possible”);
}
else
{
printf(“Quotient=%d Remainder=%d”,i/j, i%j);
}
}
nested if
An ‘if’ construct can be nested in another ‘if’ as follows
Syntax: if(<condition>)
{
---
if(<condition>)
{
---
}
else
{
---
}
---
}
else
{
---
if(<condition>)
{
---
}
else
{
---
}
---
}
else... if ladder
The ‘else..if’ ladder is used when multiple path decisions are involved. A multi path decision is a chain of ‘if’
statements where all the ‘else’ clause is followed by another ‘if’ statement.
Syntax: if(<codition>)
{
Statements;
}
else if(<condition>)
{
Statements;
}
---
else
{
Statements;
}
/* Program o compare two numbers */ /* Program to find biggest of three different
main() numbers */
{ main()
int a,b; {
printf(“\n Enter two numbers:); int a,b,c;
scanf(“%d%d”,&a,&b); printf(“\n Enter three numbers:);
if(a>b) scanf(“%d%d%d”,&a,&b,&c);
printf(“% is greater than %d”,a,b); if(a>b && a>c)
else if(a<b) printf(“%d is big”,a);
printf(“% is less than %d”,a,b); else if(b>c)
else printf(“% is big”,b);
printf(“% is equal to %d”,a,b); else
} printf(“%d is big”,c)
}
main() main()
{ {
int a,b,ch; int a,b;
printf(“\n Enter two numbers:”); char ch;
scanf(“%d%d”,&a,&b); printf(“\n Enter two numbers:”);
printf(“\n1. Addition \n 2.Subtraction \n scanf(“%d%d”,&a,&b);
3.Multiplication \n 4.Division \n 5.Modulo Division”); printf(“\n Addition \n Subtraction \n Multiplication
printf(“\n\n Enter your choice:”); \nDivision \n Modulo Division”);
scanf(“%d”,&ch); printf(“\n\n Enter your choice A S M Q R:”);
ch=getche();
if(ch==1)
printf(“Sum=%d”,a+b); if(ch==’A’ || ch==’a’) /*if(toupper(ch)==’A’) */
else if(ch==2) printf(“Sum=%d”,a+b);
printf(“Difference=%d”,a-b); else if(toupper(ch)==’S’)
else if(ch==3) printf(“Difference=%d”,a-b);
printf(“Product=%d”,a*b); else if(toupper(ch)==’M’)
else if(ch==4) printf(“Product=%d”,a*b);
{ else if(toupper(ch)==’Q’)
if (b==0) {
printf(“Division not possible with zero”); if (b==0)
else printf(“Division not possible with zero”);
printf(“Quotient=%d”,a/b); else
} printf(“Quotient=%d”,a/b);
}
else if(ch==5) else if(toupper(ch)==’R’)
{ {
if (b==0) if (b==0)
printf(“Division not possible with zero”); printf(“Division not possible with zero”);
else else
\ printf(“Remainder=%d”,a%b); \ printf(“Remainder=%d”,a%b);
} }
else else
printf(“Invalid Choice”); printf(“Invalid Choice”);
} }
switch .. case construct
It is a multi-way decision construct that tests whether the expression matches one of the number of constant
values and branches the control accordingly.
/* Program to display the name of the week basing /*Program to check whether a given character is
on the weekday number */ vowel or not */
main() main()
{ {
int n; char ch;
printf(“Enter the weekday number:”): printf(“Enter a character:”);
scanf(“%d”, &n) ch=getche();
switch(n) switch(toupper(ch))
{ {
case 1: printf(“MONDAY”); case ‘A’:
break; case ‘E’:
case 2: printf(“TUESDAY”); case ‘I’:
break; case ‘O’:
case 3: printf(“WEDNESDAY”); case ‘U’:printf(“Vowel”);
break; break;
case 4: printf(“THURSDAY”); default: printf(“Not a vowel”);
break; }
case 5: printf(“FRIDAY”); }
break;
case 6: printf(“SATURDAY”);
break;
case 7: printf(“SUNDAY”);
break;
default: printf(“Invalid choice”);
}
}
/*Program to perform arithmetic operation based /* Program to display the number od days of a
on the choice entered */ month */
main() #include<stdio.h>
{ #include<conio.h>
int a,b,ch;
void main()
printf(“\n Enter two numbers:”);
{
scanf(“%d%d”,&a,&b);
printf(“\n1. Addition \n 2.Subtraction \n int m,y;
3.Multiplication \n 4.Division \n 5.Modulo Division”); printf("\n Enter the month No.:");
printf(“\n\n Enter your choice:”); scanf("%d",&m);
scanf(“%d”,&ch); if(m==2)
switch(ch) {
{ printf("\nEmter year:");
case 1:printf(“Sum=%d”,a+b); scanf("%d",&y);
break;
if(y%4==0 && y%100!=0 || y%400==0)
case 2:printf(“Difference=%d”,a-b);
printf("Leap Year. No. of days=29");
break;
case 3:printf(“Product=%d”,a*b); else
break; printf("Non-Leap Year. No. of days=28");
case 4: if (b==0) }
printf(“Division not possible with zero”); else
else {
printf(“Quotient=%d”,a/b); switch(m)
break; {
case 5: if (b==0) case 1:
printf(“Division not possible with zero”); case 3:
else
case 5:
printf(“Remainder=%d”,a%b);
case 7:
default:printf(“Invalid Choice”);
} case 8:
} case 10:
case 12:printf("No. of days=31");
break;
case 4:
case 6:
case 9:
case 11:printf("No. of days=30");
break;
default:printf("Invalid number");
}
}
getch();
}
Iteration Constructs
Iteration means repeation. In ‘C’ language, iteration constructs are used to repeat a block of
statement(s) for a certain number of times or until a condition is met. Iteration constructs are also
called as looping constructs. In looping, a sequence of statements is executed util some condition for
the termination of loop is satisfied. C provides three types of looping constructs – for, while, do..while.
for construct
for is used when we want to execute a loop for a fixed number of times.
Syntax:: for(initialization; condition checking; re-evaluation parameters)
{
Statements;
}
The initialization part usually consists of an assignment that is done before the execution of the
loop.
The loop is executed as long as the condition is true
The re-evaluation parameter is an assignment expression that increase or decreases the value
of the loop counter
The three expressions in the loop are separated by semi-colon(;)
/* Program to display a string 10 times */ /* Program to display a first 10 natural
main() numbers */
{ main()
int i; {
for(i=1;i<=10;i++) int i;
{ for(i=1;i<=10;i++)
printf(“\n C programming”); {
} printf(“%4d”, i));
} /* %4d leaves 4 spaces between each output */
}
}
/* Program to display a first n natural /* Program to display all even numbers below
numbers */ 100 */
main() main() main()
{ { {
int i,n; int i; int i;
printf(“Enter value of n:”); for(i=1;i<100;i++) for(i=2;i<100;i+=2)
scanf(“%d”,&n); if(i%2==0) printf(“%4d”,i);
for(i=1;i<=n;i++) printf(“%4d”,i); }
{ } }
printf(“%4d”, i)); }
}
}
/* Program to display the multiplication table /* Program to display all ODD numbers below
of a given number up to a given range*/ 100 in reverse order */
main()
{ main() main()
int n,m,i; { {
printf(“Enter number & range”); int i; int i;
scanf(“%d%d”,&n,&m); for(i=99;i>0;i--) for(i=99;i>100;i-=2)
for(i=0;i<=m;i++) if(i%2!=0) printf(“%4d”,i);
printf(“\n%d * %d = %d”,n,i,n*i); printf(“%4d”,i); }
} } }
}
/* Program to count the number of factors of a /* Program to display the factors of a given
given number*/ number*/
main() main() main() main()
{ { { {
int n,i,c=0; int n,i,c=0; int n,i; int n,i;
printf(“Enter a printf(“Enter a printf(“Enter printf(“Enter
number:”); number:”); number:”); number:”);
scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n);
for(i=1;i<=n;i++) for(i=1;i<=n/2;i++) for(i=1;i<=n;i++) for(i=1;i<=n/2;i++)
if(n%i==0) if(n%i==0) if(n%i==0) if(n%i==0)
c++; c++; printf(“%d”,i); printf(“%d”,i);
printf(“Number of printf(“Number of } printf(“%d”,n);
factors=%d”,c); factors: %d”,c+1); }
} }
‘break’
break statement is not only used in switch-case construct but also in looping a construct so as to break
a loop and come out of the loop to the next statement after the construct, not allowing further
iterations.
/* Program to check whether a /*Program to find the sum of /*Program to find the sum of
given number is perfect first 10 natural numbers */ 10 different numbers */
number or not */ main() main()
main() { {
{ int i,sum=0; int n,i,sum=0;
int n,i,c=0; for(i=1;i<=10;i++) for(i=1;i<=10;i++)
printf(“Enter number:”); sum+=i; {
scanf(“%d”,&n); printf(“SUM of forst 10 printf(“\n Enter a number:”);
for(i=1;i<=n/2;i++) numbers is %d”,sum); scanf(“%d”,&n);
if(n%i==0) } sum+=n;
c+=i; }
if(c==n) printf(“SUM =%d”,sum);
printf(“PERFECT NUMBER”); }
else
printf(“NOT A PERFECT
NUMBER”):
}
Nested for
A ‘for’ construct can be nested in another ‘for’ construct as follows
for(...) /* outer for */
{
---
for(---) /*inner for */
{
---
}
---
}
In such case, the control will go to the next iteration of the outer for once it completes the iterations of
inner for. For the next iteration of outer for, the inner for is executed again and the same process is
continued till all the iterations of the outer for are completed.
a) 11111 b) 12345 c) * c) *
22222 23456 ** **
33333 34567 *** ***
44444 45678 **** ****
55555 56789 ***** *****
main() main() main() main()
{ { { {
int i,j; int i,j; int i,j; int i,j,k;
for(i=1;i<=5;i++) for(i=1;i<=5;i++) for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ { { {
for(j=1;j<=5;j++) for(j=i;j<=i+4;j++) for(j=1;j<=i;j++) for(j=1;j<10-i;;j++)
printf(“%d ”,i); printf(“%d ”,j); printf(“* ”,i); printf(“ “);
printf(“\n”); printf(“\n”); printf(“\n”); for(k=1;k<=i;k++)
} } } printf(“* ”);
} } } printf(“\n”);
}
}
/* program to display the factors of a numbers /* program to print all prime numbers below
from 1 to a given number */ 100*/
main() main()
{ {
int i,j,n; int n,i,c;
printf(“\n Enter a number:”); for(n=2;n<100;n++)
scanf(“%d”,&n); {
for(i=1;i<=n;i++) c=0;
{ for(i=2;i<=n/2;i++)
printf(“Factors of %d are:”,i); if(n%i==0)
for(j=1;j<=i./2;j++) {
if(i%j==0) c++;
printf(“%2d”,j); break;
printf(“%2d”,i); }
} if(c==0)
} printf(“%2d”,n);
}
}
‘continue’
The continue statement is used in loop so as to make the control jump to next iteration without further
processing the statements in the loop.
/* Program to display all numbers below 100 which are not multiples of 5 */
main()
{
int i;
for(i=1;i<100;i++) /* In the program, when the condition i%5==0 is true, the control jumps to the
{ nest iteration without executing the printf() statement in the for loop */
if(i%5==0)
continue;
printf(“%4d”,i);
}
}
‘while’ construct ‘do.. while’ construct
It is the simplest of looping constructs available to
In ‘do..while’ construct, the body of the loop is
a programmer in C. executed and then the condition is checked for
Syntax :: while(<condition>) next iteration. If the condition is true, the control
{ goes to the next iteration otherwise, terminates
Statements; from the loop.
} Syntax:: do
{
In this construct, the body of the loop is executed Statements;
only when the condition is true } while(<condition>);
main() main()
{ {
int i=1; int i=11;
while(i<=10) do
{ {
printf(“%4d”, i); printf(“%4d”, i);
i++; i++;
} } while(i<=10)
printf(“\nEnd”); printf(“\nEnd”);
} }
Output: End Output: 11
End
/*Program to find the sum of digits of a given /*Program to find lucky number */
number */ main()
main() {
{ int n,r,s=0;
int n,r,s=0; printf(“\n Enter a Number:”);
printf(“\n Enter a Number:”); scanf(“%d”,&n);
scanf(“%d”,&n); while(n!=0).
while(n!=0) {
{ while(n!=0)
r=n%10; {
s=s+r; r=n%10;
n=n/10; s=s+r;
} n=n/10;
printf(“\nSum=%d”,s); }
} if(s>=10)
n=s;
}
printf(“\nSum=%d”,s);
}
/*Program to reverse a given number */ /*Program to check whether a given number is
main() palindrome or not */
{ main()
int n,r,s=0; {
printf(“\n Enter a Number:”); int n,t,r,s=0;
scanf(“%d”,&n); printf(“\n Enter a Number:”);
while(n!=0) scanf(“%d”,&n);
{ t=n;
r=n%10; while(n!=0)
s=s*10+r; {
n=n/10; r=n%10;
} s=s*10+r;
printf(“\nReverse of a given number=%d”,s); n=n/10;
} }
if (s==t)
printf(“\nNumber is PALINDROM”);
else
printf(“\nNumber is NOT A PALINDROM”);
}
/*Program to print nth Fibonacci numbers */ /*Program to print first n Fibonacci numbers
main() */
{ main()
int a=1,b=0,count=1,n; {
printf(“\nwhich fibo number you want:”); int a=1,b=0,count=1,n;
scanf(“%d”,&n); printf(“\nHow many numbers you want:”);
do scanf(“%d”,&n);
{ do
printf(“%d”,a); {
c=a+b; printf(“%d”,a);
b=a; c=a+b;
a=c; b=a;
count++; a=c;
}while(count <n) count++;
printf(“%d”,a); }while(count <=n)
} }
/*Program to check whether a given number is /*Program to find the GCD of two numbers */
Armstrong number or not */ main()
main() {
{ int a,b,r;
int n,t,r,s=0; printf(“\n Enter two non-zero numbers:”);
printf(“\n Enter a Number:”); scanf(“%d%d”,&a,&b);
scanf(“%d”,&n); do
t=n; {
while(n!=0) c=a%b;
{ if(c==0)
r=n%10; {
s=s+r*r*r; printf(“GCD=%d”,b);
n=n/10; exit(0);
} }
if (s==t) c=b;
printf(“\nNumber is ARMSTRONG”); b=c;
else }
printf(“\nNumber is NOT AN ARMSTRONG”); }
}
/*Program to print all palindrome numbers /*Program to print all armstrong numbers
below 1000 */ below 1000 */
main() main()
{ {
int n,t,r,s=0; int n,t,r,s=0;
for(n=1;n<1000;n++) for(n=1;n<1000;n++)
{ {
t=n t=n;
while(t!=0) while(t!=0)
{ {
r=t%10; r=t%10;
s=s*10+r; s=s+r*r*r;
t=t/10; t=t/10;
} }
if (s==n) if (s==n)
printf(“%5d”,n); printf(“%5d”,n);
} }
} }
exit() goto
The exit() is used to terminate from program The goto statement is used make the control jump
Syntax: exit(int); to a particular label in the program
/* Program to demonstrate exit() */ Syntax: goto <label name>;
main() /*Program to demonstrate goto */
{ main()
int a,b; {
printf(“Enter two numbers:”); int n,i;
scanf(“%d”%d”,&a,&b); printf(“\n Enter range:”);
if(b==0) scanf(“%d”,&n);
{ i=1;
printf(“Division not possible”); NUM:
exit(1); printf(“%d”,i++);
} if(i<=n)
printf(“Quotient=%d Remainder=%d”,a/b/a%b); goto NUM;
} }
Functions
A function is a set of programming statements aimed at achieving a desired task.
Syntax :: return_type function_name(parameter list)
{
/* Body of the function */
}
A function declaration in ‘C’ consists of a function name followed by a pair of parenthesis(). The
parenthesis can contain an optional list of parameters whose values are passed through a function call.
The body of the function is closed within braces.
A function can have an optional ‘return’ statement. The return type of a function specifies the type of
value that a function can return to the calling function.
Note: A function call is made as - function_name(<arguments>);
A function that invokes another function is called as a calling function. The function that being
invoked is termed as a called function.
Types of functions
C provides two types of functions namely In-built functions and User-defined functions.
In-built functions, also known as Library functions, are available to a program in the standard
C library.
User-defined functions are those functions that are written by the programmer to achieve
desired results.
Advantages of functions
Functions are easy to define and use.
Functions facilitate the modular programming technique.
Functions can be used to divide large bulky program into functionally independent modules or
sub-programs that can be tested, debugged and maintained independently.
The user-defined functions can be made a part of library which in turn facilitates the usage of
those functions across various other C programs. Thereby this feature saves the time of
writing the functions again.
Function Prototyping
It is the process of declaring a function before actually defining it. In function prototype, we specify
the function name, its return-type and the parameters it takes. A prototype merely specifies the
function interface, not the body of the function.
Note: A calling function can send a package of values to the called function to operate on. Each value
passed to a function in such manner is known as argument.
Syntax :: function_name(<arg_1>,<arg_2>, ...);
There is no limitation to the number of arguments that are passed to a user-defined function and these
arguments are separated by commas.
Arrays
An array is a collection of data elements of same type referenced by a common name. Elements are
called the members of the array. Each member is identified by the array name followed by unique
index which starts with zero.
Syntax: datatype arrayname[size];
Eg: int a[10];
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
int a[]={1,2,3} 1 2 3
a[0] a[1] a[2]
int a[5]={1,2} 1 2 0 0 0
a[0] a[1] a[2] a[3] a[4]
/*Program to read 10 numbers into an array /*Program to read n numbers into an array
and display */ and display */
main() main()
{ {
int a[10],i; int a[30],i,n;
printf(“\n Enter 10 numbers:”); printf(“How many numbers you want to print:”);
for(i=0;i<10;i++) scanf(“%d”,&n);
{ printf(“\n Enter %d numbers:”,n);
printf(“\n Enter No:”); for(i=0;i<n;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter No:”);
for(i=0;i<10;i++) scanf(“%d”,&a[i]);
printf(“%5d”,a[i]); }
} for(i=0;i<n;i++)
printf(“%5d”,a[i]);
}
/*Program to find sum of 10 numbers in an /*Program to find the maximum and minimum
array */ of 10 numbers in an array */
main() main()
{ {
int a[10],i,sum=0; int a[10],i,min,max;
printf(“\n Enter 10 numbers:”); printf(“\n Enter 10 numbers:”);
for(i=0;i<10;i++) for(i=0;i<10;i++)
{ {
printf(“\n Enter No:”); printf(“\n Enter No:”);
scanf(“%d”,&a[i]); scanf(“%d”,&a[i]);
sum=sum+a[i]; }
} min=max=a[0];
printf(“Sum = %d”,sum); for(i=0;i<10;i++)
} {
if(a[i]<min)
min=a[i];
else if(a[i]>max)
max=a[i];
}
printf(“Minimum=%d Maximum=%d”,min,max);
}
/*Program to read 10 characters into an array /* Program to find the sum of numbers in ODD
and display along with their ASCII values */ places and sum of numbers in even places */
main() main()
{ {
char a[10]; int a[10]={1,2,3,4,5,6,7,8,9,10},i,so=0,se=0;
int i;
printf(“\n Enter 10 characters:”); for(i=0;i<10;i++)
for(i=0;i<10;i++) {
{ if((i+1)%2==0)
printf(“\n Enter a character:”); so+=a[i];
a[i]=getche(); else
} se+=a[i];
for(i=0;i<10;i++) printf(“\nSum of odd Numbers: %d
printf(“%c --- %d”,a[i],a[i]); \nSum of even Numbers: %d”, so,se);
} }
String/Character Arrays
A string can be defined as character type array which is teriminated by a NULL character (‘\0’).
Note: Strings are the only character constants in C language that are enclosed in double quotes (“ ”).
/*Program to find the length of a given string*/ /*Program to copy the contents of one string
main() into another string */
{ main()
char str[20]; {
int len=0,i; char str1[20],str2[20];
printf(“\n Enter a string”); int i;
gets(str); printf(“\n Enter a string”);
for(i=0;str[i]!=’\0’;i++) gets(str1);
len++; for(i=0;str1[i]!=’\0’;i++)
printf(“Length of given string=%d”,len); str2[i]=str1[i];
} str2[i]=’\0’;
printf(“Copied String= %s”,str2);
}
/*Program to concatenate two strings */ /*Program to compare two string */
main() main()
{ {
char str1[20],str2[20]; char str1[20],str2[20];
int i,j; int i,i;
printf(“\n Enter two strings”); printf(“\n Enter two strings”);
gets(str1); gets(str1);
for(i=0;str1[i]!=’\0’;i++); for(i=0;str1[i]==str2[i] && str1[i]!=’\0’;i++);
for(j=0;str[j]!=’\0’,j++,i++) if(str1[i]<str2[i])
str1[i]=str2[j]; printf(“\n str1 is less than str2”);
str1[i]=’\0’; else if(str1[i]>str2[i])
printf(“Concatenated String= %s”,str1); printf(“\n str1 is greater than str2);
} else
printf(“Both are equal”);
}
/* Program to reverse a given string */ /* Program to check whether a given string is
main() palindrome or not */
{ main()
char str[20],ch; {
int len,i,m; char str[20],ch;
printf(“\n Enter a string”); int len,i,m;
gets(str); printf(“\n Enter a string”);
printf(“\nBefore reverseing: %s”,str); gets(str);
for(len=0;str[len]!=’\0’;len++); printf(“\nBefore reverseing: %s”,str);
m=len/2; for(len=0;str[len]!=’\0’;len++);
len--; m=len/2;
for(i=0;i<m;i++,len--) len--;
{ for(i=0;i<m;i++,len--)
ch=str[i]; {
str[i]=str[len]; if(str[i]!=str[len]
str[len]=ch; {
} printf(“\n Not a palindrome”);
printf(“\nAfter reverseing: %s”,str); exit(0);
} }
}
printf(“\nPalindrom”);
}
/* Program to find the occurrence of a /* Program to find the occurrence of a sub-
character in a given String */ string in a given String */
main() #include<stdlib.h>
{ main()
char str[20],ch; {
int i; char str[20],ch[10];
printf(“\n Enter a string”); int l1,l2,i,j,c;
gets(str); printf("\n Enter a string");
printf(“\n Enter a character:”); gets(str);
ch=getche(); printf("\n Enter sub-string:");
for(i=0;str[i]!=’\0’;i++); gets(ch);
{ for(l1=0;str[l1]!='\0';l1++);
if(ch==str[i]) for(l2=0;ch[l2]!='\0';l2++);
{ for(i=0;i<l1;)
printf(“%c found at position %d”,ch,(i+1)); {
exit(0); j=c=0;
} while(ch[j]==str[i] && str[i]!='\0')
} {
printf(“\n Character Not found”); c++;
} i++;
j++;
}
if(c==l2)
{
printf("%s found in %s at %d position",ch,str, i-
l2+1);
exit(1);
}
else i++;
}
printf("Sub-string not found");
}
/* Program to find the total occurrence of a /* Program to find the occurrence of a sub-
character in a given String */ string in a given String */
main() #include<stdlib.h>
{ main()
char str[20],ch; {
int i,c=0; char str[20],ch[10];
printf(“\n Enter a string”); int l1,l2,i,j,c1,c2;
gets(str); printf("\n Enter a string");
printf(“\n Enter a character:”); gets(str);
ch=getche(); printf("\n Enter sub-string:");
for(i=0;str[i]!=’\0’;i++); gets(ch);
{ for(l1=0;str[l1]!='\0';l1++);
if(ch==str[i]) for(l2=0;ch[l2]!='\0';l2++);
c++; for(i=0;i<l1;)
} {
printf(“\n No. of times %c found in %s : %d”, ch, j=c1=0;
str, c); while(ch[j]==str[i] && str[i]!='\0')
} {
c1++;
i++;
j++;
}
if(c1==l2)
{
c2++;
c1=0;
}
else i++;
}
printf(“\n No. of times %s found in %s : %d”, ch,
str, c2);
Multi-Dimensional Arrays
A multi-dimensional array is an array of single dimensional arrays. Multi-dimensional arrays make it
easier to represent multi-dimensional objects such as graphs, matrices etc,. Each element is identified
with its row and column values.
Recursion
Recursion is the process of defining something in terms of itself. A function is said to recursive if a
statement in the body of the function calls itself.
Recursive functions can be effectively used to solve problems where the solution is expressed in terms
of successively applying the same solution to the subsets of the problem.
Eg.
main()
{
fun();
}
func()
{
printf(“\n Recursive Function”);
fun();
}
In the above program, the function will never terminate because a condition is not mentioned so as to go
back to the calling function. Therefore, when we write recursive functions, we must have an ‘if’
statement somewhere in the body of the function to force the function to return to the calling function
without executing the recursive calls again at some point of time.
Fibonacci series
1 1 2 3 5 8 13 21 ...
fibo(1) = fact(2) = 1
fact(3) = fibo(2) + fibo(1)
fact(4) = fibo(3) + fibo(2)
fact(n) = fibo(n-1) + fact(n-2)
/*Printing nth Fibonacci number using /*Printing first n Fibonacci numbers using
recursion*/ recursion*/
main() main()
{ {
int n; int n,i;
printf(“Enter a number:”); printf(“Enter a number:”);
scanf(%d”,&n); scanf(%d”,&n);
printf(“% d fibinacci number is %d”, n,fibo(n)); for(i=1;i<=n;i++)
} printf(“% d fibinacci number is %d”, n,fibo(i));
fibo(int n) }
{ fibo(int n)
if(n==1 || n==2) {
return(1); if(n==1 || n==2)
else return(1);
return(fibo(n-1) + fact(n-2)); else
} return(fibo(n-1) + fact(n-2));
}
Pointers
A pointer is a variable that holds the memory address of another variable. Pointers provide a way to
access a variable without referring to the variable directly.
Syntax: datatype *ptr_var_name;
Eg: int i,*p
p= &i; &-> specifies address of i.
Note: *p indicates value stored at the address in p.
main() Output
{
int i=10,*p;
p=&i;
printf(“\nAddress of i;%u”,&i); /* Address of i */
printf(“\nAddress of i using p;%u”,p); /* Address of i */
printf(“\nAddress of p;%u”,&p); /* Address of p */
printf(“\nValue in i;%d”,i); /* value in i =10*/
printf(“\nValue in i using p:%d”,*p); /* value in i using p=10*/
printf(“\nvalue in p;%u”,p); /* value in p = address of i*/
}
Applications of pointers
Pointers are used to return more than onle value from a function.
Pointers are used to pass arrays and strings from one function to another.
Pointers are used to allocate memory and access it.
Pointers are used to create complex data structures.
Note 1: A ‘NULL’ value can be assigned to a pointer either through a figurative constant or ‘0’.
int *p= NULL; or int *p=0;
Note 2: The declaration of int *p means p can hold the address of an integer variable only.
Pointer Arithmetic
Addition and subtraction are the only operations which can be performed on pointers.
Eg: int i=10,*p; address of i=1023(say). Integer occupies two bytes of memory i.e, 1023 & 1024.
p=&i; p contains 1023.
p=p+1; p points to next integer location i.e, 1025
p=p-1 p points to previous integer location i.e, 1023
To increment the value i i++ or (*p)++ ++i or ++*p i=i+1 or *p=*p+1
Comparison of pointers
We can compare two addresses stored in two pointers.
Eg: Assume p and q are two pointers storing the address of two integer locations
p<q => p has the address which comes before in memory than the address in q
p>q => p has the address which comes after in memory than the address in q
p==q => p and q points to same location in memory. i.e, they posses same address
Pointers and Single Dimension Array
In a single dimension array, an array name is actually a pointer to the first element in that array
Eg: int a[10];
Element Address Value
st
1 &a[0] or a a[0] or *a
2nd &a[1] or a+1 a[1] or *(a+1)
rd
3 &a[2] or a+2 a[2] or *(a+2)
...
th
n &a[n-1] or a+(n-1) a[n-1] or *(a+(n-1))
Address of an element can be expressed in two ways
By writing the actual array element preceded by &
Writing an expression in which the array subscript is added to the array name.
Eg: main()
{
int a[10] = {2,4,6,8,1,3,5,7,9,0}, i;
for(i=0;i<10;i++)
{
printf(“\n Address: &a[%d] = %u a+%d = %u”, i,&a[i],i,a+i);
printf(“\n Value: a[%d] = %d *(a+%d) = %d”, i,a[i],i,*(a+i));
}
Note: when you pas an array as an argument to a function, only the name of the array is mentioned in the
function call. As the array name itself contains the address of the first location, a new array is not created
in the function definition. In fact, it points to the same array which has been created in calling function.
Eg: int i;
main() Output
{
int a[10] = {2,4,6,8,1,3,5,7,9,0};
display(a);
for(i=0;i<10;i++)
printf(“%4d”, a[i]); 3 5 7 9 2 4 6 8 10 1
}
display(int *ary)
{
for(i=0;i<10;i++)
{
printf(“%4d”, ary[i]); 2468135790
ary[i]++;
}
Note: ary+1 doesn’t move the ary to (ary+1)th position, it just points to that position. Whereas, ary++
actually tries to move ary by one one position.
Note: In the above definition, the array_ pointer must be placed parenthesis else the definition would
represent an array of pointers.
String Functions
C compiler comes with standard library header file ‘string.h’ which provides several functions to
manipulate strings.
Function Description
strlen(str) Returns the length of the string str
strcat(s1,s2) Concatenates string s2 at the end of s1
strcpy(s1,s2) Copies the string s2 at the end of s1
strcmp(s,s2) Compares two strings and returns
a) 0 if s1==s2 b) <0 if s1<s2 c) >0 if s1>s2
strchr(s,ch) Returns the address of the first occurrence of character ch in string s
strstr(str1,str2) Returns the address of the first occurrence of string str2 in string str1
strrev(s) Reverses a given string
/*Program to allocate memory for single /* Program to allocate memory for 2-D array */
element*/ #include<alloc.h>
#include<alloc.h> main()
main() {
{ int (*p)[4],i,j;
int *p; p=(int*)malloc(3 * 4 *sizeof(int));
p=(int*)malloc(sizeof(int)); /* p=(int*)calloc(3 * 4, sizeof(int)); */
/* p=(int*)calloc(sizeof(int)); */ for(i=0;i<3;i++)
printf(“\n Enter a Number:”); for(j=0;j<4;j++)
scanf(%d”,p); {
printf(“Entered number: %d”, *p); printf(“\n Enter a Number:”);
} scanf(%d”,&p[i][j]);/*printf(“ %d”,*(p+i)+j);*/
/* Program to allocate memory for Single }
Dimension Array */ for(i=0;i<3;i++)
#include<alloc.h> {
main() for(j=0;j<4;j++)
{ printf(“ %5d”,p[i]); /*printf(“ %5d”,*(*(p+i)+j));*/
int *p,i; printf(“\n”);
p=(int*)malloc(10 * sizeof(int)); }
/* p=(int*)calloc(10, sizeof(int)); */ }
for(i=0;i<10;i++)
{
printf(“\n Enter a Number:”);
scanf(%d”,&p[i]);
}
for(i=0;i<10;i++)
printf(“ %5d”,p[i]);
}
Array of pointers
It is possible to create array of pointers which are used to store addresses.
main()
{
int a[5] = {10,20,30,40,50}
int *p[5],i; /* array p can store 5 addresses */
for(i=0;i<5;i++)
{
p[i]=&a[i];
printf(“%5d”,*p[i]);
}
Multi Dimension Array of Pointers
A multi-dimension array can be expressed in terms of array of pointers.
Syntax: type *array_name[<exp 1>][<exp 2>]...[<exp n-1>]; instead of
type array_name)[<exp1>][<exp 2>][<exp 3>]...[<exp n>];
The last expression is omitted when defining an array of pointers whereas the first expression is omitted
when defining a pointer to a group of arrays.
Eg: int a[5][6] can be expressed as int *a[5];
3rd row 4th column element can be obtained as
a[2][3] or *( a[2]+3 )
address
name[0] K A K I N A D A \0
name[1] R A J A M U N D R Y \0
name[2] V I J A Y A W A D A \0
name[3] V I Z A G \0
Note: When using ragged arrays, we cannot accept values to the array directly using scanf() or gets().
/*Program to create an integer array /*Program to read strings in ragged arrays and
dynamically */ display */
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<alloc.h> #include<alloc.h>
void main() #include<string.h>
{ void main()
int *p[5],i,j,n; {
printf("\n Enter the size of each integer row"); char *str[5],temp[30];
scanf("%d",&n); int i;
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
p[i]=(int*)malloc(n *sizeof(int)); printf("\n Enter a Name:");
for(j=0;j<n;j++) gets(temp);
{ str[i]=(char*)malloc((strlen(str)+1)*sizeof(char));
printf("\n Enter a Number:"); strcpy(name[i],temp);
scanf("%d",&p[i][j]); /*printf(“ %d”,p[i]+j);*/ }
} for(i=0;i<5;i++)
} {
for(i=0;i<5;i++) printf("\n%s",name[i]);
{ }
for(j=0;j<n;j++) }
printf("%5d",p[i][j]);
/*printf("%5d",*(p[i]+j));*/
printf("\n");
}
}
/* Program to store the address of strlen() in a /* Program to store the address of strcmp() in a
function pointer and invoke it */ function pointer and invoke it */
#include<string.h> #include<string.h>
main(); check(char *a,char *b,int (*cmp)());
{ main();
char str[30]; {
int l,(*len)(); char str1[30],str2[30];
len=strlen; int (*c)();
printf(“\n Enter a String:”); c=strcmp;
gets(str); printf(“\n Enter two Strings:”);
l=(*len)(str); /* l=strlen(str) */ gets(str1);
printf(“length of %s is %d”,str,l); gets(str2);
} check(str1,str2,c);
}
check(char *a,char *b,int (*cmp)())
{
int n;
n=(*cmp)(a,b); /* n = strcmp(a,b); */
if(n==0)
printf(“\n Strings are equal”);
esle
printf(“\nStrings are not equal”);
}
Structure
A structure is grouping of variables under one name. A Structure consists of number of data items, which
need not be of same type, grouped together.
A Structure is a powerful tool in the hands of programmer which can be used to handle a group of
logically related data items.
Defining a Structure
A structure definition forms a template that is used to carry structure variables. The variables that make
up a structure are called structure elements or structure members. ‘struct’ keyboard is used to define a
structure.
Syntax: struct structure_name
{
structure members;
} structure variables;
Eg:
struct employ struct student struct phone
{ { {
int empno; int rno; int rno;
char name[30], dept[20]; char name[30]; char name[30];
char design[20]; float fee; long int phno;
float sal; }; };
};
Assigning values
struct phone p[3]={ {1,”sekhar”, 2306314}, {2,”ravi”,2306315} , {3,”arun”,2306312}};
struct subject
{
struct student s;
char sub[30];
int marks;
};
/*Program to read data using structure /*Program to allocate memory for a structure */
pointer*/ #include<alloc.h>
main() struct phone
{ {
struct phone int rno;
{ char name[30];
int rno; long int ph;
char name[30]; };
long int ph; main()
}; {
struct phone s,*p; struct phone *p;
p=&s; p=(struct phone*)malloc(sizeof(struct phone));
printf(“\n Enter Number:”); printf(“\n Enter Number:”);
scanf(“%d”, &p->rno); scanf(“%d”, &p->rno);
fflush(stdin); fflush(stdin);
printf(“\nEnNter Name:”0; printf(“\n Enter Name:”);
gets(p->name); gets(p->name);
printf(“\n Enter Phone Number:”); printf(“\n Enter Phone Number:”);
scanf(“%ld”,&p->ph); scanf(“%ld”,&p->ph);
printf(“\nNo.:%d Name:%s Phone No: %ld”, display(p);
p->.rno,p->name,p->.phno); }
} display(struct phone *x)
{
printf(“\nNo.:%d Name:%s Phone No: %ld”,x-
>rno,x->name,x->ph);
}
Union
Union is a grouping of variables under one name. In union, memory is shared by two or more variables
of different types at different times.
Union follows the same syntax as structure, except that the keyword ‘union’ is used in place of ‘sturct’.
Syntax:: union union_name
{
union members;
}union_variables;
Eg: union temp
{
int i;
float j;
}
The major fundamental difference between structure and union is that in a structure, each member has a
storage location once it is associated with a structure. But in union, all the members use the same
location. It implies that even though a union can contain members of different type, it can handle only
one member at a time.
In case of structure, the storage location allocated is equal to the sum of the storage capacity of individual
members. In case of union, the storage size is equal to the size of the largest member of the union.
Note: As we can include a structure within a structure, a union can be included in a union. There can be a
structure in union and a union in structure.
Enumeration
It is used to invent your own data type and define what values the variables of this data type can take.
Syntax:: enum enumeration_tag
{
Enumeration members;
}enumeration variables;
Eg: enum cities
{ Kakinada, Vizag, Vijayawada, Guntur };
Note: By default, the members are internally stored as integer constants starting from ‘0’.
Kakinada-0 Vizag-1
Vijayawada-2 Guntur-3
Note: we can change the default values of enumeration elements.
Eg: enum cities
{
Kakinada=0,Vizag=4,
Vijayawada=8,Guntur };
Program:
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
main()
{
Enum week today;
today=Wednesday;
printf(“%d day”,today+1);
}
Files
File Input and Output
All I/O operations are carried out using functions from the standard C library. I/O is unique because data
may be transferred in its internal binary representation or in a human readable text format making it easy
to create files to fit for any need.
Stream: The I/O system in C provides an interface to the user. This interface is independent of actual
device being accessed. This interface is not actually a file but an abstract representation of the device,
called as stream and, the actual device is called the ‘File’.
There are two types of streams- Text stream and Binary stream.
Text Stream
It is a sequence of characters which can be organized into lines terminated by a new line character.
Binary Stream
It is sequence of bytes with one to one correspondence to those in external devices.
File
A file can be anything from a device file to a terminal or a printer. A file can associated with a stream by
performing an open operation. And likewise, it can be de-associated with the stream by a close operation.
Basic File Functions
Function Description Function Description
fopen() Opens a file fclose() Closes a file
fputc() Writes a character to a file fgetc() Reads a character from a file
fputs() Writes a string to a file fgets() Reads a string from a file
fprintf() Writes data to a file. It is to a file what printf() is fscanf() Reads data from a file. It is to
to console a file what scanf() is to
console
fwrite() Writes a complete block of data to a file. fread() Reads a complete block of
data from a file
rewind() Moves the file locator to the first byte in the file. fseek() Seeks to the specified byte in a
(Resets the file position locator to the beginning file.
of the file)
ftell() Tells the current position of the file pointer in feof() Returns true if end-of-file(eof)
terms of bytes from the beginning. is reached
ferror() Returns true, if an error occurs. fflush() Flushes the stream
remove() Erases the file
File Pointer
A file pointer is pointer to a structure which contains information about the file including its name,
current position of the file position locator, size, whether the file is opened for reading or writing etc.,
Syntax:: FILE *file_pointer;
Eg: FILE *fp;
fopen()
fopen() fopen function opens the stream for use and links a file with that stream. A file pointer is
associated with that file is then returned by fopen().
Syntax: FILE *fopen(const char *name, const char *mode);
‘mode’ specifies the purpose for which the file is being opened.
Mode Description Mode Description
R Opens text file for reading rb Opens binary file for reading
W Creates text file for writing wb Creates binary file for writing
A Appends to a text file ab Appends to a binary file
r+ Opens text file for read/write r+b Opens binary file for read/write
w+ Creates text file for read/write w+b Creates binary file for read/write
a+f Appends or create text file for read/Write a+b Appends or create binary file for read/Write
Steps performed while opening the file
Step 1: Search for the file
Step 2: If found, the file is loaded into memory. If not found, a NULL value is returned.
Step 3: fopen() then sets up a character pointer. It is a part of the file structure and points to the first
character in the file memory while the file is being loaded.
Eg: FILE *fp;
fp=fopen(“name.txt”,”r”);
if(fp=NULL)
{
printf(“File not found”);
exit(1);
}
fclose()
fclose() is used to close a file
Syntax: fclose(FILE *fp);
Note: fcloseall() is used to close all the files which are opened currently. It returns an integer which
specifies the number of strmes that are currently opened. It returns ‘EOF” when an error occurs.
fputc()
fputc() is used to write a character to a file.
Syntax: fputc(int ch, FILE *fp);
fgetc()
fgetc() is used to read a character from a file
Syntax: fgetc(FILE *fp);
/*Program*/
main()
{
FILE *fp;
char ch;
if((fp=fopen(“abc.txt”,”w”) == NULL)
{
printf(“Unable to create the file”);
exit(1);
}
ch=getche();
while(ch!=’*’)
{
fputc(ch,fp);
ch=getche();
}
fclose(fp);
if((fp=fopen(“abc.txt”,”r”) == NULL)
{
printf(“Can’t open the file”);
exit(1);
}
do
{
ch=fgetc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
fputs()
It is used to write strings to a file
Syntax: int fputs(const char *str, FILE *fp);
fgets()
It is used to read strings from a file.
Syntax: chat *fgets(char *str, int length, FILE *fp);
feof()
This function returns a non-zero value if the end-of-file has been reached.
Syntax: int feof(FILE *fp);
ftell()
It returns a long int value which gives the position of the character file pointer from the beginning of the
file in the specified stream.
fseek()
fseek() re-positions the current file pointer by a specified number of bytes from the starting, from the
current position or from the end of the stream depending up on the position specified in fseek().
Syntax: int fseek(FILE *fp, long int offset, int origin);
offset is the number of bytes beyond the file location given in origin. Origin indicates the
beginning position and has three values
SEEK_SET or 0 from the beginning of the file
SEEK_CUR or 1 from the current position of the file
SEEK_END or 2 from the end of the file
main()
{
char str[80];
FILE *fp;
if((fp=fopen(“names.txt”,”w+”)) == NULL)
{
printf(“Can’t create a file”);
exit(1);
}
do
{
printf(“Enter a string. Press enter to exit:”);
gets(str);
strcat(str,”\n”);
fputs(str,fp);
if(ferror(fp))
printf(“Error in writing’);
}while(*str!=’\n’);
rewind(fp);
while(!feof(fp))
{
printf(“The position of the file pointer:%ld”,ftell(fp));
fgets(str,80,fp);
printf(“%s”,str);
}
fclose(fp);
}
Standard streams
When C programs starts execution under DOS, five specified streams are opened automatically by the
operating system. They are
Standard input stream(stdin)
Standard output stream(stdout)
Standard error stream(stderr)
Standard printer stream(stdprn)
Standard auxiliary stream(stdaux)
stdin, stdout,stderr are assigned to systems console. stdprn is assigned to printer port. stdaux is assigned
to first serial port.
fread() and fwrite()
These functions are used to read and write a complete block of data at once to a file respectively.
Syntax: fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
fwrite(void *buffer, size_t num_bytes, size_t count, FILE *fp);
Searching
It is the process of finding the element in an array until it is found or we reach to the end of the array.
There are two types of searching techniques. They are
a. Linear search b. Binary search
Linear Search
In this technique, we compare each and every element of the array one by one with the element to be
found. The searching stops if the element is found or we reach to the end of the array.
/*Search a number in an array using Linear /*Search a string in an array using Linear
Search*/ Search*/
main() #include<string.h>
{ main()
int a[10],n,i; {
for(i=0;i<10;i++) char a[10][20],n[20];
{ int i;
printf(“\n Enter Number:”); for(i=0;i<10;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter a string:”);
printf(“\n Enter the element you want to search”); gets(a[i]);
scanf(“%d”,&n); }
for(i=0;i<10;i++) printf(“\n Enter the string you want to search”);
{ gets(n);
if(a[i]==n) for(i=0;i<10;i++)
{ {
printf(“\nNumber found at position %d”,i+1); if(strcmp(a[i],n)==0)
exit(0); {
} printf(“\nStringr found at position %d”,i+1);
} exit(0);
printf(“\nElement not found”); }
} }
printf(“\nString not found”);
}
Binary Search
This searching technique is applied to sorted array. Here, we compare the middle element of the array
with the element to be found. If found, the searching stops. Otherwise, we check whether the element to
be found is less than or greater than the middle element. If less, the above procedure is applied to the left
half of the array otherwise with the right half. The procedure is continued until the element is found or
we reach to the end of the array.
/* Search a number in a sorted array using /* Search a string in a sorted array using binary
binary search */ search */
main() #include<string.h>
{ main()
int a[10],n,i,l,m,h; {
printf(“\n ENTER NUMBERS IN SORTED char a[10][20],n[20];
ORDER”); int i,l,m,h;
for(i=0;i<10;i++) printf(“\n ENTER ELEMENTS IN SORTED
{ ORDER”);
printf(“\n Enter Number:”); for(i=0;i<10;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter a string:”);
printf(“\n Enter the element you want to search”); gets(a[i]);
scanf(“%d”,&n); }
l=0; printf(“\n Enter the string you want to search”);
h=9; gets(n);
while(l<=h) l=0;
{ h=9;
m=(l+h)/2; while(l<=h)
if(a[m]==n) {
{ m=(l+h)/2;
printf(“\nNumber found at position %d”,m+1); if(strcmp(a[m],n==0)
exit(0); {
} printf(“\nString found at position %d”,m+1);
else if(a[m]<n) exit(0);
l=m+1; }
else else if(strcmp(a[m],n)<0)
h=m-1; l=m+1;
} else
printf(“\nElement not found”); h=m-1;
} }
printf(“\nString not found”);
}
Sorting
Sorting is the process of arranging the elements in an order. The following are some of the sorting
techniques
a. Selection Sort b. Bubble Sort c. Insertion Sort d. Quick Sort
Selection Sort
In this technique, the position of the element with the least value is found and is interchanged with the
first element. The same procedure is continued with the remaining elements until the array is sorted.
Bubble Sort
Also called as exchange sort, it involves repeated comparisions and the smallest element is bubbled up to
the top.
Insertion sort
In this technique, the first two elements are sorted. Next, the algorithm inserts the third element into its
sorted position in relation to the first two elements. Then, it inserts the fourth element and the same
process is continued until all the elements are sorted.
Quick Sort
Build on the idea of partition, the general procedure is to select a value and then partition the array into
two sections such that all elements greater than or equal to the partition value are put one side and those
less than the value are put on the other. This procedure is continued for each remaining section until the
array is sorted.
/* Program to sort a numeric array */ quick_sort(int *a,int n)
#include<alloc.h> {
main() qs(a,0,n-1);
{ }
int *a,i,n; qs(int *a,int left,int right)
printf(“Enter the number of elements:”); {
scanf(“%d”,&n); int i,j,n,temp;
a=(int*)malloc(n*sizeof(int)); i=left;
for(i=0;i<10;i++) j=right;
{ n=a[(left+right)/2];
printf(“\n Enter a number:”); do
scanf(“%d”,&a[i]); {
} while(a[i]<no && i<right)
printf(“\nBefore Sorting:”); i++;
for(i=0;i<10;i++) while(no<a[j] && j>left)
printf(“%5d”,a[i]); j--;
selection_sort(a,n); if(i<=j)
/*bubble_sort(a,n); */ {
/*insertion_sort(a,n); */ temp=a[i];
/*quick_sort(a,n); */ a[i]=a[j];
printf(“\nAfter Sorting:”); a[j]=temp;
for(i=0;i<10;i++) i++;
printf(“%5d”,a[i]); j--;
} }
}while(i<=j);
if(left<j)
qs(a,left,j);
if(right>i)
qs(a,i,right);
}
selection_sort(int a[],int n) bubble_sort(int a[],int n)
{ {
int i,j,min,temp; int i,j,temp;
for(i=0;i<n-1;i++) for(i=0;i<n;i++)
{ for(j=n-1;j>i;j--)
min=i; f(a[j]<a[j-1])
for(j=i+1;j<n;j++) {
{ temp=a[j];
if(a[min]>a[j]) a[j]=a[j-1];
min=j; a[j-1]=temp;
} }
if(i!=min) }
{ insertion_sort(int *a,int n)
temp=a[i]; {
a[i]=a[min]; int i,j,temp;
a[min]=temp; for(i=1;i<n;i++)
} {
} temp=a[i];
} for(j=i-1;j>=0 && temp<a[j];j--)
a[j+1]=a[j];
a[j+1]=temp;
}
}