Vous êtes sur la page 1sur 179

J.B.

INSTITUTE OF ENGINEERING & TECHNOLOGY


YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075

DEPARTMENT OF CSE & IT

C & DATA STRUCTURES

LAB MANUAL
J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY
YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075

DEPARTMENT OF CSE & IT

INDEX

PAGE
S.NO DESCRIPTION OF THE PROGRAM
NO
1 a) A C program to find the sum of individual digits of a positive integer.
b) A Fibonacci Sequence is defined as follows: the first and second terms
in the sequence are 0 and 1. Subsequent terms are found by adding the
preceding two terms in the sequence. Write a C program to generate the
first n terms of the sequence.
c) A C program to generate all the prime numbers between 1 and n. Where
n is the value supplied by the user.

2 a) A C program to calculate the following Sum:


Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!
b) A C program toe find the roots of a quadratic equation.

3 i) C programs that use both recursive and non-recursive functions to find


the factorial of a given integer.
ii) C programs that use both recursive and non-recursive functions to find
the GCD of two given integers.
iii) C programs that use both recursive and non-recursive functions to
sovle towers of Hanoi problem.
4
a) Program to find the total distance travelled by vehicle in 't' seconds is
given by distance = ut+1/2at2 where 'u' and 'a' are the initial velocity
(m/sec.) and acceleration (m/sec2) for different values of 'u' and 'a'.

b) A C program, which takes two integer operands and one operator form
the user, performs the operation and then prints the result.
(Consider the operators +,-,*,/,% and use Switch Statement)

5 a) C program to find both the largest and smallest number in a list of


integers.
b) A C program that uses functions to perform the following:
i) Addition of Two Matrices
ii) Multiplication of Two Matrices

6 a) A C program that uses functions to perform the following operations:


i) To insert a sub-string in to given main string from a given position.
ii) To delete n Characters from a given position in a given string.
b) A C program to determine if the given string is a palindrome or not.

7 a) A C program that displays the position or index in the string S


where the string T begins, or - 1 if S doesn't contain T.

b) A C program to count the lines, words and characters in a given text.


8 a) A C program to generate Pascal's triangle.
b) A C program to construct a pyramid of numbers.

9 A C program to read in two numbers, x and n, and then compute the sum of
this geometric progression: 1+x+x2+x3+………….+xn
For example: if n is 3 and x is 5, then the program computes 1+5+25+125.
Print x, n, the sum Perform error checking. For example, the formula does
not make sense for negative exponents - if n is less than 0. Have your
program print an error message if n<0,then go back and read in the next pair
of numbers of without computing the sum. Are any values of x also illegal ?
If so, test for them too.

10 a) A C program to find the 2’s complement of a binary number.

b) A C program to convert a Roman numeral to its decimal equivalent.

11 A C program that uses functions to perform the following operations:


i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
(Note: represent complex number using a structure.)

12 a) A C program which copies one file to another.

b) A C program to reverse the first n characters in a file.


(Note: The file name and n are specified on the command line.)

13 A C program that uses functions to perform the following operations on


Single Linked list:
i) Creation ii) Insertion
ii) Deletion iv) Traversal

14 A C program that uses functions to perform the following operations on


doubly linked list:
i)Creation ii) Insertion
iii)Deletion iv) Traversal in both ways

15 i)C programs that implement stack (its operations) using Arrays


ii) C programs that implement stack (its operations) using pointers

16 i) C programs that implement Queue (its operations) using Arrays.

ii) C programs that implement Queue (its operations) using pointers.

17 A C program that uses Stack operations to perform the following:


i) Converting infix expression into postfix expression
ii) Evaluating the postfix expression

18 A C program that uses functions to perform the following:


i) Creating a Binary Tree of integers
ii)Traversing the above binary tree in preorder, inorder
and postorder.

19 i) C programs that use both recursive and non recursive functions


to perform Linear search operations for a Key value in a given
list of integers.

ii) C programs that use both recursive and non recursive functions
to perform binary search operations for a Key value in a given
list of integers.
20
A C program that implements the following sorting methods to sort a given
list of integers in ascending order
i) Bubble Sort

ii) Quick Sort

21
A C program that implements the following sorting methods to sort a given
list of integers in ascending order
i) insertion Sort

ii) Merge sort Sort

22 i) A C program to implement the Lagrange interpolation


ii) A C program to implement the Newton-Gregory forward
interpolation.

23 i) A C program to implement the Linear Regression algorithm.


ii) A C program to implement the polynomial regression algoritm.

24 i) A C program to implement trapezoidal method.


ii) A C program to implement Simpson method.
Sum of individual digits of a given positive integer

ALGORITHM :

step 1: start
step 2: read a positive integer no
step 3: sum←0 dig←0
step 4: dig ← no mod 10
step 5: sum ← sum + dig
step 6: no ← no/10
step 7: repeat steps 3,4,5 until no greater than zero
step 8: print sum
step 9: stop
FLOWCHART :

start

read no

sum=0 dig=0

yes dig=no mod 10


sum=sum+dig
Is no >0 no=no/10

No

write sum

stop
Program to find the sum of the individual digits of a given positive integer

#include<stdio.h>
#include<conio.h>
void main()
{
int no,sum,dig,t;
clrscr();
printf("\nEnter a positive integer:");
scanf("%d",&no);
t=no;
sum=0;
dig=0;
while(no>0)
{
dig=no%10;
sum=sum+dig;
no=no/10;
}
printf("\nm of the digits of the given positive integer %d is %d",t,sum);
getch();
}

Output:

INPUT:

Enter a positive integer : 1234

RESULT:

Sum of the digits of the given positive integer 1234 is 10


Fibonacci sequence

ALGORITHM :

step 1 : start
step 2 : read n
step 3 : a←0, b←1, i←3
step 4 : write a b
step 5 : c← a+b
step 6 : write c
step 7 : a←b, b←c
step 8 : i←i+1
step 9 : repeat steps 5,6,7,8 until i equals n
step 10: stop
FLOWCHART:

start

read n

a=0, b=1, i=3

write a,b

c=a+b

write c

a=b, b=c, i=i+1

yes
Is i<=n

No

stop
Program to generate Fibbonacci Series

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,i,n;
clrscr();
printf("\nEnter how many terms:");
scanf("%d",&n);
a=0;
b=1;
printf("\n%d\n%d",a,b);
i=3;
while(i<=n)
{
c=a+b;
printf("\n%d",c);
a=b;
b=c;
i++;
}
getch();
}

OUTPUT

INPUT :

Enter how many terms : 10

RESULT :
0
1
1
2
3
5
8
13
21
34
Prime Numbers

ALGORITHM :

step 1: start
step 2: read no
step 3: i←1
step 4: nof←0 j←1
step 5: rem←i mod j
step 6: if rem=0 then nof=nof+1
step 7: j←j+1
step 8: repeat steps 5,6,7 until j equals i
step 9: if nof=2 then write i
step 10: compute i←i+1
step 11: repeat steps 5 to 10 until i equals no
step 12: stop
FLOWCHART:

start

read no

i=2

No
is i <= n

yes
yes i=i+1
j=1, c=0

No
is j <= i is c=2

yes yes
j=j+1
write i
is i mod j=0

yes
c=c+1

Stop
Program to generate prime numbers between 1 and n

#include<stdio.h>
#include<conio.h>
void main()
{
int no,i,j,nof;
clrscr();
printf("\nEnter range 1 to ___:");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
nof=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
nof++;
}
if(nof==2)
printf("%d ",i);
}
getch();
}

OUTPUT

INPUT :
Enter range 1 to … 20

RESULT:

2 3 7 11 13 17 19
To evaluate the series
sum = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - x^10/10!

ALGORITHM :
step 1: start
step 2: read x,n
step 3: num←1,den←1,sum←1,i←1
step 4: num←num*x*x
step 5: den←den*(2*i-1)*(2*i)
step 6: sum←sum+num/den
step 7: i←i+1
step 8: repeat steps 4,5,6 until i<n
step 9: stop
FLOWCHART:
start

read x n

sum=1 num=1
den=1 i=1

yes num=num*x*x
Is i<n den=den*(2*i-1)*(2*i)
sum=sum+num/den
i=i+1

No

write sum

stop
Program to solve sum = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - x^10/10!

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,x,n;
long num,den;
float sum;
clrscr();
printf("\nEnter value of x : ");
scanf("%d",&x);
sum=1;
num=1;
den=1;
for(j=2,i=1;j<=10;i++,j=j+2)
{
num=-num*x*x;
den=den*(2*i-1)*(2*i);
sum=sum+(float)num/den;
}
printf("\nSum=%f",sum);
getch();
}

OUTPUT

INPUT :

Enter value of x : 2

RESULT :

Sum=-0.416155
To find the Roots of a quadratic equation
ALGORITHM :

step 1: start
step 2: read a,b,c values
step 3: compute d=b*b-4ac
step 4: if d > 0 then
r1← -(b+sqrt(d))/(2*a)
r2← -(b-sqrt(d))/(2*a)
step 5: if d=0 then
r1← -b/(2*a)
r2← -b/(2*a)
step 6: if d < 0
r1←-b/(2*a)
r2←sqrt(-d)/(2*a)
step 7: write r1 r2
step 8: stop
FLOWCHART:
start

read a,b,c

d=b*b-4ac

r1=-(b+sqrt(d))/(2*a)
yes r2=-(b-sqrt(d))/(2*a)
Is d >0

No
r1=-b/(2*a)
yes r2=-b/(2*a)
Is d =0

No

r1=-b/(2*a)
r2=sqrt(-d)/(2*a)

write r1 r2

stop
Program to find the roots of a quadratic equation

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,d;
float r1,r2;
clrscr();
printf("Enter values of a,b,c:");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
r1=-(b+sqrt(d))/(2*a);
r2=-(b-sqrt(d))/(2*a);
printf("Roots are real and different\n%f %f",r1,r2);
}
else if(d==0)
{
r1=-b/(2*a);
r2=-b/(2*a);
printf("Roots are real and equal\n%f %f",r1,r2);
}
else
{
r1=-b/(2*a);
r2=sqrt(-d)/(2*a);
printf("Roots are imaginary \n%f+i%f",r1,r2);
}
getch();
}

OUTPUT

INPUT :

Enter values of a,b,c:1 2 1

RESULT:
Roots are real and equal
-1.000000 -1.000000

INPUT :

Enter values of a,b,c:1 2 3

RESULT:

Roots are imaginary


-1.000000 + i1.414214

INPUT :

Enter values of a,b,c:1 6 6

RESULT:

Roots are real and different


-4.732051 -1.267949
To find the factorial of a given integer using
recursive and non recursive functions

ALGORITHM :

Step 1: start
Step 2: read n value
Step 3: f←1 i←1
Step 4: f←f* i
Step 5: i← i+1
Step 6: repeat steps 4 and 5 until I <=n
Step 7: write f
Step 8: stop
FLOWCHART:
start

read n

f=1, i=1

yes f=f*i
Is i<=n
i=i+1

No

write f

stop
Program to find the factorial of a given integer using Non-recursive and recursive functions

#include<stdio.h>
#include<conio.h>

unsigned int recr_factorial(int n);


unsigned int iter_factorial(int n);

void main()
{
int n,i;
long fact;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);

if(n==0)
printf("Factorial of 0 is 1\n");
else
{
printf("Factorial of %d Using Recursive Function is %d\n",
n,recr_factorial(n));
printf("Factorial of %d Using Non-Recursive Function is
%d\n",n,iter_factorial(n));
}
getch();
}

/* Recursive Function*/
unsigned int recr_factorial(int n)
{
return n>=1 ? n * recr_factorial(n-1) : 1;
}

