Académique Documents
Professionnel Documents
Culture Documents
LAB MANUAL
J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY
YENKAPALLY(V), MOINABAD(M), HYDERABAD-500075
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.
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)
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.
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
21
A C program that implements the following sorting methods to sort a given
list of integers in ascending order
i) insertion Sort
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
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:
RESULT:
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
write a,b
c=a+b
write c
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 :
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 :
RESULT:
Roots are real and equal
-1.000000 -1.000000
INPUT :
RESULT:
INPUT :
RESULT:
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>
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:
OUTPUT :
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
/* 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 :
RESULT:
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;
}
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
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 :
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
Yes
Op =oop
‘+’ res=op1 + op2
No
Yes
Op = ‘-’ res=op1 - op2
No
Yes
Op = ‘*’ res=op1 * op2
No
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
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 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
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:
RESULT:
MATRIX A
123
456
789
MATRIX B
987
654
321
MATRIX C
10 10 10
10 10 10
10 10 10
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
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:
RESULT:
MATRIX A
1 2 3
4 5 6
MATRIX B
2 1
2 1
2 1
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:
RESULT:
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:
RESULT:
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();
OUTPUT
INPUT:
RESULT:
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 :
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;
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
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);
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 :
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>
{
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:
RESULT:
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:
RESULT:
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:
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
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>
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
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
#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;
}
if(list->next->next == NULL)
printf("%d", list->next->number);
print(list->next); /* move to next item */
}
return;
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
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
#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);
while(n != -999)
{
if(head == NULL) /* create 'base' node */
{
head = (node *)malloc(sizeof(node));
head ->number = n;
head->next = NULL;
print("\n");
}
node *insert_sort(node *list, int x)
{
node *p1, *p2, *p;
p1 = NULL;
p2 = list; /* p2 points to first node */
if(p2->next == NULL)
{
p2 = p2->next; /* p2 set to NULL */
break; /* insert new node at end */
}
}
OUTPUT
INPUT :
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);}
}
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");
{
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;
OUTPUT:
***** M A I N M E N U *****
***** M A I N M E N U *****
***** M A I N M E N U *****
***** M A I N M E N U *****
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;
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);
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");
}
}
}
return 0;
}
OUTPUT:
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
Element to be pushed: 10
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
Element to be pushed: 30
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
Element to be pushed: 35
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
Element to be pushed: 40
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
Element to be popped: 40
MENU
[1] Using Push Function
[2] Using Pop Function
[3] Elements present in Stack
[4] Exit
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.
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
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.
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.
#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];
};
/*main function*/
void main()
{
int ele,k;
int ch;
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*/
if(queue->r == size - 1)
queue->r = -1;
queue->a[++queue->r] = j;
queue->num++;
return true;
}
int j;
if(e_que(queue))
return -9999;
j = queue->a[queue->f++];
if(queue->f == size)
queue->f = 0;
queue->num--;
return j;
}
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;
};
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;
}
}
}
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
z:
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
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
#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
INPUT:
RESULT :
Infix String : A + B * C – D
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
INPUT :
Enter value of A :2
Enter value of B :3
Enter value of C :4
Enter value of D :5
RESULT :
ALGORITHM :
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);
}
INPUT :
BINARY TREE
1. Create
2. Preorder
3. Inorder
4. Postorder
5. Exit
Enter your choice:1
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;
/* 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;
for(j=0;j<num;j++)
scanf("%d",&l[j]);
}
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:
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
RESULT:
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;
}
/*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);
OUTPUT
INPUT :
==================================
MENU
==================================
[1] Binary Search using Recursion method
[2] Binary Search using Non-Recursion method
Enter your Choice:1
RESULT :
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
RESULT :
Non-Recursive method:
The element 98 is present at position 3 in list
Bubble Sort
Definition :
ALGORITHM :
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:
INPUT :
RESULT :
Definition :
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.
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 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:
INPUT :
RESULT :
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 :
ASCENDING ORDER
#include<stdio.h>
#include<conio.h>
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);
*****INSERTION SORT********
INPUT :
RESULT :
Definition :
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_SORT (A)
#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**********
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 :
RESULT :
#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();
OUTPUT
INPUT :
RESULT :
Linear Regression
To illustrate, if z = A0 + A1*x + A2*y is to be fitted to N data points, the normal equations are
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.
å [festimated - fmean]2
SQR ( —————————————————————— )
å [f-fmean]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>
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();
}
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 :
Theory:
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
# 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)
INPUT :
RESULT :
Theory:
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)
RESULT :