/* Non-Recursive Function*/
unsigned int iter_factorial(int n)
{
int fact = 1;
int i;
for(i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

OUTPUT

INPUT:

Enter the number: 7

OUTPUT :

Factorial of 7 Using Recursive Function is 5040

Factorial of 7 Using Non-Recursive Function is 5040


To find GCD of two given integers

ALGORITHM :
Step 1: start
Step 2: read two integer values a,b
Step 3: rem ← a%b
Step 4: a←b, b←rem
Step 5: repeat steps 3 and 4 until rem >0
Step 6: write b
Step 7: stop
FLOWCHART:

start

read a b

rem<- a mod b

Yes
rem > 0 ? a<- b
b<-rem

No

write b
Program to find the GCD of two given integers using Non-Recursive and Recursive
functions

unsigned int GcdRecursive(unsigned m, unsigned n);


unsigned int GcdNonRecursive(unsigned p,unsigned q);
int main(void)
{
int a,b;
clrscr();
printf("Enter the two numbers whose GCD is to be found: ");
scanf("%d%d",&a,&b);
printf("GCD of %d and %d Using Recursive Function is %d\n", a,b,GcdRecursive(a,b));
printf("GCD of %d and %d Using Non-Recursive Function is %d\n",a,b,GcdNonRecursive(a,b));
getch();
return 0;
}

/* Recursive Function*/
unsigned int GcdRecursive(unsigned m, unsigned n)
{
if(n>m)
return GcdRecursive(n,m);
if(n==0)
return m;
else
return GcdRecursive(n,m%n);
}

/* Non-Recursive Function*/
unsigned int GcdNonRecursive(unsigned p,unsigned q)
{
unsigned remainder;
remainder = p-(p/q*q);

if(remainder==0)
return q;
else
while(remainder>0)
{
p=q;
q=remainder;
remainder=p%q;
}
return q;
}

OUTPUT

INPUT :

Enter the two numbers whose GCD is to be found: 15 25

RESULT:

GCD of 15 and 25 Using Recursive Function is 5

GCD of 15 and 25 Using Non-Recursive Function is 5


Towers of Hanoi

ALGROTHIM:

Recursive
Step 1: start
Step 2: read no of disks n
Step 3: if n=1, move the single disk from A to C and return.
Step 4: move the top n-1 disks from A to B using C as temporary
Step 5: move the remaining disk from A to C
Step 6: move n-1 disks from B to C, using A as temporary
Step 7: stop
Program to solve Towers of Hanoi problem using Non-Recursive and Recursive functions

#include<conio.h>
#include<stdio.h>
/* Non-Recursive Function*/
void hanoiNonRecursion(int num,char sndl,char indl,char dndl)
{
char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp;
int top,add;
top=NULL;
one:
if(num==1)
{
printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);
goto four;
}
two:
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=3;
num=num-1;
sndl=sndl;
temp=indl;
indl=dndl;
dndl=temp;
goto one;
three:
printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=5;
num=num-1;
temp=sndl;
sndl=indl;
indl=temp;
dndl=dndl;
goto one;
four:
if(top==NULL)
return;
num=stkn[top];
sndl=stksndl[top];
indl=stkindl[top];
dndl=stkdndl[top];
add=stkadd[top];
top=top-1;
if(add==3)
goto three;
else if(add==5)
goto four;
}

/* Recursive Function*/
void hanoiRecursion( int num, char ndl1, char ndl2, char ndl3)
{
if ( num == 1 )
{
printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );
return;
}

hanoiRecursion( num - 1,ndl1, ndl3, ndl2 );


printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );
hanoiRecursion( num - 1,ndl3, ndl2, ndl1 );
}
void main()
{
int no;
clrscr();
printf("Enter the no. of disks to be transferred: ");
scanf("%d",&no);

if(no<1)
printf("\nThere's nothing to move.");
else
printf("Non-Recursive");
hanoiNonRecursion(no,'A','B','C');
printf("\nRecursive");
hanoiRecursion(no,'A','B','C');

getch();
}

OUTPUT

INPUT :
Enter the no. of disks to be transferred: 4
RESULT :

Non-Recursive

Move top disk from needle A to needle B Move top disk from needle A to needle C
Move top disk from needle B to needle C Move top disk from needle A to needle B
Move top disk from needle C to needle A Move top disk from needle C to needle B
Move top disk from needle A to needle B Move top disk from needle A to needle C
Move top disk from needle B to needle C Move top disk from needle B to needle A
Move top disk from needle C to needle A Move top disk from needle B to needle C
Move top disk from needle A to needle B Move top disk from needle A to needle C
Move top disk from needle B to needle C

Recursive

Move top disk from needle A to needle C. Move top disk from needle A to needle B.
Move top disk from needle C to needle B. Move top disk from needle A to needle C.
Move top disk from needle B to needle A. Move top disk from needle B to needle C.
Move top disk from needle A to needle C. Move top disk from needle A to needle B.
Move top disk from needle C to needle B. Move top disk from needle C to needle A.
Move top disk from needle B to needle A. Move top disk from needle C to needle B.
Move top disk from needle A to needle C. Move top disk from needle A to needle B.
Move top disk from needle C to needle B.
To find the total distance travelled by vehicle in t seconds at regular intervals of
time for the given values of ‘u’ and ‘a’ (distance – ut+1/2 at2 )

ALGORITHM :

Step 1: Start
Step 2: read no of time intervals n
Step 3: i←1
Step 4: read time t
Step 5: read velocity u
Step 6: read acceleration a
Step 7: distance ← distance + u * t + ½ * a * t * t
Step 8: I ← I +1
Step 9: repeat steps 4,5,6,7 and 8 until i = n
Step 10 : write distance
Step 11: stop
Program the find the total distance travelled by vehicle in t seconds at regular intervals of
time for the given values of ‘u’ and ‘a’ (distance – ut+1/2 at2 )

#include <stdio.h>
#include <math.h>
void main()
{
int tim_intrval, counter,time;
float accl, distance=0, velos;
clrscr();
printf("<===PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL==>");
printf("\n\n\n\t\t\tNO OF TIME INTERVALS : ");
scanf("%d",&tim_intrval);
for(counter = 1; counter <= tim_intrval; counter++)
{
printf("\n\t\t\tAT T%d TIME(sec) : ",counter);
scanf("%d",&time);
printf("\t\t\tVELOCITY AT %d sec (m/sec) : ",time);
scanf("%f",&velos);
printf("\t\t\tACCLERATION AT %d sec (m/sec^2): ",time);
scanf("%f",&accl);
distance += (velos*time + (accl*pow(time,2))/2);
}
printf("\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF
TIME : %.2f",tim_intrval,distance);
getch();
}
OUTPUT

PROGRAM FOR CALCULATE TOTAL DISTANCE TRAVELED BY A VECHICLE

INPUT :
NO OF TIME INTERVALS : 3

AT T1 TIME(sec) : 10
VELOCITY AT 10 sec (m/sec) : 90
ACCLERATION AT 10 sec (m/sec^2): 2.5

AT T2 TIME(sec) : 20
VELOCITY AT 20 sec (m/sec) : 50
ACCLERATION AT 20 sec (m/sec^2): 3

AT T3 TIME(sec) : 40
VELOCITY AT 40 sec (m/sec) : 90
ACCLERATION AT 40 sec (m/sec^2): 5

RESULT :

TOTAL DISTANCE TRAVELLED BY VEHICLE IN 3 INTERVALS


OF TIME : 10225.00
To perform operation on the two given integer operands
and one operator using switch statement

ALGORITHM :

Step 1: Start
Step 2: read operator op and two operands op1 and op2
Step 3: switch(op)
Step 3.1: case + perform addition (result = op1 + op2)
Step 3.1: case - perform subtraction (result = op1 - op2)
Step 3.1: case * perform multiplication (result = op1 * op2)
Step 3.1: case / perform division (result = op1 / op2)
Step 4: write result
Step 5: stop
FLOWCHART :

start

read operator op , two integer


operands op1 and op2

Yes
Op =oop
‘+’ res=op1 + op2

No

Yes
Op = ‘-’ res=op1 - op2

No

Yes
Op = ‘*’ res=op1 * op2

No

Op = ‘/’ res=op1 / op2

write res

stop
Program to perform operation on the two given integer operands and one operator using
switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int op1,op2,res;
char op;
clrscr();
printf("Enter operator :");
scanf("%c",&op);
printf("Enter two values :");
scanf("%d%d",&op1,&op2);
switch(op)
{
case '+': res=op1+op2;
break;
case '-': res=op1-op2;
break;
case '*': res=op1*op2;
break;
case '/': res=op1/op2;
break;
case '%': res=op1%op2;
break;
default : printf("Invalid choice");
}
printf("\n%d %c %d = %d",op1,op,op2,res);
getch();
}

OUTPUT

INPUT

Enter operator : +
Enter any two integer values : 30 40
RESULT
30 + 40 = 70
To find the largest and smallest numbers in a list of integers

ALGORITHM :

Step 1: Start
Step 2: Enter size of the array n
Step 3: read n values into an array
Step 4: large←small←a[0]
Step 5: i←1
Step 6: if a[i]>large large=a[i]
Step 7: if a[i]<small small=a[i]
Step 8: i←i+1
Step 9: repeat steps 6,7 and 8 until i<n
Step 10: write large and small
Step 11: stop
FLOWCHART :

start

read n
read a[n] values

i=0
small=a[0]
large =a[0]

No

yes
A[i] >= large Large = a[i]

No

yes
A[i] <= small small = a[i]

No

write large small

stop
Program to find the largest and smallest numbers in a list of integers

#include<stdio.h>
#include<conio.h>
#define MAX 10
void main()
{
int a[MAX],i,lar,small,n;
printf("Enter value of n:");
scanf("%d",&n);
printf(“Enter %d values”,n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
lar=small=a[0];
for(i=0;i<n;i++)
{
if(a[i]>lar)
lar=a[i];
if(a[i]<small)
small=a[i];
}
printf("Large=%d Small=%d",lar,small);
getch();
}
OUTPUT
INPUT :

Enter the value of n : 5

Enter 5 values
44
55
66
33
22
RESULT :
Large : 66
Small : 22
Addition of two matrices

ALGORITHM :

Step 1: Start
Step 2: read size of the matrix A r1, c1
Step 3: read size of the matrix B r2, c2
Step 4: if r1=r2 and c1=c2 read the value of the two matrices
Step 5: Add the two matrices A and B store into C
Step 6: write A, B and C
Step 7: stop
FLOWCHART:

start

read values of two matrices A B

i = 0 j=0

No
is i <= r1

yes
yes i=i+1
j=0

No
is j <= c1

yes
j=j+1 C[i][j]=A[i][j]+B[i][j]

stop
Addition of two matrices

#include<stdio.h>
#include<conio.h>
void main()
{
int A[5][5],B[5][5],C[5][5],i,j,r1,c1,r2,c2;
clrscr();
printf("\nEnter size of matrix A :");
scanf("%d%d",&r1,&c1);
printf("\nEnter size of matrix B :");
scanf("%d%d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("\nEnter values of matrix A\n");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
printf("A[%d][%d]=",i,j);
scanf("%d",&A[i][j]);
}
printf("\nEnter values of matrix B9\n");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
{
printf("B[%d][%d]=",i,j);
scanf("%d",&B[i][j]);
}
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
C[i][j]=A[i][j]+B[i][j];
printf("\nMatrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("%d\t",A[i][j]);
printf("\n");
}
printf("\nMatrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",B[i][j]);
printf("\n");
}
printf("\nSum of two matrices A and B \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",C[i][j]);
printf("\n");
}
}
else
printf("Addition not possible");
getch();
}

OUTPUT

INPUT:

Enter size of matrix A : 3 3


Enter size of matrix B : 3 3

Enter the values of matrix A 1 2 3 4 5 6 7 8 9

Enter the values of matrix B 9 8 7 6 5 4 3 2 1

RESULT:
MATRIX A
123
456
789

MATRIX B
987
654
321

Sum of the two matrices A and B is

MATRIX C
10 10 10
10 10 10
10 10 10

Multiplication of two matrices

ALGORITHM :

Step 1: Start
Step 2: read size of the matrix A r1, c1
Step 3: read size of the matrix B r2, c2
Step 4: if c1=r2 read the value of the two matrices
Step 5: Multiply the two matrices A and B store into C
Step 6: write A, B and C
Step 7: stop
FLOWCHART:
start

Read values of two matrices A B

i=0

No
is i < c1

yes
yes i=i+1
j=0 k=0

No
is j < r2

yes
j=j+1

No
k < c2 k=k+1

yes

C[i][j]=C[i][j]+A[i][k]*B[k][j]

Print C

stop
Multiplication of two matrices

#include<stdio.h>
#include<conio.h>
void main()
{
int A[5][5],B[5][5],C[5][5],i,j,r1,c1,r2,c2;
clrscr();
printf("\nEnter size of matrix A :");
scanf("%d%d",&r1,&c1);
printf("\nEnter size of matrix B :");
scanf("%d%d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("\nEnter values of matrix A\n");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
printf("A[%d][%d]=",i,j);
scanf("%d",&A[i][j]);
}
printf("\nEnter values of matrix B9\n");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
{
printf("B[%d][%d]=",i,j);
scanf("%d",&B[i][j]);
}
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
C[i][j]=A[i][j]+B[i][j];
printf("\nMatrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("%d\t",A[i][j]);
printf("\n");
}
printf("\nMatrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",B[i][j]);
printf("\n");
}
printf("\nSum of two matrices A and B \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",C[i][j]);
printf("\n");
}
}
else
printf("Addition not possible");
getch();
}

OUTPUT

INPUT:

Enter size of matrix A : 2 3

Enter size of matrix B : 3 2

Enter the values of matrix A 1 2 3 4 5 6

Enter the values of matrix B 2 1 2 1 2 1

RESULT:
MATRIX A
1 2 3
4 5 6

MATRIX B
2 1
2 1
2 1

Sum of the two matrices A and B is

MATRIX C
12 6
30 15
To insert a sub-string in to given main string from a given position

ALGORITHM :

Step 1: Start
Step 2: read main string mstr
Step 3: read the sub string to be inserted substr
Step 4: read the position pos where the substr has to be inserted
Step 5: insert the substr into the mstr from pos
Step 6: write main string
Step 7: stop
Program to insert a sub-string in to given main string from a given position
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int pos;
char mstr[100],substr[10];
void strin(char[],char[],int);
clrscr();
printf("Enter main string");
gets(mstr);
printf("Enter the substr to be inserted:");
gets(substr);
printf("Enter the position to insert the substring in the mainstring:");
scanf("%d",&pos);
strin(mstr,substr,pos);
getch();
}
void strin(char m[],char sub[],int p)
{
char str1[100];
int i,j,k;
j=0;
for(i=0;i<p;i++)
str1[j++]=m[i];
for(k=0;sub[k]!='\0';k++)
str1[j++]=sub[k];
for(;i<strlen(m);i++)
str1[j++]=m[i];
str1[j]='\0';
printf("Main String after insertion of substring\n%s",str1);
}
INPUT:

Enter the main string : eslish


Enter the sub string : tab
Enter the position where the item has to be inserted:2

RESULT:

Main string after insertion of substring : establish


To delete n characters from a given position in a given string

ALGORITHM :

Step 1: Start
Step 2: Enter a sentence mstr
Step 3: Enter how many characters to be deleted and from which position n, pos
Step 4: i←pos
Step 5:m[i]=m[i+n];

Step 6: write m
Step 7: stop
Program to delete n characters from a given position in a given string.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,pos,len,n;
char mstr[100],substr[10],str1[100];
void strdel(char[],int,int);
clrscr();
printf("Enter main string");
gets(mstr);
printf("\nEnter how many characters and from which position:");
scanf("%d%d",&n,&pos);
strdel(mstr,n,pos);
getch();
}
void strdel(char m[],int n,int p)
{
int i;
for(i=p-1;i<m[i]!='\0';i++)
m[i]=m[i+n];
printf("After deletion : %s",m);
}

OUTPUT

INPUT:

Enter the first string : establish


Enter how many characters and from which position : 3 2

RESULT:

After deletion the string is elish


To determine if the given string is a palindrome or not

ALGORITHM :

Step 1: Start
Step 2: Enter a string s
Step 3: match=true
Step3:scan each character of the string and check
Step 4: if (string[left]!=string[right])
match=false
Step 5: if match=true
Write the given string is a palindrome
Else
Write the given string is not a palindrome
Step 6: stop
Program to determine if the given string is a palindrome or not
#include<stdio.h>
#include<string.h>
enum Boolean{false,true};
enum Boolean IsPalindrome(char string[])
{
int left,right,len=strlen(string);
enum Boolean matched=true;
if(len==0)
return 0;
left=0;
right=len-1;
/* Compare the first and last letter,second & second last & so on */
while(left<right&&matched)
{
if(string[left]!=string[right])
matched=false;
else
{
left++;
right--;
}
}
return matched;
}
int main()
{
char string[40];
clrscr();
printf("****Program to test if the given string is a palindrome****\n");
printf("Enter a string:");
scanf("%s",string);
if(IsPalindrome(string))
printf("The given string %s is a palindrome\n",string);
else
printf("The given string %s is not a palindrome\n",string);
getch();
return 0;
}
OUTPUT

INPUT
Enter a string : MALAYALAM

RESULT
The given string MALAYALAM is a palindrome
To display the position or index in the string S
where the string T begins, or - 1 if S doesn't contain T.

ALGORITHM :

Step 1: Start
Step 2: Enter a string s
Step 3: Enter a string to be searched t
Step 4: search the string t in string s
Step 5: if found
Write “the string is found at position”
Else
Wirte “the string is not found”
Step 6: stop
Program that displays the position or index in the string S where the string T begins, or - 1 if
S doesn't contain T.

#include<stdio.h>
#include<string.h>
#include<conio.h>

void main()
{
char s[30], t[20];
char *found;
clrscr();

/* Entering the main string */


puts("Enter the first string: ");
gets(s);

/* Entering the string whose position or index to be displayed */


puts("Enter the string to be searched: ");
gets(t);

/*Searching string t in string s */


found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",(found-s)+1);
else
printf("-1");
getch();
}

OUTPUT
INPUT:

Enter the first string : horizontal

Enter the string to be searched : zon

RESULT:

Second String is found in the First String at 5 position.


To count the lines, words and characters in a given text.

ALGORITHM :

Step 1: Start
Step 2: read text
Step 3: line ←0 lines←0 characters←0 words←0
Step 4: scan each character of the given text fron starting to ending char
Step 5: repeat step 6,7,8,9 till the end char
Step 6: characters←characters+1
Step 7: check if char = spaces
words←words+1
Step 8: check if char = ‘\n’
line←line+1
Step 9: write characters, words and lines
Step 10: stop
program to count the lines, words and characters in a given text.

#include <stdio.h>
main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
printf("KEY IN THE TEXT.\n");
printf("GIVE ONE SPACE AFTER EACH WORD.\n");
printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n");
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
}
OUTPUT

INPUT :

KEY IN THE TEXT.


GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS 'RETURN'.
Admiration is a very short-lived passion.
Admiration involves a glorious obliquity of vision.
Always we like those who admire us but we do not
like those whom we admire.
Fools admire, but men of sense approve.

RESULT :

Number of lines = 5
Number of words = 36
Number of characters = 205
Pascal's triangle

ALGORITHM :

Step 1: Start
Step 2: Enter how many rows r
Step 3: bin←1 q←0
Step 4: x=0
Step 5: print 40-3*q spaces
Step 6: if x=0 or q=0 bin=1
else
bin=bin*(q-x+1))/x
Step 7: write bin
Step 8: x←x+1
Step 9: repeat 5,6,7 until x < q
Step 10: q←q+1
Step 11: repeat steps 4,5,6,7 and 8 until q<r
Step 13: stop
Pascal Triangle
#include<stdio.h>
#include<conio.h>
void main()
{
int bin,p,q,r,x;
clrscr();
bin=1;
q=0;

printf("How many rows you want :");


scanf("%d",&r);
printf("\nPascal's Triangle:\n");
while(q<r)
{
for(p=40-3*q;p>0;--p)
printf(" ");
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
printf("%6d",bin);
}
printf("\n");
++q;
}
getch();
}

OUTPUT
INPUT:
Enter how many rows you want : 5
RESULT :
Pascal's Triangle:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

To construct a pyramid of numbers

ALGORITHM :

Step 1: Start
Step 2: Enter how many rows r
Step 3:
Step 4:
Step 10: q←q+1
Step 11: repeat steps 4,5,6,7 and 8 until q<r
Step 12: write
Step 13: stop
program to construct a pyramid of numbers

#include<stdio.h>
#include<conio.h>

void main()
{
int num,i,y,x=35;
clrscr();
printf("\nEnter the number to generate the pyramid:\n");
scanf("%d",&num);

for(y=0;y<=num;y++)
{
/*(x-coordinate,y-coordinate)*/
gotoxy(x,y+1);

/*for displaying digits towards the left and right of zero*/


for(i=0-y;i<=y;i++)

printf("%3d",abs(i));
x=x-3;
}
getch();
}

OUTPUT
INPUT :
Enter the number to generate the : 5

RESULT :

0
1 0 1
2 1 0 1 2
3 2 1 0 1 2 3
4 3 2 1 0 1 2 3 4
5 4 3 2 1 0 1 2 3 4 5

To read in two numbers, x and n, and then compute the sum of this
geometric progression: 1+x+x2+x3+. . . xn

ALGORITHM :

Step 1: Start
Step 2: read x n
Step 3: i←0
Step 4: if(n<0) write does not have negative exponents
Step 5: if n> p
for i=0 to n do
v←x to the power of i

sum←sum+v;
Step 6: write sum;
Step 7: stop
:
program to read in two numbers, x and n, and then compute the sum of this geometric
progression: 1+x+x2+x3+. . . xn

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
long x,n,i,sum=0,v;
clrscr();
lab:
printf("Enter the values of x and n:");
scanf("%ld%ld",&x,&n);
if(n<0)
{
printf("does not take negative exponents");
goto lab;
}
else
for(i=0;i<=n;i++)
{
v=pow(x,i);
printf("+%ld",v);
sum=sum+v;
}
printf("=%ld\n",sum);
getch();
}

OUTPUT

INPUT :

Enter the values of x and n : 2 8

RESULT:

1+2+4+8+16+32+64+128+256=511
To find the 2’s complement of a binary number

ALGORITHM :

Step 1: Start
Step 2: read binary number
Step 3: compute ones complement for the given binary number
Step 4: Add one to the ones complement
Step 5: print the result
Step 6: stop
Program to find the 2’s complement of a binary number.

#include <stdio.h>
#include<conio.h>

void complement (char *a);


void main()
{
char a[16];
int i;
clrscr();
printf("Enter the binary number : ");
gets(a);
for(i=0;a[i]!='\0'; i++)
{
if (a[i]!='0' && a[i]!='1')
{
printf("The number entered is not a binary number. Enter the correct number");
exit(0);
}
}
complement(a);
getch();
}
void complement (char *a)
{
int l, i, c=0;
char b[16];
l=strlen(a);
for (i=l-1; i>=0; i--)
{
if (a[i]=='0')
b[i]='1';
else
b[i]='0';
}
for(i=l-1; i>=0; i--)
{
if(i==l-1)
{
if (b[i]=='0')
b[i]='1';
else

{
b[i]='0';
c=1;
}
}
else
{
if(c==1 && b[i]=='0')
{
b[i]='1';
c=0;
}
else if (c==1 && b[i]=='1')
{
b[i]='0';
c=1;
}
}
}
b[l]='\0';
printf("The 2's complement is %s", b);
}

OUTPUT

INPUT:

Enter the binary number1111

RESULT:

The 2's complement is 0001


To convert a Roman numeral to its decimal equivalent.

ALGORITHM :
Step 1: Start
Step 2: read a roman number
Step 3: len c←length of the roman number
step 4: convert the roman numbers into integers and store in an array A
step 5: k ← A[len-1]
step 6: i ← len-1
step 7: if a[i] greater than a[i-1] then k← k-a[i-1];
step 8: if a[i] is equal to a[i-1] or a[i] less than a[i-1]) then k←k+a[i-1];
step 9: i←i - 1
step 10: repeat steps 7,8 and 9 until i > 0
Step 11: print k
Step 12: stop
Program to convert a Roman numeral to its decimal equivalent.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int *a,len,i,j,k;
char *rom;
printf("Enter the Roman Numeral:");
scanf("%s",rom);
len=strlen(rom);
for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;
else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else if(rom[i]=='C')
[i]=100;
else if(rom[i]=='D')
a[i]=500;
else if(rom[i]=='M')
a[i]=1000;
else
{
printf("\nInvalid Value");
exit(0);
}
}
k=a[len-1];
for(i=len-1;i>0;i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1] || a[i]<a[i-1])
k=k+a[i-1];
}
printf("\nIts Decimal Equivalent is:");
printf("%d",k);
}

OUTPUT

INPUT:

Enter the Roman Numeral : XXVIII

RESULT:

Its Decimal Equivalent is : 28


Addition and Multiplication of two complex number

ALGORITHM :

Step 1: Start
Step 2: read two complex number
Step 3: Add two complex numbers
Step 4: Multiply two complex numbers
Step 5: print the result
Step 6: stop
Program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex number

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct complex
{
float real;
float imag;
};
typedef struct complex c;
void main()
{
int ch;
struct complex add(struct complex,struct complex);
struct complex sub(struct complex,struct complex);
struct complex mul(struct complex,struct complex);
struct complex div(struct complex,struct complex);
c c1,c2,c3;
clrscr();
printf("Enter first complex ");
scanf("%f%f",&c1.real,&c1.imag);
printf("Enter second complex ");
scanf("%f%f",&c2.real,&c2.imag);
do
{
printf("\n1.Addition");
printf("\n2.Subtraction");
printf("\n3.Multiplication");
printf("\n4.Division");
printf("\n5.exit");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{

case 1:c3=add(c1,c2);
printf("%.2f+i%.2f",c3.real,c3.imag);
break;
case 2:c3=sub(c1,c2);
printf("%.2f+i%.2f",c3.real,c3.imag);
break;
case 3:c3=mul(c1,c2);
printf("%.2f+i%.2f",c3.real,c3.imag);
break;
case 4:c3=div(c1,c2);
printf("%.2f+i%.2f",c3.real,c3.imag);
break;
case 5:exit(0);

}
}while(ch!=5);
getch();
}
c add(c x,c y)
{
c z;
z.real=x.real+y.real;
z.imag=x.imag+y.imag;
return z;
}
c sub(c x,c y)
{
c z;
z.real=x.real-y.real;
z.imag=x.imag-y.imag;
return z;
}
c mul(c x,c y)
{
c z;
z.real=(x.real*y.real)-(x.imag*y.imag);
z.imag=(x.real*y.imag)+(x.imag*y.real);
return z;
}
c div(c x,c y)
{
c z;
z.real=((x.real*y.real)+(x.imag*y.imag))/((x.real*x.real)+(x.imag*x.imag));

z.imag=((y.imag*x.real)+(x.real*y.imag))/((x.real*x.real)+(x.imag*x.imag));
return z;
}

OUTPUT

INPUT:

Enter first complex 2.5 6.5

Enter second complex 4 9

RESULT:

1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter ur choice :1

Addtion : 6.50+i15.50

1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter ur choice :3

Multiplication : -48.50+i48.50
To copy one file to another file

ALGORITHM :

Step 1: Start
Step 2: read scource file fn and target file tr
Step 3: open fn in read mode and tr in write mode
Step 4: check whether both the files have been opened or not
Step 5: read character by character from fn and write into tr until fn encounters end of file
Step 6: close both files
Step 7: stop
Program to copy one file to another

#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
FILE *fs,*ft;
char ch;
clrscr();
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL)
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}

OUTPUT

INPUT: Enter two file name in command line arguments


aa.txt bb.txt

RESULT: The contents of aa.txt are copied into bb.txt


To reverse the first n characters in a file

ALGORITHM :

Step 1: Start
Step 2: read file name fn
Step 3: open fn in write mode
Step 4: check whether the file has been opened or not
Step 5: read n character from fn and write into tr until it fn encounters end of file
Step 6: close both files
Step 7: stop
program to reverse the first n characters in a file.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>

void main(int argc, char *argv[])


{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;

if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
getch();
}
OUTPUT

INPUT
RESULT

Single Linked List

ALGORITHM :

INSERTING

Step 1: Begin
Step 2: if the list is empty or the new node comes before the head node then,
Insert the new node as the head node
Step 3: else if the new node comes after the last node then insert the new node at the end
Step 4: else insert the new node in the body of the list.
Step 5: End

DELETING

Step 1: Begin
Step 2: if the list is empty then, node cannot be deleted
Step 3: else if the node to be deleted is the first node, t
hen make the head to point to ht second node
Step 4: else delete the node from the body of the list.
Step 5: End

Single Linked List

#include <stdio.h>
#include <stdlib.h>
#define NULL 0

struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node; /* node type defined */

main()
{
node *head;
void create(node *p);
int count(node *p);
void print(node *p);
head = (node *)malloc(sizeof(node));
create(head);
printf("\n");
printf(head);
printf("\n");
printf("\nNumber of items = %d \n", count(head));
}
void create(node *list)
{
printf("Input a number\n");
printf("(type -999 at end): ");
scanf("%d", &list -> number); /* create current node */

if(list->number == -999)
{
list->next = NULL;
}

else /*create next node */


{
list->next = (node *)malloc(sizeof(node));
create(list->next); */ Recursion occurs */
}
return;
}
void print(node *list)
{
if(list->next != NULL)
{
printf("%d-->",list ->number); /* print current item */

if(list->next->next == NULL)
printf("%d", list->next->number);
print(list->next); /* move to next item */
}
return;

int count(node *list)


{

if(list->next == NULL)
return (0);
else
return(1+ count(list->next));
}

OUTPUT

INPUT

Input a number
(type -999 to end); 60
Input a number
(type -999 to end); 20
Input a number
(type -999 to end); 10
Input a number
(type -999 to end); 40
Input a number
(type -999 to end); 30
Input a number
(type -999 to end); 50
Input a number
(type -999 to end); -999

RESULT

60 -->20 -->10 -->40 -->30 -->50 --> -999


Number of items = 6

Inserting an item into a linked list

node *insert(node *head)


{
node *find(node *p, int a);
node *new; /* pointer to new node */
node *n1; /* pointer to node preceding key node */
int key;
int x; /* new item (number) to be inserted */

printf("Value of new item?");


scanf("%d", &x);
printf("Value of key item ? (type -999 if last) ");
scanf("%d", &key);

if(head->number == key) /* new node is first */


{
new = (node *)malloc(size of(node));
new->number = x;
new->next = head;
head = new;
}
else /* find key node and insert new node */
{ /* before the key node */
n1 = find(head, key); /* find key node */

if(n1 == NULL)
printf("\n key is not found \n");
else /* insert new node */
{
new = (node *)malloc(sizeof(node));
new->number = x;
new->next = n1->next;
n1->next = new;
}
}
return(head);
}
node *find(node *lists, int key)
{
if(list->next->number == key) /* key found */
return(list);

else

if(list->next->next == NULL) /* end */


return(NULL);
else
find(list->next, key);
}

Function for deleting an item from linked list.

node *delete(node *head)


{
node *find(node *p, int a);
int key; /* item to be deleted */
node *n1; /* pointer to node preceding key node */
node *p; /* temporary pointer */
printf("\n What is the item (number) to be deleted?");
scanf("%d", &key);
if(head->number == key) /* first node to be deleted) */
{
p = head->next; /* pointer to 2nd node in list */
free(head); /* release space of key node */
head = p; /* make head to point to 1st node */
}
else
{
n1 = find(head, key);
if(n1 == NULL)
printf("\n key not found \n");
else /* delete key node */
{
p = n1->next->next; /* pointer to the node
following the keynode */

free(n1->next); /* free key node */


n1->next = p; /* establish link */
}
}
return(head);
}
/* USE FUNCTION find() HERE */

Program for creation of sorted list from a given list of numbers.

#include <stdio.h>
#include <stdlib.h>
#define NULL 0

struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node;

main ()
{
int n;
node *head = NULL;
void print(node *p);
node *insert_Sort(node *p, int n);

printf("Input the list of numbers.\n");


printf("At end, type -999.\n");
scanf("%d",&n);

while(n != -999)
{
if(head == NULL) /* create 'base' node */
{
head = (node *)malloc(sizeof(node));
head ->number = n;
head->next = NULL;

else /* insert next item */


{
head = insert_sort(head,n);
}
scanf("%d", &n);
}
printf("\n");
print(head);

print("\n");

}
node *insert_sort(node *list, int x)
{
node *p1, *p2, *p;
p1 = NULL;
p2 = list; /* p2 points to first node */

for( ; p2->number < x ; p2 = p2->next)


{
p1 = p2;

if(p2->next == NULL)
{
p2 = p2->next; /* p2 set to NULL */
break; /* insert new node at end */
}
}

/* key node found */


p = (node *)malloc(sizeof(node)); /* space for new node */
p->number = x; /* place value in the new node */
p->next = p2; /* link new node to key node */
if (p1 == NULL)
list = p; /* new node becomes the first node */
else
p1->next = p; /* new node inserted after 1st node */
return (list);
}
void print(node *list)
{
if (list == NULL)
printf("NULL");
else
{
printf("%d-->",list->number);
print(list->next);
}
return;
}

OUTPUT

INPUT :

Input the list of number.


At end, type -999.

80 70 50 40 60 -999

RESULT :

40-->50-->60-->70-->80-->NULL
Double Linked List

INSERTING

Step 1: Begin
Step 2: if the list is empty or the new node comes before the head node then,
Insert the new node as the head node
Step 3: else if the new node comes after the last node then insert the new node at the end
Step 4: else insert the new node in the body of the list.
Step 5: End

DELETING

Step 1: Begin
Step 2: if the list is empty then, node cannot be deleted
Step 3: else if the node to be deleted is the first node, t
hen make the head to point to ht second node
Step 4: else delete the node from the body of the list.
Step 5: End
Double Linked List

#include "stdio.h"
#include "alloc.h"
typedef struct dubll
{
int data;
struct dubll *leftlink,*rightlink;
}*DUBLL;
DUBLL high,temp_node,low,last,pntr;
int flag=0;
DUBLL NodeAlloc();
DUBLL Search(int,int);
void CreateItem();
void AppendItem();
void PrintItem();
void DeleteItem();
DUBLL Search(int item,int flag);
DUBLL NodeAlloc();
void InsertItem();
void main(void)
{
int choice,Item;
high=NULL;
while(1)
{
clrscr();
printf("\n \t\t\t***** M A I N M E N U *****\n\n");
printf("\n 1: Create Linked List \n 2: Append a Node to the List \n 3: Traverse the List \n 4:
Delete a Node from the List \n 5: Search a Node \n 6: Insert a Node to the List \n 7: Close \n\n\t\t
Enter your Option [ ]\b\b");
scanf("%d",&choice);
switch(choice)
{
case 1:
CreateItem();
puts("\nPress any key to go back to main menu.");
getch();
break;
case 2:
AppendItem();
break;
case 3:

PrintItem();
puts("\nPress any key to go back to main menu.");
getch();
break;
case 4:
DeleteItem();
break;
case 5:
printf("Find an Item: ");
scanf("%d",&Item);
temp_node=Search(Item,0);
if(temp_node)
{
puts("The item is available in the Linked List.");
}
else
{
puts("The item is not found in the Linked List.");
}
getch();
break;
case 6:
InsertItem();
break;
case 7:
exit();
default:
puts("Invalid choice.");
puts("\nPress any key to go back to main menu.");
getch();
break;
}
}
}
/* Function to Create the list*/
void CreateItem()
{
if(high==NULL)
{
printf("\n --Creating the list--");
temp_node=NodeAlloc();
printf("\n Enter starting data (as integer value) :");

scanf("%d",&temp_node->data);
high=temp_node;
}
else{ printf("\n List already created @ %d with %d as data.",high,high->data);}
}

/* Function to Append items to the list*/


void AppendItem()
{
low=high;
if(high==NULL)
{
CreateItem();
}
else
{
temp_node=NodeAlloc();
printf("\n Enter Item (in integer) :");
scanf("%d",&temp_node->data);
temp_node->rightlink=NULL;

while(low->rightlink!=NULL)
low=low->rightlink;
low->rightlink=temp_node;
temp_node->leftlink=low;
last=low->rightlink;

}
}
/* Function to Traverse the list both ways and print the data*/
void PrintItem()
{
DUBLL temp_node;
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
getch();
CreateItem();
}
temp_node=high;

last=low->rightlink;
printf("\n--Printing The List In Forward direction--\n");

while(temp_node!=NULL) //In forward direction


{
printf("\t %d",temp_node->data);
temp_node = temp_node->rightlink;
}
printf("\n");
printf("\n--Printing The List In Backward direction--\n");
temp_node=high;
if(temp_node->rightlink==NULL){printf("%d",temp_node->data);return; }
while(last!=NULL) //In backward direction
{
printf("\t %d",last->data);
last = last->leftlink;
}
}

/* Function to Delete items of the list*/


void DeleteItem()
{
int value;
DUBLL temp_node;
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
getch();
CreateItem();
}
printf("\n Item to delete :");
scanf("%d",&value);
pntr=Search(value,1);
pntr->leftlink->rightlink=pntr->rightlink;
pntr->rightlink->leftlink=pntr->leftlink;
temp_node=pntr;
free(temp_node);
}

/* Function to Search an item from the list*/


DUBLL Search(int item,int flag)
{
temp_node = high;
if(high==NULL)

{
printf("\n List is not available. Please create a list first.");
getch();
CreateItem();
}
while(temp_node!=NULL)
{
if(temp_node->data==item )
{
if(flag==0)
{
return(1);
}
else
{
return(temp_node);
}
}
temp_node=temp_node->rightlink;
}
}
/* Function to Allocate nodes*/
DUBLL NodeAlloc()
{
DUBLL tmep_node;
tmep_node=malloc(sizeof(struct dubll));
if(tmep_node==NULL)
{
printf("\n No memory available. Node allocation cannot be done.");
}
tmep_node->rightlink=tmep_node->leftlink=NULL;
return(tmep_node);
}
/* Function to Insert items in the middle of the list*/
void InsertItem()
{
int node;
DUBLL temp_node;

if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
getch();
CreateItem();

}
temp_node=NodeAlloc();
printf("Position At which node to be inserted: ___ & New Item Value: ___ ");
scanf("%d",&node);
scanf("%d",&temp_node->data);
pntr=Search(node,1);
if(pntr->rightlink==NULL)
{
printf("\n The operation is not possible.");
getch(); return;
}
temp_node->leftlink=pntr; //creating link to new node
temp_node->rightlink=pntr->rightlink;
pntr->rightlink->leftlink=temp_node;
pntr->rightlink=temp_node;

printf("\n Item has been Inserted.");


getch();
}

OUTPUT:
***** M A I N M E N U *****

1: Create Linked List


2: Append a Node to the List
3: Traverse the List
4: Delete a Node from the List
5: Search a Node
6: Insert a Node to the List
7: Close
Enter your Option [ 1]

Creating the list--


Enter starting data (as integer value) :
11 22 33 44 55 66

***** M A I N M E N U *****

1: Create Linked List


2: Append a Node to the List
3: Traverse the List
4: Delete a Node from the List
5: Search a Node
6: Insert a Node to the List
7: Close
Enter your Option [ 3]

--Printing The List In Forward direction--


11 22 33 44 55 66

--Printing The List In Backward direction--


66 55 44 33 22 11
Press any key to go back to main menu.

***** M A I N M E N U *****

1: Create Linked List


2: Append a Node to the List
3: Traverse the List
4: Delete a Node from the List
5: Search a Node
6: Insert a Node to the List
7: Close
Enter your Option [ 2]

Enter Item (in integer) :88

***** M A I N M E N U *****

1: Create Linked List


2: Append a Node to the List
3: Traverse the List
4: Delete a Node from the List
5: Search a Node
6: Insert a Node to the List
7: Close

Enter your Option [ 3]

--Printing The List In Forward direction--


11 22 33 44 55 66 88

--Printing The List In Backward direction--


88 66 55 44 33 22 11
Press any key to go back to main menu.
Stacks using Arrays

Definition :

Lists permit the insertion or deletion of an element to occur only at one end. A linear list
belonging to this subclass is called a stack. They are also referred to as pushdown lists.

The insertion operation is referred to as PUSH and the deletion operation as POP. The most
accessible element in a stack is known as the TOP of the stack.

Since insertion and deletion operations are performed at one end of stack, the elements can only
be removed in the opposite order from that in which they were added to the stack. Such a linear
list is frequently referred to as a LIFO ( Last-In First-Out ) LIST.

An example of stack is the “in” tray of a busy executive. The files pile up in the tray and whenever
the executive has time to clear the files, he/she takes it off from the top. That is, files are added at
the top and removed from the top. Therefore stacks are sometimes referred to as LIFO structure.

A pointer TOP

A pointer TOP keeps track of the top element in the stack. Initially when the stack is empty,
TOP has a value of –1 and when the stack contains a single element, TOP has a value of 0 ( Zero )
and so on. Each time a new element is inserted in the stack, the pointer is incremented by 1. The
pointer decrements by 1 each time a deletion is made from the stack.
ALGORITHM :

Procedure PUSH(S,TOP,X) : This procedure inserts an element X to the top of the stack
which is represented by a vector S consisting MAX elements with a pointer TOP denoting
the top element in the stack.
STEP 1 : [Check for stack underflow]
If (TOP>=max-1)
then write(stack overflow)
Return
STEP 2 : [Increment TOP]
TOP <-- TOP+1
STEP 3 : [Insert element]
S[TOP] <-- X
STEP 4 : [Finished] Return
The first step of this algorithm checks for an overflow condition. If such a condition exists,
then the insertion can't be performed and an appropriate error message results.

Procedure POP(S,TOP,X) : This procedure removes top element from the stack.
STEP 1 : [Check for the underflow on stack]
If (TOP<0)
then write(stack underflow)
Return
STEP 2 : [Hold the former top element of stack into X]
X <-- S[TOP]
STEP 3 : [Decrement the TOP pointer or index by 1]
TOP <-- TOP-1
STEP 4 : [finished-Return the popped item from the stack]
Return(X)
As Underflow condition is checked for in the first step of the algorithm. If such a condition
exists, then the deletion cannot be performed and an appropriate error message results
Procedure Display(S,TOP) : This procedure displays the contents of the stack i.e., vector
S.
STEP 1 : [check for empty on stack]
if (TOP==-1)
then write('stack empty')
Return
STEP 2 : [Repeat through STEP 3 from i=TOP to 0]
Repeat through STEP 3 for i=TOP to 0 STEP-1]
STEP 3 : [Display the stack content]
write (S[i])
STEP 4 : [Finished]
Return
The first step of this algorithm checks for an empty condition. If such a condition exists,
then the contents of the stack cannot be displayed and an appropriate error message results.
Stack (its operations) using Arrays

#include<stdio.h>
#include<conio.h>
int st_arr[20];
int t=-1;
void push_ele(int ele);
int pop_ele();
void display_ele();
void main()
{
char choice,num1=0,num2=0;
while(1)
{
clrscr();
printf("======================================");
printf("\n\t\t MENU ");
printf("\n======================================");
printf("\n[1] Using Push Function");
printf("\n[2] Using Pop Function");
printf("\n[3] Elements present in Stack");
printf("\n[4] Exit\n");
printf("\n\tEnter your choice: ");
fflush(stdin);
scanf("%c",&choice);
switch(choice-'0')
{
case 1:
{
printf("\n\tElement to be pushed: ");
scanf("%d",&num1);
push_ele(num1);
break;
}
case 2:
{
num2=pop_ele(1);
printf("\n\tElement to be popped: %d\n\t",num2);
getch();
break;
}
case 3:
{

display_ele();
getch();
break;
}

case 4:
exit(1);
break;
default:
printf("\nYour choice is invalid.\n");
break;
}
}
}
/* Push() function. */
void push_ele(int ele)
{
if(t==99)
{
printf("STACK is Full.\n");
getch();
exit(1);
}
st_arr[++t]=ele;
}
/*Pop() function. */
int pop_ele()
{
int ele1;
if(t==-1)
{
printf("\n\tSTACK is Empty.\n");
getch();
exit(1);
}
return(st_arr[t--]);
}
/*Implementing display() function. */
void display_ele()
{
int k;

printf("\n\tElements present in the stack are:\n\t");


for(k=0;k<=t;k++)
printf("%d\t",st_arr[k]);
}
Stacks using Pointers

Write C programs that implement stack (its operations) using ii) Pointers

#include<stdio.h>
#include<conio.h>
struct st_point
{
int ele;
struct st_point *l;
}*t;
int i;
void push_ele(int j);
int pop_ele();
void display_ele();
void main()
{
char choice,num1=0,num2=0;
int i;
while(1)
{
clrscr();
printf("======================================");
printf("\n\t\t MENU ");
printf("\n======================================");
printf("\n[1] Using Push Function");
printf("\n[2] Using Pop Function");
printf("\n[3] Elements present in Stack");
printf("\n[4] Exit\n");
printf("\n\tEnter your choice: ");
scanf("%c",&choice);
switch(choice-'0')
{
case 1:
{
printf("\n\tElement to be pushed:");
scanf("%d",&num1);
push_ele(num1);
break;
}
case 2:
{
num2=pop_ele(1);

printf("\n\tElement to be popped: %d\n\t",num2);


break;
}

case 3:
{
printf("\n\tElements present in the stack are:\n\t");
display_ele();
getch();
break;
}
case 4: exit(1);
default:
printf("\nYour choice is invalid.\n");
}
}
}

/*Inserting the elements using push function*/


void push_ele(int j)
{
struct st_point *m;
m=(struct st_point*)malloc(sizeof(struct st_point));
m->ele=j;
m->l=t;
t=m;
return;
}

/*Removing the elements using pop function*/


int pop_ele()
{
if(t==NULL)
{
printf("\n\STACK is Empty.");
getch(); exit(1);
}
else
{
int i=t->ele;
t=t->l;
return (i);
}

return 0;
}

/*Displaying the elements */


void display_ele()
{
struct st_point *pointer=NULL;
pointer=t;
while(pointer!=NULL)
{
printf("%d\t",pointer->ele);
pointer=pointer->l;
}
}

OUTPUT:

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 1

Element to be pushed: 10

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 1


Element to be pushed: 25

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 1

Element to be pushed: 30

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 1

Element to be pushed: 35

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 1

Element to be pushed: 40

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 3

Elements present in the stack are:


10 25 30 35 40
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 3

Elements present in the stack are:


10 25 30 35 40

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 2

Element to be popped: 40

MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit

Enter your choice: 3

Elements present in the stack are:


10 25 30 35
QUEUE STRUCTURE

Definition :

Lists permit deletions to be performed at one end of a list and insertions at the other end.
The information in such a list is processed in the same order as it was received, i.e. on a first-in,
first-out (FIFO) or first-come first-serve (FCFS) basis. This type of list is referred to as a Queue.

FRONT : Pointer to the front element of a queue

REAR : Pointer to the rear element of a queue

Types of Queues

• Linear Queue
• Circular Queue
• Prioirity Queue

The insertion operation is referred to as QINSERT and the deletion operation as QDELETE. We
can insert an item at the rear end using QINSERT and remove an item at the front end using
QDELETE

A pointer FRONT and REAR

FRONT and REAR, pointers to the front and rear elements of queue respectively. Each time
a new element is inserted in the queue, the REAR pointer is incremented by one. The FRONT
pointer is incremented by 1 each time a deletion is made from the queue. FRONT and REAR
pointers should be reset to -1 once they are found equal
LINEAR QUEUE

ALGORITHM :

Procedure QINSERT(Q,F,MAX,X) : Given F and R, pointers to the front and rear elements of a
queue. A QUEUE Q consisting of MAX elements and an element X. this procedure inserts X at
the rear end of the queue prior to the first invocation of the procedure, F and R have been set to -1.

STEP 1: [Is front pointer properly set]


if (F==R)
then F <-- R <-- -1

STEP 2: [Check for overflow condition]


if (R>=(MAX-1))
then write ('Error : Overflow')
Return

STEP 3: [Increment rear pointer]


R <-- R+1

STEP 4: [Insert element]


Q[R] <-- X
Return

Procedure QDELETE(Q,F,R) : Given F and R,the pointers to the front and rear elements of a
queue respectively and the queue Q to which they correspond. This procedure delets and returns
the element at the front end of the queue .Here X is a temporary variable.

STEP 1: [Check for underflow condition]


if (F>=R)
then write('Error : Underflow']
Return

STEP 2: [Increment the front pointer]


F <-- F+1
STEP 3: [Delete element]
Y <-- Q[F]
Return Y

Programs that implement Queue (its operations) using Arrays

#include<stdio.h>
#include<alloc.h>
#include<conio.h>
#define size 10
#define true 1
#define false 0

struct q_arr
{
int f,r;
int num;
int a[size];
};

void init(struct q_arr* queue);


int e_que(struct q_arr* queue);
int f_que(struct q_arr* queue);
int add_ele(struct q_arr* queue,int);
int rem_ele(struct q_arr* queue);
void display_ele(struct q_arr* queue);

/*main function*/
void main()
{
int ele,k;
int ch;

struct q_arr *queue = (struct q_arr*)malloc(sizeof(struct q_arr));


init(queue);

while(1)
{
clrscr();
printf("\n\n****IMPLEMENTATION OF QUEUE USING ARRAYS****\n");
printf("============================================");
printf("\n\t\tMENU\n");
printf("============================================");
printf("\n\t[1] To insert an element");
printf("\n\t[2] To remove an element");
printf("\n\t[3] To display all the elements");
printf("\n\t[4] Exit");
printf("\n\n\t Enter your choice: ");

scanf("%d",&ch);

switch(ch)
{
case 1:
{
printf("\nElement to be inserted:");
scanf("%d",&ele);
add_ele(queue,ele);
break;
}

case 2:
{
if(!e_que(queue))
{
k=rem_ele(queue);
printf("\n%d element is removed\n",k);
getch();
}
else
{
printf("\tQueue is Empty. No element can be removed.");
getch();
}
break;
}

case 3:
{
display_ele(queue);
getch();
break;
}

case 4:
exit(0);
default:
printf("\tInvalid Choice.");
getch();
break;

}
}
}
/*end main*/

void init(struct q_arr* queue)


{
queue->f = 0;
queue->r = -1;
queue->num = 0;
}

/* Function to check is the queue is empty*/


int e_que(struct q_arr* queue)
{
if(queue->num==0)
return true;
return false;
}

/* Function to check if the queue is full*/


int f_que(struct q_arr* queue)
{
if(queue->num == size)
return true;
return false;
}

/* Function to add an element to the queue*/


int add_ele(struct q_arr* queue,int j)
{
if(f_que(queue))
return false;

if(queue->r == size - 1)
queue->r = -1;
queue->a[++queue->r] = j;
queue->num++;
return true;
}

/* Function to remove an element of the queue*/


int rem_ele(struct q_arr* queue)
{

int j;
if(e_que(queue))
return -9999;
j = queue->a[queue->f++];
if(queue->f == size)
queue->f = 0;
queue->num--;
return j;
}

/* Function to display the queue*/


void display_ele(struct q_arr* queue)
{
int j;
if(e_que(queue))
{
printf("Queue is Empty. No records to display.");
return;
}
printf("\nElements present in the Queue are: ");
for(j=queue->f;j<=queue->r;j++)
printf("%d\t",queue->a[j]);
printf("\n");
}
Queues using Pointers

Write C programs that implement Queue (its operations) using ii) Pointers

#define true 1
#define false 0
#include<stdio.h>
#include<conio.h>
#include<process.h>

struct q_point
{
int ele;
struct q_point* n;
};

struct q_point *f_ptr = NULL;

int e_que(void);
void add_ele(int);
int rem_ele(void);
void show_ele();

/*main function*/
void main()
{
int ele,choice,j;
while(1)
{
clrscr();
printf("\n\n****IMPLEMENTATION OF QUEUE USING POINTERS****\n");
printf("==============================================");
printf("\n\t\t MENU\n");
printf("==============================================");
printf("\n\t[1] To insert an element");
printf("\n\t[2] To remove an element");
printf("\n\t[3] To display all the elements");
printf("\n\t[4] Exit");
printf("\n\n\tEnter your choice:");
scanf("%d", &choice);

switch(choice)
{

case 1:
{
printf("\n\tElement to be inserted:");
scanf("%d",&ele);
add_ele(ele);
getch();
break;
}

case 2:
{
if(!e_que())
{
j=rem_ele();
printf("\n\t%d is removed from the queue",j);
getch();
}
else
{
printf("\n\tQueue is Empty.");
getch();
}
break;
}

case 3:
show_ele();
getch();
break;

case 4:
exit(1);
break;

default:
printf("\n\tInvalid choice.");
getch();
break;
}

}
}

/* Function to check if the queue is empty*/


int e_que(void)
{
if(f_ptr==NULL)
return true;
return false;
}

/* Function to add an element to the queue*/


void add_ele(int ele)
{
struct q_point *queue = (struct q_point*)malloc(sizeof(struct q_point));
queue->ele = ele;
queue->n = NULL;
if(f_ptr==NULL)
f_ptr = queue;
else
{
struct q_point* ptr;
ptr = f_ptr;
for(ptr=f_ptr ;ptr->n!=NULL; ptr=ptr->n);
ptr->n = queue;
}
}

/* Function to remove an element from the queue*/


int rem_ele()
{
struct q_point* queue=NULL;
if(e_que()==false)
{
int j = f_ptr->ele;
queue=f_ptr;
f_ptr = f_ptr->n;
free (queue);
return j;
}
else
{
printf("\n\tQueue is empty.");
return -9999;
}
}

/* Function to display the queue*/


void show_ele()
{
struct q_point *ptr=NULL;
ptr=f_ptr;
if(e_que())
{
printf("\n\tQUEUE is Empty.");
return;
}
else
{
printf("\n\tElements present in Queue are:\n\t");
while(ptr!=NULL)
{
printf("%d\t",ptr->ele);
ptr=ptr->n;
}
}
}

OUTPUT:
****IMPLEMENTATION OF QUEUE USING POINTERS****

INPUT :
==============================
MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 1
Element to be inserted : 45
===============================
MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 1
Element to be inserted : 35
===============================
MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 1
Element to be inserted : 99
===============================
MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 3
Elements present in the queue are :
45 35 99
==================================
MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 2
45 is deleted
================================

MENU
[1] To insert an element
[2] To remove an element
[3] To display all the elements
[4] Exit
Enter your choice: 3

Elements present in the queue are :


35 99
Infix notation to Postfix

z:

A + ( B * C ) Paranthesis for emphasis


A + ( BC* ) Convert the multiplication
A ( BC* ) + Convert the addition
ABC*+ Postfix form

The only rules to remember during the conversion process are that operations with highest
precedence are converted first and that after a portion of the expression has been converted to
postfix, it is to be treated as a single operand. Consider the same example with the precedence
of operators reversed by the deliberate insertion of parenthesis.

( A + B ) * C Infix form
( AB+ ) * C Convert the addition
( AB+ ) C * Convert the multiplication
AB+C* Postfix form

In the above example the addition is converted before the multiplication because of the
parenthesis. In going from ( A + B ) * C to ( AB+ ) * C, A and B are the operands and + is the
operator. In going from ( AB+ ) * C to ( AB+ ) C *, ( AB+ ) and C are the operands and * is
the operator. The rules for converting from infix to postfix are simple, providing that you
know the order of precedence.
Infix to Postfix

ALGORITHM :

STEP 1 : Read the given infix expression into string called infix.

STEP 2 : Read one character at a time and perform the following operations :

1. If the read character is an operand, then add the operand to the postfix string.
2. If the read character is not an operand, then check
If the stack is not empty and precedence of the top of the
stack operator is higher than the read operator,
then pop the operator from stack and add this
operator to the postfix string.
Else push the operator onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : If stack is not empty, then pop the operator from stack and add this operator

to the postfix string.

STEP 5 : Repeat STEP 4 till all the operators are popped from the stack.

STEP 6 : Display the result of given infix expression or resultant postfix expression

stored in a string called postfix from this algorithm.


Converting an infix expression to a postfix expression

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void push(char);
char pop();
char post[100],infix[100],stack[100],t,x;
int top=-1,i=0,j=0;
void check();
int priority(char);
void main()
{
clrscr();
printf("\nEnter the infix expression:");
gets(infix);
push('#');
while(infix[i]!='\0')
{
t=infix[i];
if(isalpha(t))
push(t);
else if(t=='+' ||t=='-' ||t=='*' ||t=='/'||t=='^' ||t=='(' || t==')')
{
switch(t)
{
case '+':
case '-':check();
push(t);
break;
case '*':
case '/':check();
push(t);
break;
case '(':push(t);
break;
case ')':
x=pop();
do
{
post[j++]=x;

}while((x=pop())!='(');
break;
}
}
i++;
}
x=pop();
do
{
post[j++]=x;
}while((x=pop())!='#');
post[j]='\0';
printf("Infix : %s Postfix :%s",infix,post);
getch();

}
void push(char c)
{
stack[++top]=c;
}
char pop()
{
return(stack[top--]);
}
void check()
{
if(priority(t)>=priority(stack[top]))
post[j++]=pop();
}
int priority(char op)
{
int p;
switch(op)
{
case '^':p=3;
break;
case '+':
case '-':p=2;
break;
case '*':
case '/':p=1;
break;

default:p=0;
}
return p;
}

OUTPUT

COVERSION OF INFIX EXPRESSION TO POSTFIX EXPRESSION

INPUT:

Enter the infix string : A + B * C - D

RESULT :

Infix String : A + B * C – D

Postfix String : ABC*+D-


Evaluation of Postfix Expression

ALGORITHM :

STEP 1 : Read the given postfix expression into a string called postfix.

STEP 2 : Read one character at a time & perform the following operations :
1. If the read character is an operand, then convert it to float and push it onto the stack.
2. If the character is not an operand, then pop the operator from stack and assign to OP2.
Similarly, pop one more operator from stack and assign to OP1.
3. Evaluate the result based on operator x.
4. Push the result (based on operator x) onto the stack.

STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : Return the result from this procedure or algorithm and display the result in main
program.
Program to evaluate postfix expression

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<math.h>
void push(float);
float pop();
char post[100];
float st[100],x;
float res;
float evalpost();
float op1,op2;
int tos;
/*****************MAIN FUNCTION***************/
void main()
{
clrscr();
printf("\nEVALUATION OF POSTFIX EXPRESSION\n");
printf("\nEnter the postfix expression:");
gets(post);
tos=-1;
int i=0;
while(post[i]!='\0')
{
if(isalpha(post[i]))
{
printf("\nEnter value of %c :",post[i]);
scanf("%f",&x);
push(x);
}
else
{
op2=pop();
op1=pop();
//printf("\nop1=%f op2=%f",op1,op2);
switch(post[i])
{
case '+': res=op1+op2;
push(res);
break;
case '-': res=op1-op2;
push(res);

break;
case '*': res=op1*op2;
push(res);
break;
case '/': res=op1/op2;
push(res);
break;
case '^': res=pow(op1,op2);
push(res);
break;
}
}
i++;
}
printf("\nThe evaluation of the given expression is %f",pop());
getch();
}

/**************PUSH**************/
void push(float val)
{
st[++tos]=val;
}
/**************POP**************/

float pop()
{
return(st[tos--]);
}
OUTPUT

EVALUATION OF POSTFIX EXPRESSION

INPUT :

Enter the postfix expression:ABC*+D-

Enter value of A :2

Enter value of B :3

Enter value of C :4

Enter value of D :5

RESULT :

The evaluation of the given expression is 9.000000


Binary Tree

ALGORITHM :

Creating a Binary Tree

Step 1: Start
Step 2: Obtain a node and assign a value to the node
Step 3: Insert into a binary tree
Step 4: repeat 2 and 3 until stopped by the user
Step 5. stop

Preorder :
Step 1: Start
Step 2: Visit the root
Step 3: Traverse the left subtree in preorder
Step 4: Traverse the right subtree in preorder
Step 5: stop

Inorder :
Step 1: Start
Step 2: Traverse the left subtree in inorder
step 3: Visit the root
Step 4: Traverse the right subtree in inorder
Step 5: stop

Postorder :
Step 1: Start
Step 2: Traverse the left subtree in postorder
Step 3: Traverse the right subtree in postorder
step 4: Visit the root

Program to create a Binary Tree and traverse it in Preorder, Indorder and Postorder

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct btree
{
int info;
struct btree *lptr;
struct btree *rptr;
};
typedef struct btree Tree;
Tree *root,*node;
Tree *create(int,Tree*);
void preorder(Tree*);
void inorder(Tree*);
void postorder(Tree*);
void main()
{
int ch,no;
root=NULL;
clrscr();
do
{
printf("\n\t\tBINARY TREE\n");
printf("\n1.Create");
printf("\n2.Preorder");
printf("\n3.Inorder");
printf("\n4.Postorder");
printf("\n5.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nNote : Enter 0 to stop\n");
printf("\nEnter any integer value :\n");
scanf("%d",&no);
while(no!=0)
{
root=create(no,root);
scanf("%d",&no);
}
break;
case 2:
printf("\nPREORDER\n");
preorder(root);
break;
case 3:
printf("\nINORDER\n");
inorder(root);
break;
case 4:
printf("\nPOSTORDER\n");
postorder(root);
break;
case 5:
exit(0);
}
}while(ch!=5);
}

Tree *create(int data,Tree *t)


{
if(!t)
{
t=(Tree*)malloc(sizeof(Tree));
t->info=data;
t->lptr=NULL;
t->rptr=NULL;
}
if(data<t->info)
t->lptr=create(data,t->lptr);
if(data>t->info)
t->rptr=create(data,t->rptr);
return t;
}
void preorder(Tree *ptr)
{
if(ptr!=NULL)
{
printf("%3d",ptr->info);
preorder(ptr->lptr);
preorder(ptr->rptr);
}
}
void postorder(Tree *ptr)
{
if(ptr!=NULL)
{
postorder(ptr->lptr);
postorder(ptr->rptr);
printf("%3d",ptr->info);
}
}
void inorder(Tree *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->lptr);
printf("%3d",ptr->info);
inorder(ptr->rptr);
}
}
OUTPUT

CREATION OF BINARY TREE AND ITS TRAVERSALS

INPUT :
BINARY TREE

1. Create
2. Preorder
3. Inorder
4. Postorder
5. Exit
Enter your choice:1

Note : Enter 0 to stop

Enter any integer value :


20
22
8
21
17
9
5
14
18
0

RESULT :

BINARY TREE

1. Create
2. Preorder
3. Inorder
4. Postorder
5. Exit
Enter your choice:2

PREORDER
20 8 5 17 9 14 18 22 21
BINARY TREE

1. Create
2. Preorder
3. Inorder
4. Postorder
5. Exit
Enter your choice:3

INORDER
5 8 9 14 17 18 20 21 22

BINARY TREE

1. Create
2. Preorder
3. Inorder
4. Postorder
5. Exit
Enter your choice:4

POSTORDER
5 14 9 18 17 8 21 22 20
Linear Search

ALGORITHM :

step 1: start
step 2: read how many elements n
step 3: read n elements
step 4: enter the key element to be searched
step 5: compare the key element with n elements
step 6: if the element is found then write the element is found in postition else not found
step 7: stop
Program to implement Linear search using Reccursive and Non-Reccursive functions

#include <stdio.h>
#define MAX_LEN 10
void l_search_recursive(int l[],int num,int ele);
void l_search(int l[],int num,int ele);
void read_list(int l[],int num);
void print_list(int l[],int num);
void main()
{
int l[MAX_LEN], num, ele;
int ch;
clrscr();
printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Linary Search using Recursion method");
printf("\n[2] Linary Search using Non-Recursion method");
printf("\n\nEnter your Choice:");
scanf("%d",&ch);
if(ch<=2 & ch>0)
{
printf("Enter the number of elements :");
scanf("%d",&num);
read_list(l,num);
printf("\nElements present in the list are:\n\n");
print_list(l,num);
printf("\n\nElement you want to search:\n\n");
scanf("%d",&ele);
switch(ch)
{
case 1:printf("\n**Recursion method**\n");
l_search_recursive(l,num,ele);
getch();
break;

case 2:printf("\n**Non-Recursion method**\n");


l_search_nonrecursive(l,num,ele);
getch();
break;
}
}
getch();
}

/* Non-Recursive method*/
void l_search_nonrecursive(int l[],int num,int ele)
{
int j, f=0;
for(j=0;j<num;j++)
if( l[j] == ele)
{
printf("\nThe element %d is present at position %d in list\n",ele,j+1);
f=1;
break;
}
if(f==0)
printf("\nThe element is %d is not present in the list\n",ele);
}

/* Recursive method*/
void l_search_recursive(int l[],int num,int ele)
{
int f = 0;

if( l[num] == ele)


{
printf("\nThe element %d is present at position %d in list\n",ele,num+1);
f=1;
}
else
{
if((num==0) && (f==0))
{
printf("The element %d is not found.",ele);
}
else
{
l_search(l,num-1,ele);
}
}
getch();
}

void read_list(int l[],int num)


{
int j;
printf("\nEnter the elements:\n");

for(j=0;j<num;j++)
scanf("%d",&l[j]);
}

void print_list(int l[],int num)


{
int j;
for(j=0;j<num;j++)
printf("%d\t",l[j]);
}
OUTPUT

INPUT :
MENU
===================================
[1] Linary Search using Recursion method
[2] Linary Search using Non-Recursion method
Enter your Choice:1
Enter the number of elements :5
Enter the elements:
55 6 8 9 7
Element you want to search: 9

RESULT:

Elements present in the list are:


55 6 8 9 7
**Recursion method**
The element 9 is present at position 4 in the list.

INPUT:
MENU
=======================================
[1] Linary Search using Recursion method
[2] Linary Search using Non-Recursion method
Enter your Choice:2
Enter the number of elements :6
Enter the elements:
55 44 88 11 22 33

Element you want to search : 88

RESULT:

Elements present in the list are:


55 44 88 11 22 33
**Non-Recursion method**
The element 88 is present at position 3 in list
Binary Search

ALGORITHM :

step 1: start
step 2: read how many elements n
step 3: read n elements
step 4: enter the key element to be searched
step 5: sort the elements
step 6: compare the key element with n elements
step 7:
step 8: write the element is found in postition else not found
step 9: stop
Programs that use both recursive and non recursive functions to perform binary search
operations

#include <stdio.h>
#define MAX_LEN 10

/* Non-Recursive function*/
void b_search_nonrecursive(int l[],int num,int ele)
{
int l1,i,j, flag = 0;
l1 = 0;
i = num-1;
while(l1 <= i)
{
j = (l1+i)/2;
if( l[j] == ele)
{
printf("\nThe element %d is present at position %d in list\n",ele,j);
flag =1;
break;
}
else
if(l[j] < ele)
l1 = j+1;
else
i = j-1;
}
if( flag == 0)
printf("\nThe element %d is not present in the list\n",ele);
}

/* Recursive function*/
int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a)
{
int m,pos;
if (arrayStart<=arrayEnd)
{
m=(arrayStart+arrayEnd)/2;
if (l[m]==a)
return m;
else if (a<l[m])
return b_search_recursive(l,arrayStart,m-1,a);
else
return b_search_recursive(l,m+1,arrayEnd,a);
}
return -1;
}

void read_list(int l[],int n)


{
int i;
printf("\nEnter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&l[i]);
}

void print_list(int l[],int n)


{
int i;
for(i=0;i<n;i++)
printf("%d\t",l[i]);
}

/*main function*/
void main()
{
int l[MAX_LEN], num, ele,f,l1,a;
int ch,pos;

clrscr();

printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Binary Search using Recursion method");
printf("\n[2] Binary Search using Non-Recursion method");
printf("\n\nEnter your Choice:");
scanf("%d",&ch);

if(ch<=2 & ch>0)


{
printf("\nEnter the number of elements : ");
scanf("%d",&num);
read_list(l,num);
printf("\nElements present in the list are:\n\n");
print_list(l,num);
printf("\n\nEnter the element you want to search:\n\n");
scanf("%d",&ele);
switch(ch)
{
case 1:printf("\nRecursive method:\n");
pos=b_search_recursive(l,0,num,ele);
if(pos==-1)
{
printf("Element is not found");
}
else
{
printf("Element is found at %d position",pos);
}
getch();
break;

case 2:printf("\nNon-Recursive method:\n");


b_search_nonrecursive(l,num,ele);
getch();
break;
}
}
getch();
}

OUTPUT
INPUT :
==================================
MENU
==================================
[1] Binary Search using Recursion method
[2] Binary Search using Non-Recursion method
Enter your Choice:1

Enter the number of elements : 5

Enter the elements: 45 50 68 74 85

RESULT :

Elements present in the list are:


45 50 68 74 85

Enter the element you want to search : 68

Recursive method:
Element is found at 3 position

INPUT :
======================================================
MENU
=====================================================
[1] Binary Search using Recursion method
[2] Binary Search using Non-Recursion method
Enter your Choice:2

Enter the number of elements : 5

Enter the elements:


25 65 87 98 153

RESULT :

Elements present in the list are: 25 65 87 98 153

Enter the element you want to search : 98

Non-Recursive method:
The element 98 is present at position 3 in list
Bubble Sort

Definition :

Bubble Sort is an elementary sorting algorithm. It works by repeatedly exchanging adjacent


elements, if necessary. When no exchanges are required, the data is sorted.

ALGORITHM :

Procedure BubbleSort(A, MAX) : Here A is an array consisting of MAX elements. This


procedure sorts the elements in Ascending Order by repeatedly exchanging adjacent elements, if
necessary. Here 'temp' is a temporary variable used to exchange the adjacent elements in this
procedure.

ASCENDING ORDER
for i ← 1 to MAX do
for j ← MAX downto i+1 do
If A[j] < A[j-1] then
Exchange A[j] ↔ A[j-1]
Program to implement Bubble sort

#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
// Function for Bubble Sort
void bub_sort(int list[], int n)
{
int i,j;
for(i=0;i<(n-1);i++)
for(j=0;j<(n-(i+1));j++)
if(list[j] > list[j+1])
swapList(&list[j],&list[j+1]);
}
void readlist(int list[],int n)
{
int j;
printf("\nEnter the elements: \n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}
// Showing the contents of the list
void printlist(int list[],int n)
{
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}
void main()
{
int list[MAX], num;
printf(“\n”BUBBLE SORT”);
printf("\n\n\nEnter the number of elements [Maximum 10]\n");
scanf("%d",&num);
readlist(list,num);
printf("\n\nElements in the list before sorting are:\n");
printlist(list,num);
bub_sort(list,num);
printf("\n\nElements in the list after sorting are:\n");
printlist(list,num);
}

OUTPUT:

******BUBBLE SORT *****

INPUT :

Enter the number of elements [Maximum 10] : 6

Enter the elements:


55 44 11 66 88 5

RESULT :

Elements in the list before sorting are:


55 44 11 66 88 5

Elements in the list after sorting are:


5 11 44 55 66 88
QUICK SORT

Definition :

Quick Sort works on the principle of divide-and-conquer. It is an algorithm of choice in many


situations because it is not difficult to implement, it is a good "general purpose" sort and it
consumes relatively fewer resources during execution.

ALGORITHM : QUICK SORT

Procedure QuickSort(A, left, right) : Here A is an array consisting of MAX elements. This
procedure sorts the elements in Ascending or Descending Order based on the divide and conquer
method.

Quick Sort works by partitioning a given array A[p . . r] into two non-empty sub-array A[p . . q]
and A[q+1 . . r] such that every key in A[p . . q] is less than or equal to every key in A[q+1 . . r].
Then the two sub-arrays are sorted by recursive calls to Quick sort. The exact position of the
partition depends on the given array and index q is computed as a part of the partitioning
procedure.

Procedure QuickSort(A, left, right)

If left < right then


pivot = Partition (A, left, right)
Recursive call to QuickSort (A, left, pivot-1)
Recursive call to QuickSort (A, pivot+1, right)

PARTITION (A, p, r)
x = A[p]
i = p-1
j = r+1
while TRUE do
Repeat j = j-1
until A[j] ≤ x
Repeat i = i+1
until A[i] ≥ x
if i < j
then exchange A[i] = A[j]
else return j
Quick sort

#include <stdio.h>
#define MAX 10

void swap(int *m,int *n)


{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
int get_key_position(int x,int y )
{
return((x+y) /2);
}

// Function for Quick Sort


void quicksort(int list[],int m,int n)
{
int key,i,j,k;
if( m < n)
{
k = get_key_position(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
i++;
while((j >= m) && (list[j] > key))
j--;
if( i < j)
swap(&list[i],&list[j]);
}
swap(&list[m],&list[j]);
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
// Function to read the data
void read_data(int list[],int n)
{
int j;
printf("\n\nEnter the elements:\n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}

// Function to print the data


void print_data(int list[],int n)
{
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}

void main()
{
int list[MAX], num;
clrscr();
printf("\n***** Enter the number of elements Maximum [10] *****\n");
scanf("%d",&num);
read_data(list,num);
printf("\n\nElements in the list before sorting are:\n");
print_data(list,num);
quicksort(list,0,num-1);
printf("\n\nElements in the list after sorting are:\n");
print_data(list,num);
getch();
}
OUTPUT:

******QUICK SORT *****

INPUT :

Enter the number of elements [Maximum 10] : 10

Enter the elements:


15 4 11 6 28 25 9 35 45 3

RESULT :

Elements in the list before sorting are:


15 4 11 6 28 25 9 35 45 3

Elements in the list after sorting are:


3 4 6 9 11 15 25 28 35 45
Insertion Sort

Definition :

Insertion Sort is an example of an incremental algorithm. It builds the sorted sequence one
number at a time.

If the first few objects are already sorted, an unsorted object can be inserted in the sorted set in
proper place. This is called insertion sort. An algorithm consider the elements one at a time,
inserting each in its suitable place among those already considered (keeping them sorted).

ALGORITHM :

Procedure InsertionSort(A, MAX) : Here A is an array consisting of MAX elements. This


procedure sorts the elements in Ascending Order.

ASCENDING ORDER

For j = 2 to length [A] do


key = A[j]
Put A[j] into the sorted sequence A[1 . . j-1]
i = j-1
while i > 0 and A[i] > key do
A[i+1] = A[i]
i = i-1
A[i+1] = key
Program to implement Insertion sort

#include<stdio.h>
#include<conio.h>

void inst_sort(int []);

void main()
{
int num[5],count;
clrscr();
printf(“\n******INSERTION SORT******”);
printf("\nEnter the Five Elements to sort:\n");

for (count=0;count<5;count++)
scanf("%d",&num[count]);
inst_sort(num);

printf("\n\nElements after sorting: \n");


for(count=0;count<5;count++)
printf("%d\n",num[count]);
getch();
}

// Function for Insertion Sorting


void inst_sort(int num[])
{
int i,j,k;
for(j=1;j<5;j++)
{
k=num[j];
for(i=j-1;i>=0 && k<num[i];i--)
num[i+1]=num[i];
num[i+1]=k;
}
}
OUTPUT:

*****INSERTION SORT********

INPUT :

Enter the Five Elements to sort:


5
66
22
44
55

RESULT :

Elements after sorting:


5
22
44
55
66
Merge Sort

Definition :

Merge-sort is based on the divide-and-conquer paradigm. The Merge-sort algorithm can be


described in general terms as consisting of the following three steps:
1. Divide Step
If given array A has zero or one element, return S; it is already sorted. Otherwise, divide A into
two arrays, A1 and A2, each containing about half of the elements of A.

2. Recursion Step
Recursively sort array A1 and A2.

3. Conquer Step
Combine the elements back in A by merging the sorted arrays A1 and A2 into a sorted sequence.

ALGORITHM :

To begin, suppose that we have two sorted arrays A1[1], A1[2], . . , A1[M] and A2[1], A2[2], . . . ,
A2[N]. The following is a direct algorithm of the obvious strategy of successively choosing the
smallest remaining elements from A1 to A2 and putting it in A

MERGE (A1, A2, A)


i = j1
A1[m+1], A2[n+1] = INT_MAX
For k = 1 to m + n do
if A1[i] < A2[j]
then A[k] = A1[i]
i = i +1
else
A[k] = A2[j]
j=j+1

The Merge sort algorithm is as follows:

MERGE_SORT (A)

A1[1 . . floor(n/2)] = A[1 . . floor(n/2)]


A2[1 . . floor(n/2)] = A[1 + floor(n/2) . . n]
Merge Sort (A1)
Merge Sort (A1)
Merge Sort (A1, A2, A)
Program to implement Merge sort

#include <stdio.h>
#include <stdlib.h>
#define MAX_ARY 10
void merge_sort(int x[], int end, int start);
int main(void) {
int ary[MAX_ARY];
int j = 0;
printf("\n\nEnter the elements to be sorted: \n");
for(j=0;j<MAX_ARY;j++)
scanf("%d",&ary[j]);
/* array before mergesort */
printf("Before :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);
printf("\n");
merge_sort(ary, 0, MAX_ARY - 1);
/* array after mergesort */
printf("After Merge Sort :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);
printf("\n");
getch();
}
/* Method to implement Merge Sort*/
void merge_sort(int x[], int end, int start) {
int j = 0;
const int size = start - end + 1;
int mid = 0;
int mrg1 = 0;
int mrg2 = 0;
int executing[MAX_ARY];
if(end == start)
return;
mid = (end + start) / 2;
merge_sort(x, end, mid);
merge_sort(x, mid + 1, start);
for(j = 0; j < size; j++)
executing[j] = x[end + j];
mrg1 = 0;
mrg2 = mid - end + 1;
for(j = 0; j < size; j++) {
if(mrg2 <= start - end)
if(mrg1 <= mid - end)
if(executing[mrg1] > executing[mrg2])
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
else
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
}
}

OUTPUT:

*******MERGE SORT**********

Enter 10 elements to be sorted:


55
66
22
33
1
44
77
58
25
35
Before : 55 66 22 33 1 44 77 58 25 35
After Merge Sort : 1 22 25 33 35 44 55 58 66 77
Lagrange interpolation

ALGORITHM :

Step 1: Start
Step 2: read x, n
Step 3: for i=1 to n+1 in steps of 1 do read xi, fi
Step 4: sum ← 0
Step 5: for i=1 to n+1 in steps of 1 do
Step 6: prodfunc ← 1
Step 7: for j=1 to n+1 in steps of 1 do
Step 8: if (j ≠ i) then prodfunc ← prodfunc x ( x – xj ) / ( xi – xj )
endfor
Step 9: sum ← sum + fi * prodfunc
Remarks : sum is the value of f at x
endfor
Step 10: Write x, sum
Step 11: Stop
Program to implement the Lagrange interpolation

#include<stdio.h>
#include<conio.h>
#define MaxN 90

void main()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator, denominator, x, y=0;
int i, j, n;
clrscr();
printf("Enter the value of n: \n");
scanf("%d", &n);
printf("Enter the values of x and y: \n");
for(i=0; i<=n; i++)
scanf("%f%f", &arr_x[i], &arr_y[i]);
printf("Enter the value of x at which value of y is to be calculated: ");
scanf("%f", &x);
for (i=0; i<=n; i++)
{
numerator=1;
denominator=1;
for (j=0; j<=n; j++)
if(j!=i)
{
numerator *= x-arr_x[j];
denominator *= arr_x[i]-arr_x[j];
}
y+=(numerator/denominator)*arr_y[i];
}
printf("When x=%4.1f y=%7.1f\n",x,y);
getch();
}
OUTPUT

Lagrange Interpolation

INPUT :

Enter the value of n: 5


Enter the values of x and y:
arr_x[0]=5
arr_y[0]=7
arr_x[1]=9
arr_y[1]=8
arr_x[2]=2
arr_y[2]=3
arr_x[3]=4
arr_y[3]=6
arr_x[4]=1
arr_y[4]=9
Enter the value of x at which value of y is to be calculated: 4

RESULT :

Interpolated function value


When x= 4.0 y= 8.7
Newton-Gregory forward interpolation

Program to implement the Newton-Gregory forward interpolation

#include<stdio.h>
#include<conio.h>
#define MaxN 100
#define Order_of_diff 4

void main ()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y, p, h,
diff_table[MaxN+1][Order_of_diff+1];
int i,j,n,k;
clrscr();

printf("Enter the value of n \n");


scanf("%d",&n);
printf("Enter the values of x and y");

for(i=0; i<=n; i++)


scanf("%f%f", &arr_x[i], &arr_y[i]);
printf("Enter the value of x at which value of y is to be calculated");
scanf("%f", &x);
h=arr_x[1]-arr_x[0];

for(i=0; i<=n-1; i++)


diff_table[i][1]=arr_y[i+1]-arr_y[i];/*Creating the difference table and calculating first order
differences*/
for(j=2; j<=Order_of_diff; j++)/*Calculating higher order differences*/
for(i=0; i<=n-j; i++)
diff_table[i][j]=diff_table[i+1][j-1] - diff_table[i][j-1];
i=0;
while(!(arr_x[i]>x)) /* Finding x0 */
i++;
i--;
p=(x-arr_x[i])/h;
y=arr_y[i];

for (k=1; k<=Order_of_diff; k++)


{
numerator *=p-k+1;
denominator *=k;
y +=(numerator/denominator)*diff_table[i][k];
}
printf("When x=%6.1f, y=%6.2f\n",x, y);
getch();
}

OUTPUT

Newton-Gregory forward interpolation

INPUT :

Enter the value of n : 5


Enter the values of x and y
10 2.2
15 2.6
20 3.0
25 3.3
30 3.6
Enter the value of x at which value of y is to be calculated23

RESULT :

When x= 23.0, y= 3.17


Linear Regression

Linear Regression

To illustrate, if z = A0 + A1*x + A2*y is to be fitted to N data points, the normal equations are

A0*N + A1*åx + A2*åy = åz


A0*åx + A1*åx*x + A2*åx*y = åx*z
A0*åy + A1*åy*x + A2*åy*y = åy*z

where the å’s are over all N data sets.

Solving the above system we get the values of the coefficients A0, A1 and A2. Obviously, it may be
generalized to any number of variables or parameters.

The correlation coefficient is computed with

å [festimated - fmean]2
SQR ( —————————————————————— )
å [f-fmean]2

The standard error of estimate is calculated using


å [f – festimated ]2
SQR ( ————————————————————— )
N-2

Summations are over all N data points, f is the dependent variable, and the festimated is found using
the regression results.
ALGORITHM :

Step 1: Start
Step 2: read n
Step 3: sum ? 0
Step 4: sum xsq ? 0
Step 5: sum y ? 0
Step 6: sum xy ? 0
Step 7: i?1
Step 8: read x,y
Step 9: sum x ? sum x + x
Step 10: sum xsq ? sum xsq + x2
Step 11: sum y ? sum y + y
Step 12: sum xy ? sum xy + x * Y
Step 13: i ? i + 1
Step 14: repeat steps 8,9,10,11 and 12 until i=n
Step 15: den ? n * sum xsq – sum x * sum x
Step 16: ao ? (sum y * sum xsq – sum x * sum xy)/den
Step 17: a1 ? (n * sum xy - sum x * sum y)/den
Step 18: write ao, a1
Step 19: stop
Program to implement the linear regression algorithm.

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>

float mean(float *a, int n);


void deviation(float *a, float mean, int n, float *d, float *S);

void main()
{
float a[20],b[20],dx[20],dy[20];
float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0;
float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0;
char type_coff[7];
int n=0,i=0;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter the values of x and y:\n");
for(i=0;i<n;i++)
scanf("%f%f",&a[i],&b[i]);
mean_x=mean(a,n);
mean_y=mean(b,n);
deviation(a,mean_x,n,dx,&sx);
deviation(b,mean_y,n,dy,&sy);
for(i=0;i<n;i++)
sum_xy=sum_xy+dx[i]*dy[i];
corr_coff=sum_xy/(n*sx*sy);
printf("Enter the type of regression coefficient as 'x on y' or 'y on x': ");
fflush(stdin);
gets(type_coff);
if(strcmp(type_coff,"x on y")==1)
{
reg_coff_xy=corr_coff*(sx/sy);
printf("\nThe value of linear regression coefficient is %f",reg_coff_xy);
}
else if(strcmp(type_coff,"y on x")==1)
{
reg_coff_yx=corr_coff*(sy/sx);
printf("\nThe value of linear regression coefficient is %f",reg_coff_yx);
}
else
printf("\nEnter the correct type of regression coefficient.");
getch();
}

float mean(float *a, int n)


{
float sum=0, i=0;
for(i=0;i<n;i++)
sum=sum+a[i];
sum=sum/n;
return (sum);
}

void deviation(float *a, float mean, int n, float *d, float *s)
{
float sum=0,t=0;
int i=0;
for(i=0;i<n;i++)
{
d[i]=a[i]-mean;
t=d[i]*d[i];
sum=sum+t;
}
sum=sum/n;
*s=sqrt(sum);
}
OUTPUT

INPUT :
Enter the value of n : 5
Enter the values of x and y3 5
26
78
37
69

57
Enter the value of x at which value of y is to be calculated5

RESULT :

When x= 5.0, y=-6573.00


Trapezoidal Rule

Aim: To find the approximate Area under the given curve


By Trapezoidal Rule.

Theory:

According to Newton – Cotes Quadrature Formula

Putting n=1 in above & taking the curve through (x0,y0) & (x1,y1)as a straight line i.e. a polynomial
of first order so that differences of order higher than first become zero, we get

This is known as Trapezoidal Rule.


Program To find the Area under the curve by TRAPEZOIDAL RULE

# include <stdio.h>
# include<conio.h>

float function(float x)
{
return(1/(1+x*x));
}
void main()
{
int i;
float a,b,n,h,y;
printf("\nThis Program Will Find the Root Of The Equation f(x) = 1/(1+x^2)\n");
printf("\n\t************ By Trapezoidal Rule ************\n");
printf("\nEnter the Limits of Integration & no. of SubIntervals\n");
printf("\nEnter the lower limit of Integration - ");
//lower limit = 0
scanf("%f",&a);
fflush(stdin);
printf("\nEnter the upper limit of Integration - ");
//upper limit = 6
scanf("%f",&b);
fflush(stdin);
printf("\nEnter the number of SubIntervals - ");
//Subintervals = 6
scanf("%f",&n);
fflush(stdin);
h=(b-a)/n;
y=function(a)+function(b);
for(i=1;i<n;i++)
{
y = y + (2*function(a+i*h));
}
printf("\nThe value of Integral of the given function is - %f",(h/2)*y);
}
OUTPUT

This Program Will Find the Root Of The Equation f(x) = 1/(1+x^2)

************ By Trapezoidal Rule ************

INPUT :

Enter the Limits of Integration & no. of SubIntervals

Enter the lower limit of Integration - 0

Enter the upper limit of Integration - 6

Enter the number of SubIntervals - 6

RESULT :

The value of Integral of the given function is - 1.410799


Simpson Rule
Aim: To find the approximate Area under the given curve
By Simpson’s Rule.

Theory:

According to Newton – Cotes Quadrature Formula

Putting n=2 in above & taking the curve through (x0,y0), (x1,y1) & (x2,y2) as a parabola i.e. a
polynomial of second order so that differences of order higher than second vanish, we get

This is known as the Simpson’s one – third Rule or simply Simpson’s Rule & is most commonly
used
Program to find the Area under the curve by SIMPSON’S RULE

# include <stdio.h>

float function(float x)
{
return(1/(1+x*x));
}
void main()
{
int i;
float a,b,n,h,y;
printf("\nThis Program Will Find the Root Of
The Equation f(x) = 1/(1+x^2)\n");
printf("\n\t************ By Simpson's Rule ************\n");
printf("\nEnter the Limits of Integration
& no. of SubIntervals(must be a EVEN Number)\n");
printf("\nEnter the lower limit of Integration - ");
//lower limit = 0
scanf("%f",&a);
fflush(stdin);
printf("\nEnter the upper limit of Integration - ");
//upper limit = 6
scanf("%f",&b);
fflush(stdin);
printf("\nEnter the number of SubIntervals - ");
//Subintervals = 6
scanf("%f",&n);

h=(b-a)/n;
y=function(a)+function(b);

for(i=1;i<n;i+=2)
{
y = y + (4*function(a+i*h)) + (2*function(a+(i+1)*h));
}
printf("\nThe value of Integral of the given function is - %f",(h/3)*y);
}
OUTPUT

INPUT :

This Program Will Find the Root Of The Equation f(x) = 1/(1+x^2)

************ By Simpson's Rule ************

Enter the Limits of Integration & no. of SubIntervals


(must be a EVEN Number)

Enter the lower limit of Integration - 0

Enter the upper limit of Integration - 6

Enter the number of SubIntervals - 6

RESULT :

The value of Integral of the given function is - 1.384192

Vous aimerez peut-être aussi