Documente Academic
Documente Profesional
Documente Cultură
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
void main()
{
int l,b,h, vol;
printf(“enter values for length, breadth,height of cylinder”);
scanf(“%d %d %d”, &l,&b,&h);
vol=l*b*h;
printf(“\n volume of cylinder is %d”, vol);
}
1
PROBLEM 2: To find area of triangle : sqrt(s*(s-a)*(s-b)*(s-c))
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
float s, area;
printf(“enter values for three sides of triangle”);
scanf(“%d %d %d”, &a,&b,&c);
s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(“\n area of triangle with sides a=%d, b=%d, c=%d is %f”, a,b,c,area);
}
2
PROBLEM 3: Convert Celcious temperature to Farenheit.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
float c,f;
printf(“enter a value in celcious\n”);
scanf(“%f”,&c);
f=(9.0/5)*c+32;
printf(“temperature in farenheit is %f”,f);
}
3
PROBLEM 4: Calculate Simple Interest using (p*t*r)/100.
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
void main()
{
int p,t,r;
float si;
printf(“enter values p,t,r”);
scanf(“%d %d %d”, &p,&t,&r);
si=(p*t*r)/100.0;
printf(“\n Simple interest is = Rs .%f”, si);
}
4
PROBLEM 5:-Find Value of S=ut+1/2*a*t**2.
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
void main()
{
float u,t,a,S;
clrscr();
printf(“enter values u,t,a”);
scanf(“%f %f %f”, &u,&t,&a);
S=(u*t)+(0.5*a*t*t);
printf(“\n S = %f”, S);
}
Output:- S =79.200
5
PROBLEM 6:- Find Sum to first n numbers (using goto).
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n, i=1, sum=0;
printf(“enter value for n”);
scanf(“%d”,&n);
abc:
sum=sum+i;
i=i+1;
if (i<=n) goto abc;
printf(“sum upto %d numbers is %d”,n,sum);
}
6
PROBLEM 7:- Swap two numbers.( using temporary variable).
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a,b,t;
printf(“enter value for a,b”);
scanf(“%d %d”,&a,&b);
printf(“before swapping a=%d b=%d”,a,b);
t=a;
a=b;
b=t;
printf(“after swapping a=%d b=%d”,a,b);
}
7
PROBLEM 8:- Swap Two numbers (without using temporary variable)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a,b,t;
printf(“enter value for a,b”);
scanf(“%d %d”,&a,&b);
printf(“before swapping a=%d b=%d”,a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“after swapping a=%d b=%d”,a,b);
}
8
PROGRAMS USING STANDARD FUNCTIONS
PROBLEM 9:- To convert Upper case character to lower case and vice-versa.
PROCEDURE:-
1.input a character
2.if the given character is small case convert it to upper case
3.else if the given character is upper case convert it to lower case
4. after conversion print the character
CODE:-
#include<stdio.h>
#include<ctype.h>
void main()
{
char c;
printf(“enter a character”);
c=getchar();
if (islower(c))
putchar(toupper(c));
else
putchar(tolower(c));
}
Input:-enter a character
A
Output:-a
9
PROGRAMS USING IF,IF-ELSE,CASE.
PROBLEM 10:- Greatest of 3 numbers.( Nested IF-ELSE)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a,b,c;
printf (“enter values for a,b,c”);
scanf(“%d %d %d”,&a,&b.&c);
if(a>b)
{
if(a>c)
printf(“ %d is the greatest “,a);
else
printf(“%d is the greatest”,c);
}
else {
if(b>c)
printf(“%d is the greatest”,b);
else
printf(“%d is the greatest”,c);
}
}
Output:- 7 is geatest
10
PROBLEM 11:- Find greatest of 3 numbers.(Using conditional operator)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a,b,c,y;
printf(“enter values for a,b,c”);
scanf(“%d %d %d “,&a,&b,&c);
y=(a>b)?(((a>c)?a:c) : ((b>c)?b:c))
printf(“%d is the greatest “,y);
}
Output:- b =8 is geatest
11
PROBLEM 12:- Write a C program to read a number and to print the
number in words.(EX:=384=three eight four)in switch case.
PROCEDURE:-
1.input an integer
2.reverse the given integer
3. repeat steps 4 to 6 reversed integer is greater than 0
4. find modulo 10 value
5. print the result of step 4 in words
6. find new value of reversed number by dividing by 10.
CODE:-
#include<stdio.h>
void main()
{
int a,rev=0,n;
printf(“enter a number”);
scanf(“%d”,&a);
while(a>0)
{
n=a%10;
rev=rev*10+n;
a=a/10;
}
while(rev>0)
{
n=rev%10;
switch(n)
{
case 1: printf(“one”); break; case 2: printf(“two”); break;
case 3: printf(“three”); break; case 4: printf(“four”); break;
case 5: printf(“five”); break; case 6: printf(“six”); break;
case 7: printf(“seven”);break; case 8: printf(“eight”); break;
case 9: printf(“nine”); break; case 0: printf(“zero”); break;
}
rev=rev/10;
}
}
12
PROBLEM 13:-Generate the electricity bill based on the specifications:
Domestic >100 units Rs 1.50
101 – 300 units Rs 2.00
301 – 500 units Rs 2.50
L.T.Consumer 501 – 1000 units Rs 4.00
H.T.Consumer 1001- 2000 units Rs 5.00
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int units;
float price;
printf(“enter the number of units “);
scanf(“%d”,&units);
if(units<100)
price=units*1.50;
else if(units>100&&units<=300)
price=units*2.00;
else if(units>300&&units<=500)
price=units*2.50;
else if (units>500&&units<=1000)
price=units*4.00;
else if(units>1000&&units<=2000)
price=units*5.00;
printf(“the total bill is %f”,price);
}
13
PROBLEM 14:-(Switch Case) print result : grade on prercentage
Percentage > 75 Distinction.
60 - 74 First Class.
50 - 59 Second Class.
40 - 49 Third Class.
Percentage< 40 Fail.
PROCEDURE:-
1.input the total marks(for ten subjects)
2.find percentage(marks/10)
3. if above percentage is 10 or 9 or 8 or 7 grade is distinction
4.if percentage is 6 grade if first
5.if percentage is 5 grade is second
6.if percentage is 4 grade is third
7. if percentage is less than 4 grade is fail
CODE:-
#include<stdio.h>
void main()
{
int x,marks;
printf(“enter the marks of the students”);
scanf(“%d”,&marks);
x=marks/10;
switch(x)
{
case 10:
case 9:
case 8:
case 7: printf(“Distinction”);
break;
case 6: printf(“first class”);
break;
case 5: printf(“second class”);
break;
case 4: printf(“third class”);
break;
case 3: case 2: case 1: printf(“fail”); break;
default: printf(“enter correct marks”);
}
}
14
PROBLEM 15:- Generate the Net Salary with the given terms
SALARY < 22000 Nil
22001 - 30000 20 % of income >20000
30001 - 50000 1600 + 25 % of income >30000
50001 - 75000 6600 + 40 % of income >50000
> 75000 16600 + 50 % of income>75000
PROCEDURE:-
1. input salary of the employee
2. based on the above specifications calculate net salary
3. printf the net salary
CODE:-
#include<stdio.h>
void main()
{
long double sal, netsal;
printf(“enter the salary of the employee”);
scanf(“%Lf”,&sal);
if(sal<22000)
netsal=sal;
else if(sal>22000&&sal<=30000)
netsal=(sal-20000)*0.2;
else if(sal>30000&&sal<=50000)
netsal=1600+(sal-30000)*0.25;
else if(sal>50000&&sal<=75000)
netsal=6600+(sal-50000)*0.40;
else
netsal=16600+(sal-75000)*0.5;
printf(“the net salary of the employee is :%Lf”,netsal);
}
15
PROGRAMS USING LOOPS (WHILE ,DO_WHILE,FOR)
PROBLEM 16:- Sum and average of n different numbers.
PROCEDURE:-
1. input an integer value n and set sum to 0
2. repeat step 3 until all the n different values are read
3. read an integer add this to previous sum
4. print the sum
CODE:-
#include<stdio.h>
void main()
{
int n,x,i=1;sum=0;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter %d different values”,n);
while(i<=n)
{
scanf(“%d”,&x);
sum=sum+x;
i++;
}
printf(“sum of %d numbers is %d”, n, sum);
}
16
PROBLEM 17:- Find Sum of even and odd in a series of numbers.
PROCEDURE:-
1.enter an integer value n, set oddsum and evensum to 0
2. repeat step 3 and 4 until all the n different values are read
3.read an integer find modulo 2 of that if result is 0 add this to previous evensum
4.if result of modulo is 1 add the integer to previous oddsum
5.print the oddsum and evensum
CODE:-
#include<stdio.h>
void main()
{
int n,x,i=1;sume=0,sumo=0;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter %d different values”,n);
while(i<=n)
{
scanf(“%d”,&x);
if(x%2= =0)
sume=sume+x;
else
sumo=sumo+x;
i++
}
printf(“Even sum =%d \n Odd sum = %d”, sume,sumo);
}
17
PROBLEM 18:- Reversing a number.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n,r;
printf(“enter value for n”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
printf(“%d”,r);
n=n/10;
}
}
18
PROBLEM 19:- Sum of digits of a number down to a single digit.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n,m,sum,r;
printf(“enter value for n”);
scanf(“%d”,&n);
m=n;
while(n>9)
{
sum=0;
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
n=sum;
}
printf(“sum of %d down to single digit is %d”,m,sum);
}
19
PROBLEM 20. Number system conversion.(Decimal to Binary)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
long int n,m,s=0,r,f=1;
printf(“enter number in decimal system \n”);
scanf(“%ld”,&n);
m=n;
While (n>0)
{
r=n%2;
s=s+r*f;
f=f*10;
n=n/2;
}
printf(“the binary value for the decimal number %ld is %ld”,m,s);
}
20
PROBLEM 21:- Find factorial of a number.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
long int n, fact=1;
int i;
printf(“enter value for n”);
scanf(“%ld”,&n);
for(i=1;i<=n;i++)
fact=fact *i ;
printf(“ factorial for the number %ld is %ld”,n,fact);
}
21
PROBLEM 22:- Find G.C.D.(Greatest Common Divisor) of two numbers.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a,b,n;
printf(“enter two numbers for a,b to find GCD”);
scanf(“%d %d “,&a,&b);
if(a>b)
n=b;
else
n=a;
do
{
if(a%n = = 0 && b%n = = 0)
{
printf(“ GCD for %d and %d is %d”,a,b,n);
break;
}
else
n=n-1;
}while(n>0);
}
22
PROBLEM :-23 Checking whether a number is Prime.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n , i,flag =0;
printf(“enter a number “);
scanf(“%d”,&n);
for(i=2;i<n;i++)
{
if (n % i = = 0)
{
flag=1;
break;
}
}
if (flag = = 0)
printf(“the given number %d is prime number “,n);
else
printf(“the given number %d is not a prime number “,n);
}
23
PROBLEM 24:- Generate all primes below 100.
PROCEDURE:-
1.set n=1
2. repeat steps 3 to 6 until n reaches 100
3.start finding modulo value for n with i=2 to n-1 value incrementing i by 1 each time
4.if at any point remainder becomes 0
5.don’t print that n
5.else print n
6.increment n by 1
CODE:-
#include<stdio.h>
void main()
{
int i,flag,n ;
printf(“primes below 100 are\n”);
for(n=1;n<=100;n++)
{
flag=0;
for(i=2;i<n;i++)
{
if (n % i = = 0)
{
flag=1;
break;
}
}
if (flag = = 0)
printf(“%3d “,n);
}
}
Output:-1,2,3,5,7,11,13,17,19,23,………………97
24
PROBLEM 25:- Checking whether a number is perfect.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n ,i,s=0
printf(“enter a number “);
scanf(“%d”,&n);
for(i=1;i<n;i++)
{
if (n % i = = 0)
s=s+i;
}
if (n = = s)
printf(“the given number %d is perfect number “,n);
else
printf(“the given number %d is not a perfect number “,n);
}
25
PROBLEM 26:- Generate all perfect nos. below 100.
PROCEDURE:-
1.set n=1
2.repeat steps 3 to 6 until n reaches 100 incrementing n by 1 each time
3.set sum to 0
4.start finding modulo value for n with i=1 to n-1 value incrementing i by 1 each time
5.if at any point remainder is 0 add i to sum
6.if sum is same as n then print n
CODE:-
#include<stdio.h>
void main()
{
int n ,i,s;
printf(“the perfect numbers below 100 are \n”);
for(n=1;n<=100;n++)
{
s=0;
for(i=1;i<n;i++)
{
if (n % i = = 0)
s=s+i;
}
if (n = = s)
printf(“%3d “,n);
}
}
Output:-6,28
26
PROBLEM 27:- Checking whether a number is Fibonacci.
PROCEDURE:-
1.enter an integer value
2. set a=0,b=1,c=a+b,flag=0
3.repeat steps 4 ,5 until c is less than or equal to n
4.if n and c are same print that n is Fibonacci number
5.else set a=b,b=c, c=a+b
6 if n is not equal to c it is not Fibonacci number
CODE:-
#include<stdio.h>
void main()
{
int n, a=0,b=1 ,c,flag=0;
printf(“enter a number”);
scanf(“%d”,&n);
do
{
c=a+b;
if(n= = c)
{
flag=1;
break;
}
a=b;
b=c;
}while(c<=n);
if(flag = = 1)
printf(“%d is Fibonacci number”,n);
else
printf(“%d is not Fibonacci number”,n);
}
Input:-enter a number 8
Output:-8 is Fibonacci number
27
PROBLEM 28:- Generate Fibonacci series below 100( 0 ,1, 1, 2 ,3 ,5,8………..)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int i=3, a=0,b=1 ,c;
printf(“Fibonacci series below 100 are :\n”);
printf(“%3d %3d”,a,b);
while(i<=100)
{
c=a+b;
printf(“%3d”,c);
a=b;
b=c;
i++;
}
}
28
PROBLEM 29:- Check whether a given number is Fibonacci prime or not.
PROCEDURE:-
1.input an integer n
2. first check whether it is prime or not
3. if it prime check whether it is in the Fibonacci series
4.the above check can be made by generating series and comparing each number with n
5.if n is found in the series then n is Fibonacci prime
6.else it is not Fibonacci prime
CODE:-
#include<stdio.h>
void main(){
int n,i=2,k=0,a,b,i,m;
printf(“enter the number”);
scanf(“%d”,&n);
while(i<=n/2)
{
if(n%i = = 0)
{
k=1; break;
}
i++;
}
if(k!=1)
{
a=0; b=1; i=1; m=n;
while(i<=m)
{
c=a+b;
if(m= =c)
{
printf(“ %d is Fibonacci prime”,n); break;
}
a=b; b=c; i++;
}
if(m!=c)
printf(“%d Not Fibonacci prime”,n);
}
else
printf(“not prime “);
}
Input:-enter the number 13
Output:- 13 is Fibonacci prime
29
PROBLEM 30:- Generate twin primes below 100.( (3,5), (5,7), ……………).
PROCEDURE:-
1.set n to 2
2.check whether n is prime if so increment n by 2 and call it as m
3.check whether m is prime
4. if so print n and m (they are twin prime because the difference is 2)
5.set n value as m
6.repeat the process in steps 2 to 5 so as to generate all twin primes below 100
CODE:-
#include<stdio.h>
void main(){
int i,b=2,n=2, a=3,ctr;
while(n<100)
{
ctr=0; i=2;
while(i<n)
{
if(n%i = =0)
{
ctr=1; break;
}
}
if(ctr= =0)
{
a=n;
if((a-b)= = 2)
printf(“( %d , %d) \n”,b,a);
b=a;
}
n++;
}
}
30
PROBLEM 31. Sum of the series to 25 terms 1+1/4+1/9+.....
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int i;
float sum=0;
for(i=1;i<=25;i++)
sum=sum+(1.0/(i * i));
printf(“ sum of the series is = %f”,sum);
}|
31
PROBLEM 32:-. Evaluate the cos(x) series(x-x3/3!+x5/5!-……..)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int i=1,n;
float sum,t,x,y;
printf(“enter the number of terms and degrees”)
scanf(“%d %f”,&n,&y);
x=y*3.142/180;
sum=x;
t=x;
while(i<n)
{
t=((-t)*x*x)/((2*i)*(2*i+1));
sum=sum+t;
i++;
}
printf(“ cos(%f)=%f”,y,sum);
}
Output:-cos(60)=0.499999
32
PROBLEM 33:- Evaluate the sin(x) series(1-x2/2!+x4/4!-….)
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int i=1,n,y;
float sum,t,x;
printf(“enter the number of terms and degrees”)
scanf(“%d %d”,&n,&y);
x=y*3.142/180;
sum=1;
t=1;
while(i<n)
{
t=((-t)*x*x)/((2*i)*(2*i-1));
sum=sum+t;
i++;
}
printf(“ sin(%d)=%f”,y,sum);
}
Output:-sin(30)=0.49999
33
PROBLEM 34. Checking whether a number is Palindrome.
PROCEDURE:-
1.input an integer value n
2.set sum to 0
3.repeat steps 4 to 6 until n is greater than 0
4. find n modulo 10 and assign it to r
5.set sum=sum*10+r
6.new value of n is equal to n/10
7.if n and sum values are equal then print n is palindrome
8.else print n is not palindrome
CODE:-
#include<stdio.h>
void main()
{
int n,r,s=0,m;
printf(“enter value for n”);
scanf(“%d”,&n);
m=n;
while(n>0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
if(s= =m)
printf(“ %d is a palindrome”,m);
else
printf(“%d is not a palindrome”,m);
}
Input:- enter value for n 121
34
Generate the following Pyramids .
35) 1
2 2
3 3 3
4 4 4 4
………….
PROCEDURE:-
1.enter the number of rows n
2.set i to 1
3.repeat steps 4 to 8 until i<=n
4.set j to 1
5.repeat steps 6 and 7 until j<=i
6.print the value of j
7.increment j by 1
8. go to new line ,increment i by 1
CODE:-
# include<stdio.h>
void main()
{
int i,j,n;
printf(“enter value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i; j++)
{
printf(“ %3d”,j);
}
printf(“\n”);
}
}
35
36) 1
2 2
3 3 3
4 4 4 4
…………………….
PROCEDURE:-
1.enter the number of rows n
2.set i to 1
3.repeat steps 4 to 8 until i<=n
4.set j to 1, print (n-i) spaces
5.repeat steps 6 and 7 until j<=i
6.print the value of j
7.increment j by 1
8. go to new line, increment i by 1
CODE:-
# include<stdio.h>
void main()
{
int i,j,n,k;
printf(“enter value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(k=1;k<=30-i; k++)
printf(“ “);
for(j=1;j<=i; j++)
{
printf(“ %3d”,j);
}
printf(“\n”);
}
}
36
37) 1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
PROCEDURE:-
1.enter the number of rows n
2.print required spaces so as to get output in pyramid form
3.set i to 1
4.repeat steps 5 to 11 until i is less than or equal to n
5.set j to i
6.repeat step 7 until j is less than or equal to 2*i-1
7.print value of j, increment j by 1
8. set l to 2*i-2
9.repeat step 10 until l is greater than or equal to i
10. print value of l, decrement l by 1
11. goto new line , increment i by 1
CODE:-
#include<stdio.h>
void main()
{
int i,j,n=4,k;
for(i=1;i<=n;i++)
{
for(k=1;k<=30-i; k++)
printf(“ “);
for(j=i;j<=2*i-1; j++)
printf(“ %3d”,j);
for(l=2*i-2; l>=i; l--)
printf(“%3d”,l);
printf(“\n”);
}
}
Output:- 1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
37
PROBLEM 38:- 1
2 3
4 5 6
7 8 9 10
……………..
PROCEDURE:-
1.enter the number of rows r
2.find the last no. to printed n=2+(r-1)
3.set i to 1,j=1,c=0
4.repeat steps 5 to 10 until j is less than or equal to n
5.set c to c+i
6.repeat step 7 to 8 until j is less than or equal to c and j less than or equal n
7.if i is less than or equal to n, then print value of j
8. increment j by 1
9.go to new line , set j to c+i
10 .increment i by 1
CODE:-
#include<stdio.h>
void main()
{
int r,c,j,n,i;
printf(“enter the no. of rows”);
scanf(“%d”,&r);
printf(“the required output is :\n”);
n=((2+(r-1));c=0;i=1;j=1;
while(j<=n)
{ c=c+i;
while(j<=c && j<=n)
{ if(i<=n)
{ printf(“%4d”,j);
}
j++;
}
printf(“\n”); j=c+i; i++;
}}
Input:- enter the no. of rows 4
Output:- 1
2 3
4 5 6
7 8 9 10
38
……………..
PROBLEM 39:- 1
0 1
1 0 1
0 1 0 1
PROCEDURE:-
1.enter no. of rows n, set k to 0 and l to 1
2. repeat steps 3 to 9 until i is less than or equal to n incrementing i by 1 each time
3. if modulo 2 of i is 0 then do step 4 and 5
4. set j to 1 and repeat step 5 until j is less than or equal to i/2 incrementing j by 1 each
time
5.print k and l
6.else set m to 1 repeat step 7 ,8 until m is less than or equal i incrementing m by 1
7. if m modulo 2 is not equal to 0 print value of l
8. else print value of k
9.go to new line
CODE:-
#include<stdio.h>
void main()
{
int i,j,k=0,l=1,n,m;
printf(“enter n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if(i%2 = =0)
{
for(j=1;j<=i/2;j++)
printf(“%d %d”,k,l);
}
else
{
for(m=1;m<=i;m++)
{
if(m%2!=0)
printf(“%d”,l);
else
printf(“%d”,k);
}
} printf(“\n”)
}}
Input:-enter n 4
Output:- 1
0 1
1 0 1
39
0 1 0 1
PROBLEM 40:- *
* *
* * *
* * * *
PROCEDURE:-
1.enter the number of rows n
2.set i to 1
3.repeat steps 4 to 8 until i<=n
4.set j to 1, print (n-i) spaces
5.repeat steps 6 and 7 until j<=i
6.print the value of ‘*’
7.increment j by 1
8. go to new line, increment i by 1
CODE:-
# include<stdio.h>
void main()
{
int i,j,k;
for(i=1;i<=4;i++)
{
for(k=1;k<=30-i; k++)
printf(“ “);
for(j=1;j<=i; j++)
printf(“*”);
printf(“\n”);
}
}
Output:- *
* *
* * *
* * * *
40
PROGRAMS USING ARRAYS.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int a[20],i,n,sum=0;
float avg;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter the %d element”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
sum=sum+a[i];
}
avg=sum/(float)n;
printf(“ Sum = %d \n average= %f”,sum, avg);
}
41
PROBLEM 42: Sort array of n numbers in ascending & descending order.
PROCEDURE:-
1.read the no. of values to be entered n
2.read the n different elements
3.repeat steps 4 to 5 for i=1 ,2,….,n-1
4.repeat step 5 for j=1,2,….,n-i
5.if A[j]>A[j+1] swap both the elements
6.print the n elements
CODE:-
#include<stdio.h>
void main()
{
int a[20],i,n,j,t;
float avg;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter the %d element”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=1;i<n;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
print(“the ascending order is :\n”);
for(i=1;i<=n;i++)
printf(“%3d”,a[i]);
print(“the descending order is :\n”);
for(i=n;i>=1;i--)
printf(“%3d”,a[i]);
}
Input:-enter the no. of elements:4
Enter the 4 different numbers
2841
Output:-the ascending order is :- 1 2 4 8
The descending order is : 8 4 2 1
42
PROBLEM 43:- Find the Maximum and Minimum in an array of n numbers.
PROCEDURE:-
1.read the no. of values to be entered n
2.read the n different elements
3.set max =a[1]
4.repeat step 5 for i=2 ,3,…..n
5.if a[i]>max, then set max=a[i]
6.print max
7.set min =a[1]
8.repeat step 9 for i=2 ,3,…..n
5.if a[i]<min, then set min=a[i]
6.print min
CODE:-
#include<stdio.h>
void main()
{
int a[20],i,n,max,min;
float avg;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter the %d element”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
}
max=a[1];
for(i=2;i<=n;i++)
if(a[i]>max)
max=a[i];
min=a[1];
for(i=2;i<=n;i++)
if(a[i]<min)
min=a[i];
printf(“ Maximum = %d \n Minimum=%d”,max,min);
}
Input:-enter value for n 4
Enter 4 different values
2548
Output:-maximum=8
Minimum=2
43
PROBLEM 44:- Sum of digits in even and odd places.
PROCEDURE:-
1.enter a number n, se=0,so=0,k=0
2.repeat steps 3 to 6 until n>0
3.increment k by 1, find n modulo 10 and assign to j
4.if k modulo 2 is 0 se=se+j
5.else so=so+j
6.new n is n/10
7.print even digit sum and odd digit sum
CODE:-
#include<stdio.h>
void main()
{
int n, se=0,so=0,k=0,j;
printf(“enter a number”);
scanf(“%d”,&n);
while(n>0)
{
k++;
j=n%10;
if(k%2= =0)
se=se+j;
else
so=so+j;
n=n/10;
}
printf(“sum of digits in even places=%d”,se);
printf(“sum of digits in odd places=%d”,so);
}
44
PROBLEM 45: Sum of two matrices
PROCEDURE:-
1.enter value for m n
2.enter values for matrix A of m by n order
3.enter value for m n
4.enter values for matrix B of m by n order
5.add A and B matrix and store in C matrix
6.print C matrix
CODE:-
#include<stdio.h>
void main()
{
int i,j, a[10][10],b[10][10],c[10][10],m.n;
printf(“enter value for m,n”);
scanf(“%d %d”,&m,&n);
printf(“enter the first matrix\n”);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the second matrix\n”);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&b[i][j]);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
c[i][j]=a[i][j]+b[i][j];
printf(“the resultant sum of two matrices is :\n”);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
printf(“%3d”,c[i][j]);
printf(“\n”);
}
}
Input:-enter value for m n 2 2
Enter the first matrix : 1 1
2 2
enter value for m n 2 2
enter the second matrix: 2 2
3 3
Output:-the resultant sum of two matrices: 3 3
5 5
45
PROBLEM 46:- Difference of two Matrices.
PROCEDURE:-
1.enter value for m n
2.enter values for matrix A of m by n order
3.enter value for m n
4.enter values for matrix B of m by n order
5.Subtract A and B matrix and store in C matrix
6.print C matrix
CODE:-
#include<stdio.h>
void main()
{
int i,j, a[10][10],b[10][10],c[10][10],m.n;
printf(“enter value for m,n”);
scanf(“%d %d”,&m,&n);
printf(“enter the first matrix\n”);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the second matrix\n”);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&b[i][j]);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
c[i][j]=a[i][j]-b[i][j];
printf(“the resultant difference of two matrices is :\n”);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
printf(“%3d”,c[i][j]);
printf(“\n”);
}
}
Input:-enter value for m n 2 2
Enter the first matrix : 3 3
3 3
enter value for m n 2 2
enter the second matrix: 2 2
2 2
Output:-the resultant difference of two matrices: 1 1
1 1
46
PROBLEM 47:-Multiplication of two Matrices.
PROCEDURE:-
1.enter value for m n
2.enter values for matrix A of m by n order
3.enter value for p q
4.enter values for matrix B of m by n order
5.if n is equal to p then
5.find product A and B matrix and store in C matrix
6.print C matrix
7.if n is not equal to p matrix multiplication not possible
CODE:-
#include<stdio.h>
void main()
{
int i,j, a[10][10],b[10][10],c[10][10],m.n,p,q,k;
printf(“enter value for m,n”); scanf(“%d %d”,&m,&n,&p,&q);
printf(“enter the first matrixof order % by %d\n”,m,n);
for(i=1;i<=m;i++) for(j=1;j<=n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the second matrix of order %d by %d\n”,p,q);
for(i=1;i<=p;i++) for(j=1;j<=q;j++)
scanf(“%d”,&b[i][j]);
if(n= =p)
{
for(i=1;i<=m;i++) for(j=1;j<=q;j++)
{
c[i][j]=0;
for(k=1;k<=p;k++)
c[i][j]=c[i][j] +a[i][k]*b[k][j];
}
printf(“the resultant product of two matrices is :\n”);
for(i=1;i<=m;i++)
{ for(j=1;j<=q;j++) printf(“%3d”,c[i][j]); printf(“\n”);
}
}
else
printf(“matrix multiplication not possible”);
}
Input:- enter value for m n 2 2 Enter the first matrix : 3 3
3 3
enter value for m n 2 2 enter the second matrix: 2 2
2 2
Output:- the resultant difference of two matrices: 12 12
12 12
47
PROBLEM 48:- Write a program to test whether a given Matrix is an upper
triangular Matrix or not. An upper triangular Matrix is one in all which all
these elements below its principal diagonal are 0.
PROCEDURE:-
1.enter value for m n
2.enter values for matrix A of m by n order
3.if all the elements below the principal diagonal are 0’s then
4 print “Upper triangular matrix”.
5.else print “not an upper triangular matrix”.
CODE:-
#include<stdio.h>
void main()
{
int a[10][10],m,n,i,j,t;
printf(“Enter the no.of rows & columns of the matrix:”);
scanf(“%d %d”, &m,&n);
if(m!=n)
printf(“Upper triangular rows must be equal to columns”);
else
{
printf(“Enter values\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(i>j) {
if(a[i][j]!=0)
t=1;
}
else if(a[i][j]==0)
t=1;
if(t==1)
printf(“Not upper Triangular Matrix”);
else
printf(“Upper Triangular”);
}
Input:- enter value for m n 2 2 Enter the first matrix : 3 3
0 3
Output:-upper triangular
48
PROBLEM 49:- Write a program to test whether a given Matrix is an unit
Matrix or not.
PROCEDURE:-
1.enter value for m n
2.enter values for matrix A of m by n order
3.if all the elements below the principal diagonal are 1’s and the remaining all elements
must be 0’s then
4 print “unit matrix”.
5.else print “not a unit matrix”.
CODE:-
#include<stdio.h>
void main()
{
int a[10][10],m,n,i,j,t=0;
printf(“Enter the no.of rows & columns of the matrix:”);
scanf(“%d %d”, &m,&n);
if(m!=n)
printf(“m, n must be equal”);
else
{
printf(“Enter values\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
if(i==j) {
if(a[i][j]!=1)
t=1;
}
if(t==1)
printf(“Not unit Matrix);
else
printf(“Unit Matrix”);
}
Input:- enter value for m n 2 2 Enter the first matrix : 1 0
0 1
Output:-unit matrix
49
PROBLEM 50:- Write a c function to test whether a given matrix is
symmetric or not.
PROCEDURE:-
1.enter value for m m
2.enter values for matrix A of m by m order
3.Find the transpose of matrix A and store it in B
4.if all the elements of A and B are same then
5. print “symmetic matrix”.
6.else print “not a symmetric matrix”.
CODE:-
#include<stdio.h>
void main()
{
int a[10][10],m,n,i,j,t=0;
printf(“Enter the no.of rows & columns of the matrix:”);
scanf(“%d %d”, &m,&n);
if(m!=n)
printf(“m,n must be equal );
else
{
printf(“Enter values\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]!=a[j][i])
t=1;
if(t==1)
printf(“Not Symmetric Matrix”);
else
printf(“ Symmetric Matrix”);
}
Input:- enter value for m m 2 2 Enter the first matrix : 1 0
0 1
Output:-symmetric matrix
50
PROGRAMS USING STRINGS
PROCEDURE:-
1.read a string
2.start extracting each character from the string
3.if character is a space
4.then increase space count by 1
5.else increase character count by 1
6.print space count and character count
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
char str[100];
int i=0,word=0,chr=0;
clrscr();
printf(“Enter any String : “);
gets(str);
while(str[i]!=’\0’)
{
if(str[i]= =” “)
word++;
else
chr++;
i++;
}
printf(“The Total No.of Words : %d \nThe Total No.of Characters %d”,word+1,chr);
}
51
PROBLEM 52:- Compare two strings.
PROCEDURE:-
1.read two string
2.find the lengths of each string if they are equal then only proceed for comparision
3.start extracting character by character from the both the strings till the end of strings
4.compare the characters extracted
5.if at any point they are not equal stop further comparision and print that strings unequal
6.else print that strings are equal
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
char str[100],str1[100];
int k,n,m;
printf(“Enter First String : “); gets(str);
printf(“Enter Second String : “); gets(str1);
n=strlen(str); m=strlen(str1);
if(n= =m)
{
k=0; i=0;
while(str[i]!=’\0’)
{
if(str[i]!=str1[i])
{
k=1; break;
}
i++;
}
if(k= =0)
printf(“The strings are Equal”);
else
printf(“The strings are not Equal”);
}
else
printf(“strings are uncomparable”);
}
52
PROBLEM 53:- Copy a String into another.
PROCEDURE:-
1.read a string
2.start extracting character by character till the end of string
3.store each character into second string
4.terminate the second string with null character
5.print the second string
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
char str[100],str1[100];
clrscr();
printf(“Enter First String : “);
gets(str);
i=0;
while(str[i]!=’\0’)
{
str1[i]=str[i];
i++;
}
str1[i]=’\0’;
printf(“The Original string : %s”,str);
printf(“The Copied string : %s”,str1);
}
53
PROBLEM 54:- Concatenate Two Strings.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
char str[100],str1[25];
int i,j,k;
clrscr();
printf(“Enter First String : “);
gets(str);
printf(“Enter Second String : “);
gets(str1);
for(j=0;str[j]!=’\0’;j++);
for(i=0;str1[i]!=’\0’;i++)
str[i+j+1]=str1[i];
str[i+j+1]=’\0’
printf(“After ConcatenatingTwo strings :”);
puts(str);
}
54
PROBLEM 55. Insert a substring into a String from a particular position.
PROCEDURE:-
1.read a string
2.traverse till the position for inserting the substring
3.move the remaining characters of the original string ahead by the no. of characters in
substring
4.insert the substring
5.print the original string
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
char s[100],s1[50];
int i,j,k,pos,m;
printf("enter Two Strings : ");
gets(s); gets(s1);
k=strlen(s); j=strlen(s1);
printf("enter Position to Insert string : ");
scanf("%d",&pos);
m=j; i=k+j; s[i+1]='\0';
while(m>=0)
{
s[i]=s[k-1];
i--; k--; m--;
}
i=0;
while(s1[i]!='\0')
{
s[pos]=s1[i];
pos++; i++;
}
printf("The result string is : %s",s);
}
55
PROBLEM 56:- Delete n characters in the string from a particular position.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
char str[20];
int i,j,m,n;
printf(“enter the string”);
gets(str);
printf(“enter the position and the number of characters to be deleted”);
scanf(“%d %d”, &n,&m);
j=n+m;
i=n;
while(str[j]!=’\0’)
{
str[i]=str[j];
i++;
j++;
}
str[i]=’\0’;
printf(“the new string is “);
puts(str);
}
56
PROBLEM 57:- Reverse a given String.
PROCEDURE:-
1.read a string S
2. move till the end of string
3.start printing character by character from end till the beginning
CODE:-
#include<stdio.h>
main()
{
int i,j;
char s[100];
printf(“Enter the string”);
scanf(“%s”,s);
for(i=0;s[i]!=’\0’;i++);
printf(“The reversed string is:”);
for(j=i-1;j>=0;j--)
putchar(s[j]);
}
57
PROBLEM 58:- Check whether a given string is palindrome or not.
PROCEDURE:-
1.read a string S
2.move till the end of S
3.start copying from the last character till the first character into another string S1
4.if S and S1 are the same then print “palindrome” else print “not palindrome”
CODE:-
#include<stdio.h>
main()
{
int i,j,k;
char s[100],s1[100];
printf(“Enter the string”);
gets(s);
for(i=0;s[i]!=’\0’;i++);
printf(“The reversed string is:”);
k=0;
for(j=i-1;j>=0;j--)
{
s1[k]=s[j];
k++;
}
s1[k]=’\0’;
if(strcmp(s,s1)= =0)
printf(“the string is palindrome”);
else
printf(“string is not palindrome);
}
58
PROBLEM 59:- Write a program to compare two given strings .the function
should return 1 if the strings are equal and 0 otherwise.
PROCEDURE:-
1. read two strings S1,S2
2. find the lengths of both the strings
3. if they are equal the proceed with comparision else print “uncomparable”
4. start comparing from first characters of either of the string till the end of string
5. if at any position a mismatch occurs print”unequal “ return
6. else print “equal”
CODE:-
#include<stdio.h>
void main()
{
char str[20],str1[20];
int flag=0,i=0;
int strcp(char [ ], char [ ]), x;
printf(“enter the first string”);
gets(str);
printf(“enter the second string”);
gets(str1);
n=strlen(str); m=strlen(str1);
if(m= =n)
{x=strcp(str,str1);
if(x= =0)
printf(“strings are equal”);
else
printf(“strings are unequal”);
}
else printf(“uncomparable”);
}
int strcp(char *s1, char *s2)
{ int i=0,flag=0;
while(*s1!=’\0’)
{
if(*s1!=*s2)
{
flag=1; break;
}
s1++; s2++;
}
if(flag= =0) return(0);else return(1);
}
Input:- enter first string: HELLO
enter second string:HELLO
Output:-strings are equal
59
PROBLEM 60:- Program to find the number of occurences of each alphabet
in a given string .Assume that the string contain only alphabets.
PROCEDURE:-
1.read a string S
2.repeat steps 3 to 7till the end of the string S, set i to 0 and character count by 0
3. strart scanning the the character i th character
4.repeat step 5 till the end of the string S
5. if the i th character matches with any other characters scanned increase character count
by 1
6. print the character count
7.increase i by 1
CODE:-
#include<stdio.h>
void main()
{
char str[20];
printf(“enter the string”);
gets(str);
i=0;
while(str[i]!=’\0’)
{
c=0;
ch=str[i];
j=i;
while(str[j]!=’\0’)
{
if(ch= =str[j])
c++;
j++;
}
printf(“%c ‘s no. of occurrences is %d”,ch,c);
i++;
}
}
Input:-enter the string: I am fine
Output:- i ‘s no. of occurrences is 2
a’s no. of occurrences is 1
m’ss no. of occurrences is 1
f’s no. of occurrences is 1
n’s no. of occurrences is 1
e’s no. of occurrences is 1
60
PROBLEM 61:- Maximum of the given numbers in an array.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
void maxi(int [],int);
int a[20],i,n,max;
float avg;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter the %d element”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
}
maxi(a,n);
}
void maxi(int a[],int n)
{
int i,max;
max=a[1];
for(i=2;i<=n;i++)
if(a[i]>max)
max=a[i];
printf(“maximum value is %d”,max);
}
Input:- enter value for n 4
Enter 4 elements 10 80 9 4
Outout:-maximum value is 80
61
PROBLEM 62:- Factorial of given number.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
long int fact(long int);
long int n,f;
printf(“enter value for n”);
scanf(“%ld”,&n);
f=fact(n);
printf(“factorial of %ld is %ld”,n,f);
}
long int fact(long int n)
{
long int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return(f);
}
62
PROBLEM 63:- Reverse a string.
PROCEDURE:-
1.read a string S
2. move till the end of string
3.start printing character by character from end till the beginning
CODE:-
#include<stdio.h>
void main()
{
char str[20];
void rev(char [ ]);
printf(“enter the string”);
gets(str);
rev(str);
}
63
PROBLEM 64:- Swap two numbers (Call by value).
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
void swap(int,int);
int a,b;
printf(“enter values for a,b”);
scanf(“%d %d”,&a,&b);
printf(“before swapping a=%d b=%d”,a,b);
swap(a,b);
printf(“after swapping a=%d b=%d”,a,b);
}
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf(“in function after swapping a=%d b=%d”,a,b);
}
64
PROBLEM 65:- Swap two numbers (Call by reference).
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
void swap(int *, int *);
int a,b;
printf(“enter values for a,b”);
scanf(“%d %d”,&a,&b);
printf(“before swapping a=%d b=%d”,a,b);
swap(&a,&b);
printf(“after swapping a=%d b=%d”,a,b);
}
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
65
PROBLEM 66:- A recursive function in C for finding the factorial of a given
number n.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
long int n,f;
long int fact(long int);
printf(“enter value for n”);
scanf(“%ld”,&n);
f=fact(n);
printf(“factorial of %ld is %ld “,n,f);
}
long int fact(long int n)
{
if(n= =0)
return(1);
else
return(n*fact(n-1));
}
66
PROBLEM 67:- Compare two strings.
PROCEDURE:-
1.read two string
2.find the lengths of each string if they are equal then only proceed for comparision
3.start extracting character by character from the both the strings till the end of strings
4.compare the characters extracted
5.if at any point they are not equal stop further comparision and print that strings unequal
6.else print that strings are equal
CODE:-
#include<stdio.h>
void main()
{
char str[20],str1[20];
int flag=0,i=0;
void strcp(char [ ], char [ ]);
int x;
printf(“enter the first string”); gets(str);
printf(“enter the second string”); gets(str1);
n=strlen(str); m=strlen(str1);
if(m= =n)
{
strcp(str,str1);
}
else
printf(“uncomparable”);
}
void strcp(char *s1, char *s2)
{
int i=0,flag=0;
while(*s1!=’\0’)
{
if(*s1!=*s2)
{
flag=1; break;
}
s1++; s2++;
}
if(flag= =0)
printf(“strings are equal”);
else
printf(“strings are unequal”);
}
Input:-enter first string: HELLO
Enter second string: HELLO
Output:-strings are equal
67
PROBLEM 68:- Sort table of strings .
PROCEDURE:-
1. Enter n strings
2. compare string with its successor string using strcmp() function
3. if its value is greater than 0 then swap both the strings
4. repeat the process until all the strings are sorted
5. print the sorted strings
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
int n,i,j;
char s[100][100],t[100];
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter %d strings “,n);
for(i=0;i<n;i++)
scanf(“%s”,s[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(s[i],s[j])>0)
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
printf(“the sorted strings are\n”);
for(i=0;i<n;i++)
printf(“%s \n”, s[i]);
}
Input:-enter value for n 3
Enter 3 strings xxx aaa ccc
Output:-the sorted string are: aaa ccc xxx
68
PROBLEM 69:- Find sum of first n numbers using recursive function.
PROCEDURE:-
1. Read number n
2. if n=0 return 0 else
3. recursively find s=n+sum(n-1)
4. print s
CODE:-
#include<stdio.h>
void main()
{
int n,x,sum(int);
printf(“enter value for n”);
scanf(“%d”,&n);
x=sum(n);
printf(“sum upto %d numbers is %d”,n,x);
}
int sum(int n)
{
if (n= = 0)
return(0);
else
return(n+sum(n-1));
}
69
PROBLEM 70:- Find Standard Deviation for a set of values .
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n ,x[100],i;
float avg,sum=0,sn,sd;
printf(“enter value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&x[i]);
sum=sum+x[i];
}
avg=sum/n;
sn=0;
for(i=1;i<=n;i++)
sn = sn + (x[i]-avg)*(x[i]-avg);
sd= (1.0/n)*sqrt(sn);
printf(“the standard deviation is %f “, sd);
}
Output:-sd=0.25
70
PROGRAMS ON STRUCTURES:
71
for(i=0;i<n;i++)
gt+=st[i].tst[i];
for(j=0;j<m;j++)
gt+=st[j].ts[j];
for(i=0;i<m;i++)
printf(“\t sub %d\t”,i+1);
printf(“student total \n”);
for(i=0;i<n;i++)
{ printf(“ %5d”,j+1);
for(j=0;j<n;j++)
{
printf(“%d \t”,st[i].s[j]);
}
printf(“%d \n”,st[i].tst[i]);
}
printf(“sun tot \t”);
for(i=0;i<m;i++)
printf(“%5d”,st[i].ts[i]);
printf(“%5d”,gt);
}
Input:-
enter no. of students 5
enter no. of subjects 4
enter 5 students 4 subject marks
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40
50 50 50 50
Output:-
72
PROBLEM 72:- Write a simple program method of sending an entire
structure as a parameter to a function.
PROCEDURE:-
CODE:-
#include<stdio.h>
struct abc
{
int a;
float b;
};
void main()
{
struct abc s1={10,10.5};
struct abc s2;
struct abc modify(struct abc );
printf(“ the structure members before modification are :”);
printf(“%5d %8.3f”,s1.a,s1.b);
s2=modify(s1);
printf(“ the structure members after modification are :”);
printf(“%5d %8.3f”,s2.a,s2.b);
}
73
PROBLEM 73:- Write a suitable program to explain the concept of
UNIONS.
PROCEDURE:-
1.read values for a union members through union variable
2 assign values to each member and print it immediately.
CODE:-
#include<stdio.h>
union abc
{
int a;
float b;
};
void main()
{
union abc s1;
printf(“ the union members values are:”);
scanf(“\n%d”,&s1.a);
printf(“%d”,s1.a);
scanf(“%f”,&s1.b);
printf(“\n%f”,s1.b);
}
74
PROGRAMS USING POINTERS
PROBLEM 74:- Perform all arithmetic operations using pointer variables.
PROCEDURE:-
1. read two values a and b store addresses of a and b in p and q
2. perform arithmetic manipulations using pointers p and q
CODE:-
#include<stdio.h>
void main()
{
int a,b,ch;
int *p=&a,*q=&b;
printf(“enter value for a and b”);
scanf(“%d %d”,&a,&b);
printf(“enter ur choice 1:add 2:subtract 3: multiply 4: divide 5:exit”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“the sum = %d “,(*p+*q));
break;
case 2: printf(“the difference = %d “,(*p-*q));
break;
case 3: printf(“the product = %d “,(*p * (*q)));
break;
case 4: printf(“the quotient = %d “,(*p/(*q)));
break;
case 5: exit();
}
}
Input:-enter values for a and b 5 2
Output:-the sum= 7
The difference =3
The product = 10
The quotient =2
75
PROBLEM 75:- Write a program to compute the sum of all elements stored in
an array.
PROCEDURE:-
#include<stdio.h>
void main()
{
int a[20],i,n,*x,sum=0;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter %d elements “,n);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
x=&a[0];
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+*x;
x++;
}
printf(“the sum=%d”,sum);
}
76
PROBLEM 76:- Write a program to find the length of string.
PROCEDURE:-
1. read string
2. while moving till the end of string increment a counter value C
3. print C value
CODE:-
#include<stdio.h>
void main()
{
char str[20];
char s=&str[0];
int i=0;
printf(“enter a string”);
gets(str);
while(*s!=’\0’)
{
i++;
s++;
}
printf(“the length of the string is %d”,i);
}
77
PROBLEM 77:- Write a program to sort a given set of numbers.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int n, *a,i,j,t;
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter the array elements”);
for(i=1;i<=n;i++)
scanf(“%d”,(a+i));
for(i=1;i<n;i++)
for(j=1;j<=n-i;j++)
{
if(*(a+j)>*(a+j+1))
{
t=*(a+j);
*(a+j)=*(a+j+1);
*(a+j+1)=t;
}
}
printf(“the sorted data is”);
for(i=1;i<=n;i++)
printf(“%4d”,*(a+i));
}
78
PROBLEM 78: Write a program to find matrix multiplication.
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,a[10][10],b[10][10],c[10][10],*p,*q,*r,l,m,n,o;
clrscr();
printf("Enter Dimentions for First matrix :");
scanf("%d%d",&l,&m);
printf("Enter Dimentions for Second matrix :");
scanf("%d%d",&n,&o);
if(m==n)
{
printf("\nEnter First Matrix : ");
for(i=0;i<l;i++)
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
printf("\nEnter Second Matrix : ");
for(i=0;i<n;i++)
for(j=0;j<o;j++)
scanf("%d",&b[i][j]);
for(i=0;i<l;i++)
for(j=0;j<m;j++)
{
*(*(c+i)+j)=0;
for(k=0;k<n;k++)
*(*(c+i)+j) = *(*(c+i)+j) + (*(*(a+i)+k)) * (*(*(b+k)+j));
}
79
printf("\n The Product of two Matrix");
for(i=0;i<n;i++)
{
for(j=0;j<o;j++)
printf("%3d",c[i][j]);
printf("\n");}
}
else
printf("\nMatrix Multimplication is Not Posible");
getch();
}
Input:- enter value for m n 2 2 Enter the first matrix : 3 3
3 3
80
PROBLEM 79:- Compare two strings.
PROCEDURE:-
1.read two string
2.find the lengths of each string if they are equal then only proceed for comparision
3.start extracting character by character from the both the strings till the end of strings
4.compare the characters extracted
5.if at any point they are not equal stop further comparision and print that strings unequal
6.else print that strings are equal
CODE:-
#include<stdio.h>
void main()
{
char str[20],str1[20];
char *s1=&str[0];
char *s2=&str1[0];
int n,m,flag;
printf(“enter first string”);
gets(str);
printf(“enter second string”);
gets(str1);
n=strlen(str);
m=strlen(str1);
if(n= =m)
{
flag=0;
while(*s1!=’\0’)
{
if(*s1!=*s2)
{
flag=1;
break;
}
s1++;
s2++;
}
if(flag= =0)
printf(“strings are equal”);
else
printf(“strings are not equal”);
}
else
printf(“strings are uncomparable”);
}
Input:-enter first string: HELLO
Enter second string: HELLO
Output:-strings are equal
81
PROBLEM 80:- Copy contents of one string to another.
PROCEDURE:-
1.Read a string S
2.extract character by character from S and copy it into S1 till end of S
3.print S1
CODE:-
#include<stdio.h>
void main()
{
char str[20],str1[20];
char *s1=&str[0];
char *s2=&str1[0];
int n,m,flag;
printf(“enter the string”);
gets(str);
while(*s1!=’\0’)
{
*s2=*s1;
s1++
s2++;
}
*s2=’\0’;
printf(“the copied string is “);
puts(str1);
}
82
PROBLEM 81:- Sort table of string .
PROCEDURE:-
1. Enter n strings
2. compare string with its successor string using strcmp() function
3. if its value is greater than 0 then swap both the strings
4. repeat the process until all the strings are sorted
5. print the sorted strings
CODE:-
#include<stdio.h>
#include<string.h>
void main()
{
int n,i,j;
char s[100][100],t[100];
printf(“enter value for n”);
scanf(“%d”,&n);
printf(“enter %d strings “,n);
for(i=0;i<n;i++)
scanf(“%s”,s[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(*(s+i),*(s+j))>0)
{
strcpy(t,*(s+i));
strcpy(*(s+i),*(s+j));
strcpy(*(s+j),t);
}
printf(“the sorted strings are\n”);
for(i=0;i<n;i++)
printf(“%s \n”, s[i]);
}
Input:-enter value for n 3
Enter 3 strings xxx aaa ccc
Output:-the sorted string are: aaa ccc xxx
83
PROBLEM 82:- Show call by reference concept in structures.
PROCEDURE:-
#include<stdio.h>
struct abc
{
int a;
float b;
};
void main()
{
struct abc s1={10,10.5};
void modify(struct abc *);
printf(“ the structure members before modification are :”);
printf(“%5d %8.3f”,s1.a,s1.b);
modify(&s1);
printf(“ the structure members after modification are :”);
printf(“%5d %8.3f”,s1.a,s2.b);
}
84
PROBLEM 83:- Write an example program which uses pointer to a structure.
PROCEDURE:-
CODE:-
#include<stdio.h>
struct abc
{
int a;
float b;
};
void main()
{
struct abc s1={10,10.5};
struct abc *p=&s1;
printf(“the contents of the structure”);
printf(“%d”,p->a);
printf(“\n%f “,p->b);
}
85
PROBLEM 84:- Write a program that uses a function returning a pointer.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
int *b;
int *func();
b=func();
printf(“value =%d”,*b);
}
int *func()
{
int j=50;
return(&j);
}
Output:-value =50
86
PROGRAMS USING FILES:
PROBLEM 85:- Write a program with a file named DATA contains a series
of integer numbers.Code a program to read these numbers and then write all
odd numbers to a file called ODD and all even numbers to a file called EVEN.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE *f1, *f2,*f3;
int i,n;
f1=fopen(“intfile”,”w”);
f2=fopen(“odd”,”w”);
f3=fopen(“even”,”w”);
printf(“enter 10 numbers into a file”);
for(i=1;i<=10;i++)
{
scanf(“%d”,&n);
putw(n,f1);
}
fclose(f1);
f1=fopen(“intfile”,”r”);
while((n=getw(f1))!=EOF)
if(n%2= =0)
putw(n,f3);
else
putw(n,f2);
}
fclose(f2);
fclose(f3);
f2=fopen(“odd”,”r”);
f3=fopen(“even”,”r”);
printf(“the contents of odd file are\n”);
while((n=getw(f2))!=EOF)
printf(“%3d”,n);
87
printf(“the contents of even file are\n”);
while((n=getw(f3))!=EOF)
printf(“%3d”,n);
fclose(f1);
fclose(f2);
fclose(f3);
}
88
PROBLEM 86:- Write a program with a file named TEXT (with a
paragraph in it).Code a program to read this paragraph and then write all
vowels to a file called VOWEL and consonants to a file called
CONSONANT.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE *f1, *f2,*f3;
Char c;
f1=fopen(“text”,”w”);
f2=fopen(“vowel”,”w”);
f3=fopen(“consonant”,”w”);
printf(“enter a paragraph”);
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen(“text”,”r”);
while((c=getc(f1))!=EOF)
{
if(c= =’a’ || c= =’e’ || c= =’i’ || c= =’o’ || c= =’u’)
putc(c,f2);
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
f2=fopen(“vowel”,”r”);
f3=fopen(“consonant”,”r”);
printf(“the contents of VOWEL file are\n”);
while((c=getc(f2))!=EOF)
putchar(c);
printf(“the contents of CONSONANT file are\n”);
while((c=getc(f3))!=EOF)
putchar(c);
89
fclose(f1);
fclose(f2);
fclose(f3);
}
90
PROBLEM 87:- Write a program to store text into a file , modify the same file
by replacing all the ‘a’s with ‘#’.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE *f1;
char c;
printf(“enter data to a file”);
f1=fopen(“data”,”w”);
While((c=getchar())!=EOF)
{
putc(c,f1);
}
fclose(f1);
f1=fopen(“data”,”w+”);
while((c=getc(f1))!=EOF)
{
if(c= =’a’);
putc(‘#’,f1);
}
fclose(f1);
printf(“the modified data file is \n”);
f1=fopen(“data”,”r”);
while((c=getc(f1))!=EOF)
putchar(c );
fclose(f1);
}
91
PROBLEM 88:- Write a program to create two text files , append the second
text file at the end of first file.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE *f1,*f2;
char c;
printf(“enter data to a file”);
f1=fopen(“data”,”w”);
While((c=getchar())!=EOF)
{
putc(c,f1);
}
fclose(f1);
printf(“enter data to a file”);
f2=fopen(“data1”,”w”);
While((c=getchar())!=EOF)
{
putc(c,f2);
}
fclose(f2);
f1=fopen(“data”,”a+”);
f2=fopen(“data1”,”r”);
while((c=getc(f2))!=EOF)
{
putc(c,f1);
}
fclose(f1);
fclose(f2);
printf(“the modified data file is \n”);
f1=fopen(“data”,”r”);
while((c=getc(f1))!=EOF)
92
putchar(c );
fclose(f1);
}
93
PROBLEM 89:- Write a program to copy contents of one file to another.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE f1,f2;
char c;
f1=fopen(“data1”,”w”);
f2=fopen(“data2”,”w”);
printf(“enter data to a file”);
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen(“data1”,”r”);
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f2);
f2=fopen(“data2”,”r”);
while((c=getc(f2))!=EOF)
putchar(c);
fclose(f1);
fclose(f2);
}
94
PROBLEM 90:- Write a program to see contents of file.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
FILE f1;
char c;
f1=fopen(“data1”,”w”);
printf(“enter data to a file”);
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen(“data1”,”r”);
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f2);
f2=fopen(“data2”,”r”);
while((c=getc(f2))!=EOF)
putchar(c);
fclose(f1);
fclose(f2);
}
95
PROBLEM 91:- Write a program to error handling in file operations.
PROCEDURE:-
CODE:-
#include<stdio.h>
void main()
{
char *filename;
FILE *fp1,*fp2;
int i,num;
for(i=10;i<=100;i+=10)
putw(i,fp1);
printf(“input filename”);
open-file:
scanf(“%s”,filename);
if((fp2= fopen(filename,”r”))= =NULL)
{
printf(“cannot open file”);
printf(“type filename once again”);
goto open-file;
}
else
for(i=1;i<=20;i++)
{
num=getw(fp2);
if(feof(fp2))
{
printf(“ran out of data”);
break;
}
else
printf(“%d”,num);
}
fclose(fp2);
}
96
PROBLEM 92:- Write a formatted data to a file and extract the
same(fscanf,fprintf)
PROCEDURE:-
1. fscanf () and fprintf () are used to store data in formatted form and to extract the same in
formatted form
CODE:-
#include<stdio.h>
void main()
{
FILE *fp;
int num,qty,i;
float price,value;
char item[10],filename[10];
fp=fopen(filename,”w”);
printf(“ itemname number price qty\n”);
for(i=1;i<=3;i++)
{
scanf(“%s%d%f%d”,item,&num,&price,&qty);
fclose(fp);
fp=fopen(filename,”r”);
for(i=1;i<=3;i++)
fscanf(fp,”%s %d %f %d”,item,&num,&price,&qty);
value=price*qty;
fclose(fp);
97
PROBLEM 93:- Write a program that uses the functions ftell and fseek.
PROCEDURE:-
1. file pointer can be move anywhere in the file randomly using fseek()
2. ftell() is used to find the number of bytes the current pointer is existing from beginning
of the file.
CODE:-
#include<stdio.h>
void main()
{
FILE *fp;
long n;
char c;
fp=fopen(“random”,”w”);
while((c=getchar())!=EOF)
putc(c,fp);
fclose(fp);
fp=fopen(“random”,”r”);
n=0;
while(feof(fp)= =0)
{
fseek(fp,n,0);
printf(“position of %c is %ld”,getc(fp),ftell(fp));
n=n+5;
}
fclose(fp);
}
98
PROBLEM 94:- Write a program that will receive a filename and a line of
text as command line arguments and write the text to afile.
PROCEDURE:-
1. command line arguments are argc, argv which are used as parameters in main function
2. argc specifies the no. of strings involved in the command
3. argv specifies strings involved in the command
4. command line arguments are used to redefine existing dos commands in our terms
5. as well as to provide file names at run time
CODE:-
#include<stdio.h>
void main(int argc,char *argv[])
{
FILE *fp;
int i;
char word[15];
fp=fopen(argv[1],”w”);
printf(“\nNo. Of arguments in command line =%d\n”,argc);
for(i=2;i<argc;i++)
fprintf(fp,”%s”,argv[i]);
fclose(fp);
printf(“contents of %s file \n\n”,argv[1]);
fp=fopen(argv[1],”r”);
for(i=2;i<argc;i++)
{
fscanf(fp,”%s”,word);
printf(“%s”,word);
}
fclose(fp);
for(i=0;i<argc;i++)
printf(“%*s\n”,i*5,argv[i]);
}
99
PROBLEM 95:- Write a program to copy contents of one file to another using
command line arguments.
PROCEDURE:-
1. command line arguments are argc, argv which are used as parameters in main function
2. argc specifies the no. of strings involved in the command
3. argv specifies strings involved in the command
4. command line arguments are used to redefine existing dos commands in our terms
5. as well as to provide file names at run time
CODE:-
#include<stdio.h>
void main(int argc,char *argv[])
{
FILE *f1,*f2;
char c;
f1=fopen(argv[1],”r”);
f2=fopen(argv[2],”w”);
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f1);
fclose(f2);
}
100
PROBLEM 96:- Write a program to see contents of a file using command line
arguments.
PROCEDURE:-
1 command line arguments are argc, argv which are used as parameters in main function
2 argc specifies the no. of strings involved in the command
3 argv specifies strings involved in the command
4 command line arguments are used to redefine existing dos commands in our terms
5 as well as to provide file names at run time
CODE:-
#include<stdio.h>
void main(int argc,char *argv[])
{
FILE *f1;
char c;
f1=fopen(argv[1],”r”);
while((c=getc(f1))!=EOF)
putchar (c );
fclose(f1);
}
101
PROBLEM 97:- Write a program to delete a file using command line
arguments.
PROCEDURE:-
1. command line arguments are argc, argv which are used as parameters in main function
2. argc specifies the no. of strings involved in the command
3. argv specifies strings involved in the command
4. command line arguments are used to redefine existing dos commands in our terms
5. as well as to provide file names at run time
CODE:-
102
PROBLEM 98:- Write a program to store a character string in a block of
memory space created by MALLOC() and then modify the same to store a
larger string.
PROCEDURE:-
1. MALLOC() function is used to allocate memory at run time , initialized with garbage
values
2. realloc() is used to modify the existing size of memory allocated with the help of
MALLOC()
CODE:-
#include<stdio.h>
#define NULL 0
void main()
{
char *buffer;
if((buffer=(char *)malloc(10))= = NULL)
{
printf(“malloc failed”);
exit(1);
}
printf(“buffer of size %d created \n”,_msize(buffer));
strcpy(buffer,”HYDERBAD”);
printf(“\nBuffer containsn:%s\n”,buffer);
if((buffer=(char *)realloc(buffer,15))= =NULL)
{
printf(“reallocation failed\n”);
exit(1);
}
printf(“\nbuffer size modified\n”);
printf(“\nbuffer still contains : %s\n”,buffer);
strcpy(buffer,”SECUNDERABAD”);
printf(“\nbuffer now contains : %s\n”,buffer);
free(buffer);
}
103
PROBLEM 99:- Write a small example program to explain the usage of
CALLOC().
PROCEDURE:-
1. CALLOC() function is used to allocate memory for a set of blocks at run time
CODE:-
#include<stdio.h>
#define NULL 0
void main()
{
char *buffer;
if((buffer=(char *)calloc(10,1))= = NULL)
{
printf(“calloc failed”);
exit(1);
}
printf(“buffer of size %d created \n”,_msize(buffer));
strcpy(buffer,”HYDERBAD”);
printf(“\nBuffer containsn:%s\n”,buffer);
if((buffer=(char *)realloc(buffer,15))= =NULL)
{
printf(“reallocation failed\n”);
exit(1);
}
printf(“\nbuffer size modified\n”);
printf(“\nbuffer still contains : %s\n”,buffer);
strcpy(buffer,”SECUNDERABAD”);
printf(“\nbuffer now contains : %s\n”,buffer);
free(buffer);
}
104
DATA STRUCTURES:
PROGRAMS ON STACKS
PROCEDURE:-
1.PUSH(x,n,top)
x is item to be pushed , n is max. no. of elements in stack,top initially set to -1
a) if(top = n-1) print “stack overflow”
b) else increment top by 1, stack[top]=x;
2. POP(x,n,top)
x is item to be popped , n is max. no. of elements in stack,top is pointing to a position in stack
a)if(top=-1) print “stack underflow”
b) else set x=stack[top] ,return(x) and decrement top by 1
CODE:-
#include<stdio.h>
#define max 10
void push(int);
int pop();
void display();
int stack[max],top=-1;
void main()
{
char ch=’y’;
int c,x;
while(ch= =’y’)
{
printf(“1: push 2: pop 3: display 4: exit\n”);
printf(“enter your choice”);
scanf(“%d”,&c);
switch(c)
{
case 1: printf(“enter the item to push”);
scanf(“%d”,&x);
push(x);
break;
case 2: printf(“the item popped is %d”,pop());
break;
case 3: printf(“the contents of the stack are\n”);
display();
105
break;
}
printf(“do you want to continue (y/n)”);
ch=getchar();
}
}
void push(int x)
{
if(top= = max-1)
{
printf(“stack is full”);
exit();
}
stack[++top]=x;
}
int pop()
{
if (top= = -1)
{
printf(“stack is empty”);
exit();
}
return(stack[top--]);
}
void display()
{
int i;
if(top= =-1)
{
printf(“stack is empty”);
exit();
}
else
{
for(i=top;i>=0;i--)
printf(\n%3d”,stack[i]);
}
}
106
PROBLEM 101:- Write a program to convert infix to post fix expression.
PROCEDURE:-
POSTFIX(Q,P)
Suppose Q is an arithmetic expression written in infix notation. This alg. finds the equivalent
postfix expression P.
1. Push “(“ onto STACK, and add “)” to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the STACK
is empty:
3. if an operand is encountered, add it to P.
4. if a left parenthesis is encountered , push it onto STACK.
5. if an operator X is encountered ,then :
a.Repeatedly pop from STACK and add to P each operator (on the top of STACK)
which has the same precedence as or higher precedence than X.
b. Add X to STACK.
[ end of IF structure]
6. if a right parenthesis is encountered, then:
a.Repeatedly pop from STACK and add to P each operator(on the top of STACK}
until a left parenthesis is encountered.
b. Remove the left parenthesis.
[end of IF structure]
[end of step 2 loop.]
7. exit.
CODE:-
#include<stdio.h>
void push(); char pop(); int prec();int top=-1;
char ifix[25], pfix[25],stack[20];
void main()
{
int i,j=0; char c;
printf(“enter the infix expression”);
gets(ifix);
for(i=0;ifix[i]!=’\0’,i++)
{
if(isalpha(ifix[i]))
{
pfix[j]=ifix[i];
j++;
}
else
if (ifix[i]= =’(‘)
push(ifix[i]);
else
107
if(ifix[i]= =’*’ || ifix[i]= =’\’ || ifix[i]= =’+’ || ifix[i]= =’-‘)
{
while(prec(stack[top])>= prec(ifix[i]))
pfix[j++]=pop();
push(ifix[i]);
}
else
if(ifix[i]= =’)’)
{
while(stack[top]!=’(‘)
pfix[j++]=pop();
c=pop();
}
}
pfix[j]=’\0’;
printf(“the postfix form of the infix %s is %s”,ifix,pfix);
}
void push(char c)
{
stack[++top]=c;
}
char pop()
{
return(stack[top--]);
}
int prec(char c)
{
switch(c )
{
case ‘*’:
case ‘/’: return(5);
break;
case ‘+’:
case ‘-‘: return(4);
break;
case ‘(‘: return(1);
}
}
108
PROBLEM 102:- Write a program to convert infix to pre fix expression.
PROCEDURE:-
PREFIX(Q,P)
Suppose Q is an arithmetic expression written in infix notation first reverse it. This alg. finds
the equivalent prefix expression P.
1.Push “)“ onto STACK, and add “(” to the end of Q
2.Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the STACK is
empty:
3.if an operand is encountered, add it to P.
4.if a right parenthesis is encountered , push it onto STACK.
5.if an operator X is encountered ,then :
c.Repeatedly pop from STACK and add to P each operator (on the top of STACK)
which has the higher precedence than X.
d. Add X to STACK.
[ end of IF structure]
6.if a left parenthesis is encountered, then:
e.Repeatedly pop from STACK and add to P each operator(on the top of STACK}
until a right parenthesis is encountered.
f. Remove the right parenthesis.
[end of IF structure]
[end of step 2 loop.]
7.reverse P.
8.exit.
CODE:-
#include<stdio.h>
void push();char pop();int prec();int top=-1;
char ifix[25], pfix[25],stack[20];
void main()
{
int i,j=0;
char c;
printf(“enter the infix expression”);
gets(ifix);
strrev(ifix);
for(i=0;ifix[i]!=’\0’,i++)
{
if(isalpha(ifix[i]))
{
pfix[j]=ifix[i];
j++;
}
else
109
if (ifix[i]= =’)‘)
push(ifix[i]);
else
if(ifix[i]= =’*’ || ifix[i]= =’\’ || ifix[i]= =’+’ || ifix[i]= =’-‘)
{
while(prec(stack[top])> prec(ifix[i]))
pfix[j++]=pop();
push(ifix[i]);
}
else
if(ifix[i]= =’(’)
{
while(stack[top]!=’)‘)
pfix[j++]=pop();
c=pop();
}
}
pfix[j]=’\0’;
printf(“the prefix form is %s ”,strrev(pfix));
}
void push(char c)
{
stack[++top]=c;
}
char pop()
{
return(stack[top--]);
}
int prec(char c)
{
switch(c )
{
case ‘*’:
case ‘/’: return(5);
break;
case ‘+’:
case ‘-‘: return(4);
break;
case ‘)‘: return(1);
}
}
Input:-enter infix expression: a+(b*c/d)
Output:- Prefix expression :+a/*bcd
110
PROBLEM 103:- Program to evaluate a given postfix expression using stack
PROCEDURE:-
CODE:-
#include<stdio.h>
#define max 30
int top=-1;
int stack[max];
void push(int a)
{
stack[++top]=a;
}
int pop() {
return(stack[top--]);
}
main()
{
int i,j=0,c[30],a,v;
char s[100];
clrscr();
printf(“Enter the postfix expression”);
for(i=0;(s[i]=getchar())1=’\n’;i++)
{
if(s[i]>=’a’ && s[i]<=’z’)
c[j++]=i;
}
printf(“Enter values”);
for(i=0;i<j;j++) {\
printf(“%c=”,s[c[i]]);
scanf(“%d”,&c[i]);
111
}
j=0;
for(i=0;s[i]!=’\n’;i++)
if(s[i]>=’a’ && s[i]<=’z’)
push(c[j++]);
else
{
v=pop();
switch(s[i])
{
case ‘+’ : a=pop()+v;
break;
case’-‘: a=pop()-v;
break;
case’*’: a=pop()*v;
break;
case ‘/’: a=pop()/v;
break;
}
push(a);
}
printf(“the result is %d”,pop());
getch();
}
Output:-the result is 13
112
PROBLEM 104:- Towers of Hanoi( Stack Application)
PROCEDURE:-
TOWER(N,BEG,AUX,END)
This procedure gives a recursive solution to the Towers of Hanoi problem for N disks.
1. If N=1, then:
(a) Write: BEG->END.
(b) Return. [End of If structure.]
2. [Move N-1 disks from peg BEG to peg AUX.]
Call TOWER(N-1,BEG,END,AUX).
3. Write: BEG->END.
4. [Move N-1 disks from peg AUX to peg END.]
Call TOWER(N-1,AUX,BEG,END).
5. Return.
CODE:-
#include<stdio.h>
#include<conio.h>
void main() {
int n;
char indl, sndl,dndl;
sndl=’a’;indl=’b’;dndl=’c’;
printf(“Enter the no.of discs”);
sacnf(“%d”,&n);
hanoii(n,sndl,indl,dndl);
getch();
}
hanoii(int n, char sndl, char indl, char dndl) {
if(n>0) {
hanoii(n-1,sndl,dndl,indl);
printf(“Move disc %d from %c to %c”, n,sndl,dndl);
hanoii(n-1,indl,sndl,dndl);
}
}
Input:-enter the no. of discs: 3 ( POLES are A B C)
Output:-move top disc from A to C
move top disc from A to B
move top disc from C to B
move top disc from A to C
move top disc from B to A
move top disc from B to C
move top disc from A to C
113
PROGRAMS ON QUEUES
PROCEDURE:-
1.QUEUEINSERT(QUEUE,N,FRONT,REAR,ITEM)
(This procedure inserts an element ITEM into a queue
a) [queue already filled]
if FRONT=0 and REAR=N-1 then: print “Overflow” return
b) else set REAR=REAR+1 and queue[REAR]=ITEM
2.QUEUEDELETE(QUEUE,N,FRONT,REAR,ITEM)
(This procedure inserts an element ITEM into a queue
b) [queue already filled]
if FRONT=0 and REAR=-1 then: print “UNDERFLOW” return
b) else set FRONT=FRONT+1
CODE:-
#include<stdio.h>
#define max 10
void insert(int);
int delete();
void display();
int queue[max],front=0, rear=-1;
void main()
{
char ch=’y’;
int c,x;
while(ch= =’y’)
{
printf(“1: insert 2: delete 3: display 4: exit\n”);
printf(“enter your choice”);
scanf(“%d”,&c);
switch(c)
{
case 1: printf(“enter the item to insert”);
scanf(“%d”,&x);
insert(x);
break;
case 2: printf(“the item deleted is %d”,delete());
break;
case 3: printf(“the contents of the queue are\n”);
display();
break;
114
}
printf(“do you want to continue (y/n)”);
ch=getchar();
}
}
void insert(int x)
{
if(rear= = max-1)
{
printf(“queue is full”);
exit();
}
queue[++rear]=x;
}
int delete()
{
if (front= =0 && rear= = -1)
{
printf(“queue is empty”);
exit();
}
return(queue[front--]);
}
void display()
{
int i;
if(front= =0 && rear= =-1)
{
printf(“queue is empty”);
exit();
}
else
{
for(i=front;i<=rear;i++)
printf(“%3d”,queue[i]);
}
}
115
PROBLEM 106: Write a program to implement a circular queue using
arrays.
PROCEDURE:-
1.CQUEUEINSERT(QUEUE,N,FRONT,REAR,ITEM)
(This procedure inserts an element ITEM into a queue
a) [queue already filled]
if FRONT=1 and REAR=N-1 or if FRONT = REAR+1 then: print “Overflow”
return
b) if FRONT=0 then set FRONT=1 and REAR=1
else if REAR=N then set REAR=1
else set REAR=REAR+1
c) set queue[REAR]=ITEM
d)return
2.CQUEUEDELETE(QUEUE,N,FRONT,REAR,ITEM)
(This procedure inserts an element ITEM into a queue
a)[queue already filled]
if FRONT=0 then: print “UNDERFLOW” return
b) set ITEM=queue[FRONT]
c) if FRONT=REAR then set FRONT=0 and REAR=0
d) else if FRONT=N then FRONT=1
e) else set FRONT=FRONT+1
f)return
CODE:-
#include<stdio.h>
#define max 10
void insert(int);
int delete();
void display();
int cqueue[max],front=0, rear=-1;
void main()
{
char ch=’y’;
int c,x;
while(ch= =’y’)
{
printf(“1: insert 2: delete 3: display 4: exit\n”);
printf(“enter your choice”);
scanf(“%d”,&c);
switch(c)
{
case 1: printf(“enter the item to insert”);
116
scanf(“%d”,&x);
insert(x);
break;
case 2: printf(“the item deleted is %d”,delete());
break;
case 3: printf(“the contents of the queue are\n”);
display();
break;
}
printf(“do you want to continue (y/n)”);
ch=getchar();
}
}
void insert(int x)
{
if
if ((front= =0 &&rear= = max-1) | | ((front= = rear+1)&&(front!=0&&rear!=-1)))
{
printf(“circular queue is full”);
exit();
}
else
{
rear=(rear+1)%max;
cqueue[rear]=x;
}
}
int delete()
{
if (front= =0 && rear= = -1)
{
printf(“queue is empty”);
exit();
}
else if (front= = rear)
{
x=front;
front=0;
rear =-1;
}
else
{
117
x=front;
front=(front+1)%max;
}
return(cqueue[x]);
}
void display()
{
int i;
if(front= =0 && rear= =-1)
{
printf(“queue is empty”);
exit();
}
else if (front<rear)
{
for(i=front;i<=rear;i++)
printf(“%3d”,cqueue[i]);
}
else if(front>=rear)
{
for(i=front;i<=max-1;i++)
printf(“%3d”,cqueue[i]);
front(i=0;i<front;i++)
printf(”%3d”,cqueue[i]);
}
}
118
PROBLEM 107:- Write a program to implement a dequeue using arrays
PROCEDURE:-
1.INSERTFRONT(ITEM,DQUEUE,N,FRONT,REAR)
ITEM to be inserted, DQUEUE array to store elements,N max. size of array
a) if FRONT=0 or if FRONT=0 and REAR=N-1 print “OVERFLOW” return
b) decrement FRONT by1 and DQUEUE[FRONT]=ITEM
2.INSERTREAR(ITEM,DQUEUE,N,FRONT,REAR)
ITEM to be inserted, DQUEUE array to store elements,N max. size of array
a) if FRONT=0 and REAR=N-1 print “OVERFLOW” return
b) increment REAR by1 and DQUEUE[REAR]=ITEM
3.DELETEFRONT(ITEM,DQUEUE,N,FRONT,REAR)
ITEM to be deleted, DQUEUE array to store elements,N max. size of array
a) if REAR =-1 print “UNDERFLOW” return
b) if FRONT= REAR then reset FRONT=0 AND REAR=-1
c) else increment FRONT by1
4.DELETEREAR(ITEM,DQUEUE,N,FRONT,REAR)
ITEM to be deleted, DQUEUE array to store elements,N max. size of array
a) if REAR =-1 print “UNDERFLOW” return
b) if FRONT= REAR then reset FRONT=0 AND REAR=-1
c)else decrement REAR by1
CODE:-
#include<stdio.h>
#include<conio.h>
# define max 4
int r=-1,f=0,u,r;
char dq[max];
void insertf(char c) {
if(f==0 || (f==0 && r==max-1)) {
printf(“Insertion not possible from f”);
getch();
}
else {
dq[--f]=c;
}
}
char dltf() {
if(r= =-1) {
119
u=1;
printf(“deletion not possible from f”);
}
else if(f==r) {
t=f;
f=0;
r=-1;
return(dq[t]);
}
else return(dq[f++)
}
void insertr(char c) {
if(r= =max-1 && f= =0) {
printf(“insertion not possible form r”);
getch();
}
else
dq[++r] =c;
}
char dltr() {
if(r==-1 {
u=-1;
printf(“deletion not possible r”);
}
else if (r==f) {
t=r;
r=-2;
f=0;
return(dq[t]);
}
else
return(dq[r--]);
}
main() {
int i, n;
char c;
do {
clrscr();
printf(“\n 1: Insert front\n”);
printf(“ 2: Insert Rear \n”);
printf(“ 3: Delete Front \n”);
printf(“ 4: Delete Rear \n”);
printf(“ 5: Display \n”);
printf(“ 6: Quit \n”);
120
printf(“ Enter choice \n”);
scanf(“%d”,&n);
switch(n) {
case 1: printf(“Enter Item to be inserted”);
flushall();
c=getchar();
insertf(c);
break;
case 2: printf(“Enter item to be inserted”);
flushall();
c=getchar();
insertr©;
break;
case 3: c=dltf();
if(u!=1)
printf(“deleted %c”,c);
getch();
u=0;
reak;
case 4: c=dltr();
if(u!=1)
printf(“deleted %c”,c);
getch();
u=0;
break;
case 5: for (i=f;i<=r;i++)
printf(“%c”,dq[i]);
getch();
}
}while(n!=6);
}
121
PROGRAMS ON LINKED LISTS
PROCEDURE:-
1.CREATE()
a) set FIRSTNODE to NULL and TEMPNODE to FIRSTNODE
b) create NEWNODE if FIRSTNODE=NULL then FIRSTNODE=NEWNODE and
TEMPNODE=NEWNODE
c) else set LINK[TEMPNODE]=NEWNODE
d) set TEMPNODE=NEWNODE
e) to create another node goto step b
f) set LINK[NEWNODE]=NULL
2. INSERTBEG()
a) create a NEWNODE
b) set LINK[NEWNODE]=FIRST
c) FIRST=NEWNODE
3. INSERTEND()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the last node using TEMP=LINK[TEMP]
d) set LINK[TEMP]=NEWNODE
4. INSERTPOS()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the position required using TEMP=LINK[TEMP]
d) set LINK[NEWNODE]=LINK[TEMP], and set LINK[TEMP]=NEWNODE
5. DELETEBEG()
a) FIRST= LINK[FIRST]
3. DELETEEND()
a) set TEMP=FIRST
b) traverse till the last but one node using TEMP=LINK[TEMP]
c) set LINK[TEMP]=NULL
4. DELETEPOS()
a) set TEMP=FIRST
b) traverse till the position required using TEMP=LINK[TEMP]
d) set TEMP=LINK[LINK[TEMP]]
CODE:-
#include<stdio.h>
#include<alloc.h>
struct sll
{
122
int data;
struct ll *link;
};
typedef struct sll node;
node *first=NULL,*new;
void create(), insertbeg(), insertmid(), insertend();
void delbeg(), delmid(),delend();
void display();
void main()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: create 2: insert 3: delete 4: display 5: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: create();
break;
case 2: insert();
break;
case 3: delete();
break;
case 4: display();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void create()
{
node *temp;
char ch=’y’;
temp=first;
do
{
printf(“enter the data for the new node\n”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
if(first= =NULL)
{
first=new;
123
temp=new;
new->link=NULL;
}
else
{
temp->link=new;
new->link=NULL;
temp=new;
}
printf(“do you want to create another node(y/n)”);
ch=getchar();
}while(ch!=’n’);
}
void insert()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: insertbeg 2: insertmid 3: insertend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: insertbeg();
break;
case 2: insertmid();
break;
case 3: insertend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void insertbeg()
{
printf(“ enter data for node to be added in the beginning”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
if(first= = NULL)
{first =new;
new->link=NULL;
}
124
else
{
new->link=first;
first=new;
}
}
void insertmid()
{
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to insert a node”);
scanf(“%d”,&pos);
printf(“ enter data for node to be added at the position %d”,pos);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(i<pos)
{
temp=temp->link;
i++;
}
new->link=temp->link;
temp->link=new;
}
}
void insertend()
{
node *temp;
temp=first;
printf(“ enter data for node to be added at end”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=new;
new->link=NULL;
}
void delete()
{
char ch=’y’;
int c;
125
while(ch= = ‘y’)
{
printf(“ 1: delbeg 2: delmid 3: delend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: delbeg();
break;
case 2: delmid();
break;
case 3: delend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void delbeg()
{
if(first= = NULL)
{printf(deletion not possible “);
exit();
}
else
{
first=first->link;
}
}
void delmid()
{
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to delete a node”);
scanf(“%d”,&pos);
while(i<pos)
{
temp=temp->link;
i++;
}
temp->link=temp->link->link;
126
void delend()
{
node *temp;
temp=first;
while(temp->link->link!=NULL)
{
temp=temp->link;
}
temp->link=NULL;
}
void display()
{
node * temp;
if (first= =NULL)
{
printf(“linked list is empty”);
exit();
}
else
{
printf(“the contents of single linked list are :\n”);
temp=first;
while(temp!=NULL)
{
printf(“%3d”,temp->data);
temp=temp->link;
}
}
127
PROBLEM 109:- Write a program to implement push and pop operations in
a stack using linked list.
PROCEDURE:-
1.CREATE()
a) set FIRSTNODE to NULL and TEMPNODE to FIRSTNODE
b) create NEWNODE if FIRSTNODE=NULL then FIRSTNODE=NEWNODE and
TEMPNODE=NEWNODE
c) else set LINK[NEWNODE]=FIRST
d) FIRST=NEWNODE
2. PUSH()
a) create a NEWNODE
b) set LINK[NEWNODE]=FIRST
c) FIRST=NEWNODE
3. POP()
a) FIRST= LINK[FIRST]
CODE:-
#include<stdio.h>
struct node
{
int qyt;
struct node *next;
};
void main()
{
struct node *start;
int stop;
char k;
struct node *push(void);
struct node *pop(void);
void display(void);
printf(“stack using single linked list”);
start=NULL;
stop=0;
do
{
printf(“ push : P pop: O exit: E”);
printf(“enter choice”);
do k=getchar(); while(strchr(“PpOoEe”,k)= = NULL);
switch(k)
{
case ‘P’:
case ‘p’: start=push(start);
printf(“STACK”);
128
display(start);
break;
case ‘O’:
case ‘o’ : start=pop(start);
printf(“STACK”);
display(start);
break;
case ‘E’:
case ‘e’: stop=1;
}
}while(!stop);
}
void display(struct node *record)
{
printf(“ROOT”);
while(record!=NULL)
{
printf(“%d”,&record->qty);
record=record->next;
}
return();
}
129
printf(“popped element =%d”,first->element);
temp=first->next;
free(first);
first=temp;
if(first= =NULL) printf(“empty”);
}
return(first);
}
130
PROBLEM 110:- Write a program to implement queue operations using
linked list.
PROCEDURE:-
1.ADDREAR(ITEM)
traverse till the end and always add data at the end
2.DELETEFRON(ITEM)
always delete elements from front end only
CODE:-
#include<stdio.h>
struct queue
{
struct node *front, *rear;
}*q;
struct node
{
int data;
struct node *next;
};
void insert(struct queue *q,int x)
{
struct node *new;
new=(struct node *)malloc(sizeof(struct node));
new->data=x;
new->next=NULL;
if(q->rear= =NULL)
q->front=new;
q->rear=new;
else
q->rear->next=new;
q->rear=new;
}
131
q->front=q->front->next;
}
}
void main()
{
int x, ch;
printf(“1:insert 2: delete 3:display 4:exit”);
printf(“enter choice”);
scanf(“%d”,&ch);
while(ch!=4)
{
switch(ch)
{
case 1: printf(“enter the number to be inserted”);
scanf(“%d”,&x);
insert(q,x);
break;
case 2: x=delete(q);
printf(“element deleted is %d”,x);
break;
case 3: display();
break;
case 4: exit(0);
}
printf(“1:insert 2: delete 3:display 4:exit”);
printf(“enter choice”);
scanf(“%d”,&ch);
}
getch();
}
132
PROBLEM 111:- Linked list Concatenation
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
struct node {
int info;
struct node *l;
}*fl=NULL,*s1,*s,*f,*n,*t,*t1;
struct node create() {
char c= ‘y’
f=NULL;
while(c= =’y’) {
n=(struct node *)malloc(sizeof(struct node));
printf(“Enter the data”);
scanf(“%d”,&n->info);
if(f= =NULL) {
f=n;t=f;
}
else {
t->l=n;
t=n;
}
n->l=NULL;
printf(“continue(y/n”);
flushall();
c=getchar();
}
return(f)
}
Void Display(struct node f)
{
Printf(“ist LL”);
For(t=f;t!=NULL;t=t->l)
Printf(“%d”,t->info);
Printf(“\n 2nd LL”);
For(t=f1;t!=NULL;t=t->l)
Printf(“%d”,t->info);
133
}
struct node concat(struct node f,struct node t)
{
t1=f;
while(t1->l!=NULL)
{
t1=t1->l;
}
t1->l=t ;
return(f) ;
}
void main() {
int n;
clrscr();
do{
printf(“1: create\n 2: concat\n 3: Display 4.quit\n Enter choice”);
scanf(%d”,&n);
switch(n) {
case 1: f=create();
t=create();
break;
case 2: f1=concat(f,t);
break;
case 3: display(f1);
break:
}
}while(n!=4);
}
134
PROBLEM 112:- Merging of two linked lists
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
struct node {
int info;
struct node *l;
}*fl=NULL,*s1,*s,*f,*n,*t,*t1;
struct node create() {
char c= ‘y’
f=NULL;
while(c= =’y’) {
n=(struct node *)malloc(sizeof(struct node));
printf(“Enter the data”);
scanf(“%d”,&n->info);
if(f= =NULL) {
f=n;t=f;
}
else {
t->l=n;
t=n;
}
n->l=NULL;
printf(“continue(y/n”);
flushall();
c=getchar();
}
return(f)
}
Void Display(struct node f)
{
Printf(“ist LL”);
For(t=f;t!=NULL;t=t->l)
Printf(“%d”,t->info);
Printf(“\n 2nd LL”);
135
For(t=f1;t!=NULL;t=t->l)
Printf(“%d”,t->info);
}
struct node merge(struct node t,struct node f1)
{
t=f;
while(t->l!=NULL && f1->l;!=NULL) {
s=t->l;
n=f1->l;
f1->l=t->l;
t->l=f1;
t=s;
f1=n;
}
if(t->l= =NULL)
t->l=f1->l;
if(f1->l= =NULL)
f1->l=t
}
return(t);
}
void main() {
int n;
clrscr();
do{
printf(“1: create\n 2: merge\n 3: Display 4.quit\n Enter choice”);
scanf(%d”,&n);
switch(n) {
case 1: f=create();
t=create();
break;
case 2: f1=merge(f,t);
break;
case 3: display(f1);
break:
}
}while(n!=4);
}
136
PROBLEM 113:- Spliting of linked list
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
struct node {
int info;
struct node *l;
}*fl=NULL,*s1,*s,*f,*n,*t,*t1;
struct node create() {
char c= ‘y’
f=NULL;
while(c= =’y’) {
n=(struct node *)malloc(sizeof(struct node));
printf(“Enter the data”);
scanf(“%d”,&n->info);
if(f= =NULL) {
f=n;t=f;
}
else {
t->l=n;
t=n;
}
n->l=NULL;
printf(“continue(y/n”);
flushall();
c=getchar();
}
return(f)
}
void split(struct node f) {
int i=1,n;
printf(“Enter the position”);
scanf(%d”,&n);
t=f;
while(i<n-1) {
137
t=t->l;
i++;
}
f1=t->l;
t->l=NULL;
printf(“SLL splited”);
display(t);
display(f1);
}
Void Display(struct node f)
{
Printf(“ LL is”);
For(t=f;t!=NULL;t=t->l)
Printf(“%d”,t->info);
}
void main() {
int n;
clrscr();
do{
printf(“1: create\n 2: split\n 3.quit\n Enter choice”);
scanf(%d”,&n);
switch(n) {
case 1: f=create();
break;
case 2: split(f);
break;
}
}while(n!=3);
}
138
PROBLEM 114:- Reversing a linked list
PROCEDURE:-
CODE:-
#include<stdio.h>
#include<conio.h>
struct node {
int info;
struct node *l;
}*fl=NULL,*s1,*s,*f,*n,*t,*t1;
struct node create() {
char c= ‘y’
f=NULL;
while(c= =’y’) {
n=(struct node *)malloc(sizeof(struct node));
printf(“Enter the data”);
scanf(“%d”,&n->info);
if(f= =NULL) {
f=n;t=f;
}
else {
t->l=n;
t=n;
}
n->l=NULL;
printf(“continue(y/n”);
flushall();
c=getchar();
}
return(f)
}
struct node rev() {
f1=f;
s=NULL;
while(f1!=NULL) {
t=f1->l;
f1->l=s;
139
s=f1;
f1=t;
}
f=s;
return(f);
}
void main() {
int n;
clrscr();
do{
printf(“1: create\n 2: split\n 3.quit\n Enter choice”);
scanf(%d”,&n);
switch(n) {
case 1: f=create();
break;
case 2: f=rev();
break;
case 3: display(f)
}
}while(n!=4);
}
140
PROBLEM 115:- Write a program to add two polynomials using linked
representation
PROCEDURE:-
1.enter two polynomials in terms of two linked lists P1 P2
2. repeat steps 3 to 5 while P1!=NULL
3. take power field of the node and start comparing with power fields in P2 until
P2!=NULL
4.if power fields are equal find sum of corresponding coeffiecients and place the result in
third linked list
5. set P1=LINK[P1]
CODE:-
Struct poly
{
int coeff,power;
struct poly *link;
}*p1,*p2,*p3,*prev,*temp,*first;
void create(int n)
{
int i=1;
first=(struct poly*)malloc(sizeod(struct poly));
printf(“\n Enter coeff & power:”);
scanf(“%d%d”,&first->coeff,&first->pow);
first->link-NULL;
prev=first;
p1=first;
while(i<n)
{
temp=struct poly *)malloc(sizeof(sizeof(struct poly));
scanf(:%d%d”,&temp->coeff,&temp->pow);
prev->link=temp;
prev=prev->link;
i++;
}
prev->link=NULL;
}
main()
{
int n1,n2,x;
printf(“Enter no. of item of poly 1:”);
scanf(“%d”,&n1);
printf(“Enter no. of item of poly 2:”);
scanf(“%d”,&n2);
crete(p1);
141
p1=first;
create(p2);
temp=(struct poly *)malloc(sizeod(struct poly));
p3=temp;
prev=temp;
while(p1!=NULL && p2!=NULL)
{
temp=(struct poly *)malloc(sizeof(struct poly));
if(p1->pow > p2->pow)
{
temp->pow=p1->pow;
temp->coeff = p1->coeff;
p1=p1->link;
}
else if (p2->pow > p1->pow)
{
temp->pow – p2->pow;
temp->coef = p2->coef;p2=p2->link;
}
else
{
x=p1->coeff+p2->coeff;
if(x!=0)
{
temp->ceoff=x;
temp->pow=p1->pow;
}
p1=p1->link;
p2=p2->link;
}
prev->link=temp;
prev=prev->link;
}
if(p1!=NULL)
{
while(p1!=NULL)
{
temp-struct poly *)malloc(sizeof(sturct poly));
temp->coef=p1->coef;
temp->pow=p1->pow;
p1=p1->link;
prev->link=temp;
prev->link;
prev=prev->link;
}
}
142
else if(p2!=NULL)
{
while(p2!=NULL)
{
temp=struct poly *)malloc(sizeof(struct poly));
temp->coef=p2->coef;
temp->pow=p2->pow;
p2=p2->link;
prev->link=temp;
prev=prev->link;
}
}
prev->link-NULL;
temp=p3;
p3=p3->link;
free(temp);
temp=p3;
printf(“:poly after addition is \n”);
while(temp!-NULL)
{
printf(“%3d * %d”,temp->coeff,temp->pow);
temp=temp->link;
}
getch();
}
143
PROBLEM 116:- Write a program to implement a circular single linked list
PROCEDURE:-
1.CREATE()
a) set FIRSTNODE to NULL and TEMPNODE to FIRSTNODE
b) create NEWNODE if FIRSTNODE=NULL then FIRSTNODE=NEWNODE and
TEMPNODE=NEWNODE
c) else set LINK[TEMPNODE]=NEWNODE
d) set TEMPNODE=NEWNODE
e) to create another node goto step b
f) set LINK[NEWNODE]=FIRST
2. INSERTBEG()
a) create a NEWNODE
b) set TEMP=FIRST traverse till the last node set LINK[TEMP]=NEWNODE
c) set LINK[NEWNODE]=FIRST, set FIRST=NEWNODE
3. INSERTEND()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the last node’s link field is not equal FIRST using TEMP=LINK[TEMP]
d) set LINK[TEMP]=NEWNODE and LINK[NEWNODE]=FIRST
4. INSERTPOS()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the position required using TEMP=LINK[TEMP]
d) set LINK[NEWNODE]=LINK[TEMP], and set LINK[TEMP]=NEWNODE
5. DELETEBEG()
a) Set TEMP=FIRST traverse until the last node’s link field is not equal to FIRST
and set TEMP= LINK[FIRST] and FIRST=LINK[FIRST]
3. DELETEEND()
a) set TEMP=FIRST
b) traverse till the last but one node using TEMP=LINK[TEMP]
c) set LINK[TEMP]=FIRST
4. DELETEPOS()
a) set TEMP=FIRST
b) traverse till the position required using TEMP=LINK[TEMP]
d) set TEMP=LINK[LINK[TEMP]]
CODE:-
#include<stdio.h>
#include<alloc.h>
struct csll
{
int data;
struct csll *link;
};
typedef struct csll node;
144
node *first=NULL,*new;
void create(), insertbeg(), insertmid(), insertend();
void delbeg(), delmid(),delend();
void display();
void main()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: create 2: insert 3: delete 4: display 5: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: create();
break;
case 2: insert();
break;
case 3: delete();
break;
case 4: display();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void create()
{
node *temp;
char ch=’y’;
temp=first;
do
{
printf(“enter the data for the new node\n”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
if(first= =NULL)
{
first=new;
temp=new;
new->link=first;
}
else
145
{
temp->link=new;
new->link=first;
temp=new;
}
printf(“do you want to create another node(y/n)”);
ch=getchar();
}while(ch!=’n’);
}
void insert()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: insertbeg 2: insertmid 3: insertend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: insertbeg();
break;
case 2: insertmid();
break;
case 3: insertend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void insertbeg()
{
node *temp;
printf(“ enter data for node to be added in the beginning”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
if(first= = NULL)
{first =new;
new->link=first;
}
else
{
temp=first;
146
while(temp->link!=first)
temp=temp->link;
temp->link=new;
new->link=first;
first=new;
}
}
void insertmid()
{
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to insert a node”);
scanf(“%d”,&pos);
printf(“ enter data for node to be added at the position %d”,pos);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(i<pos)
{
temp=temp->link;
i++;
}
new->link=temp->link;
temp->link=new;
}
}
void insertend()
{
node *temp;
temp=first;
printf(“ enter data for node to be added at end”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(temp->link!=first)
{
temp=temp->link;
}
temp->link=new;
new->link=first;
}
void delete()
{
char ch=’y’;
147
int c;
while(ch= = ‘y’)
{
printf(“ 1: delbeg 2: delmid 3: delend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: delbeg();
break;
case 2: delmid();
break;
case 3: delend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void delbeg()
{
node *temp;
if(first= = NULL)
{printf(deletion not possible “);
exit();
}
else
{
temp=first;
while(temp->link!=first)
temp=temp->link;
temp->link=first->link;
first=first->link;
}
}
void delmid()
{
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to delete a node”);
scanf(“%d”,&pos);
while(i<pos)
{
148
temp=temp->link;
i++;
}
temp->link=temp->link->link;
void delend()
{
node *temp;
temp=first;
while(temp->link->link==first)
{
temp=temp->link;
}
temp->link=first;
}
void display()
{
node * temp;
if (first= =NULL)
{
printf(“linked list is empty”);
exit();
}
else
{
printf(“the contents of circularly single linked list are :\n”);
temp=first;
do
{
printf(“%3d”,temp->data);
temp=temp->link;
}while(temp!=first);
}
149
PROBLEM 117:- Write a program to implement a doubly linked list.
PROCEDURE:-
1.CREATE()
a) set FIRSTNODE to NULL and TEMPNODE to FIRSTNODE
b) create NEWNODE if FIRSTNODE=NULL then FIRSTNODE=NEWNODE and
TEMPNODE=NEWNODE and LLINK[NEWNODE]=NULL
c) else set RLINK[TEMPNODE]=NEWNODE and LLINK[NEWNODE]=TEMPNODE
d) set TEMPNODE=NEWNODE
e) to create another node goto step b
f) set RLINK[NEWNODE]=NULL
2. INSERTBEG()
a) create a NEWNODE
b) set RLINK[NEWNODE]=FIRST and LLINK[NEWNODE]=NULL
c) FIRST=NEWNODE
3. INSERTEND()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the last node using TEMP=RLINK[TEMP]
d) set RLINK[TEMP]=NEWNODE and LLINK[NEWNODE]=TEMP and
RLINK[NEWNODE]=NULL
4. INSERTPOS()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the position required using TEMP=RLINK[TEMP]
d) set LLINK[ RLINK [TEMP]=NEWNODE
set RLINK[NEWNODE]=RLINK[TEMP]
set RLINK[TEMP]=NEWNODE;
set LLINK[NEWNODE]=TEMP
5. DELETEBEG()
a) FIRST= RLINK[FIRST]
b)LLINK[FIRST]=NULL
3. DELETEEND()
a) set TEMP=FIRST
b) traverse till the last but one node using TEMP=RLINK[TEMP]
c) set RLINK[TEMP]=NULL
4. DELETEPOS()
a) set TEMP=FIRST
b) traverse till the position required using TEMP=LINK[TEMP]
c) set LLINK[RLINK[RLINK[TEMP]=TEMP
set RLINK[TEMP]=RLINK[RLINK[TEMP]]
CODE:-
#include<stdio.h>
#include<alloc.h>
struct dll
150
{
struct dll *llink
int data;
struct dll *rlink;
};
typedef struct dll node;
node *first=NULL,*new;
void create(), insertbeg(), insertmid(), insertend();
void delbeg(), delmid(),delend();
void display();
void main()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: create 2: insert 3: delete 4: display 5: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: create();
break;
case 2: insert();
break;
case 3: delete();
break;
case 4: display();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void create()
{
node *temp;
char ch=’y’;
temp=first;
do
{
printf(“enter the data for the new node\n”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
if(first= =NULL)
151
{
first=new;
temp=new;
new->llink=NULL;
new->rlink=NULL;
}
else
{
temp->rlink=new;
new->llink=temp;
new->rlink=NULL;
temp=new;
}
printf(“do you want to create another node(y/n)”);
ch=getchar();
}while(ch!=’n’);
}
void insert()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: insertbeg 2: insertmid 3: insertend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: insertbeg();
break;
case 2: insertmid();
break;
case 3: insertend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void insertbeg()
{
printf(“ enter data for node to be added in the beginning”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
152
if(first= = NULL)
{first =new;
new->llink=NULL;
new->rlink=NULL;
}
else
{
new->rlink=first;
first->llink=new;
new->llink=NULL;
first=new;
}
}
void insertmid()
{
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to insert a node”);
scanf(“%d”,&pos);
printf(“ enter data for node to be added at the position %d”,pos);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(i<pos)
{
temp=temp->rlink;
i++;
}
temp->rlink->llink=new
new->rlink=temp->rlink;
temp->rlink=new;
new->llink=temp;
}
}
void insertend()
{
node *temp;
temp=first;
printf(“ enter data for node to be added at end”);
new=(node*)malloc(sizeof(node));
scanf(“%d”,&new->data);
while(temp->rlink!=NULL)
{
153
temp=temp->rlink;
}
temp->rlink=new;
new->llink=temp;
new->rlink=NULL;
}
void delete()
{
char ch=’y’;
int c;
while(ch= = ‘y’)
{
printf(“ 1: delbeg 2: delmid 3: delend 4: exit\n”);
printf(“enter your option”);
scanf(“%d”,&c);
switch(c )
{
case 1: delbeg();
break;
case 2: delmid();
break;
case 3: delend();
}
printf(“do you want to continue(y/n)”);
ch=getchar();
}
}
void delbeg()
{
node *temp;
if(first= = NULL)
{printf(deletion not possible “);
exit();
}
else
{
first=first->rlink;
first->llink=NULL;
}
}
void delmid()
{
154
int pos,i=1;
node *temp;
temp=first;
printf(“enter the position to delete a node”);
scanf(“%d”,&pos);
while(i<pos)
{
temp=temp->rlink;
i++;
}
temp->rlink->rlink->llink=temp;
temp->rlink=temp->rlink->rlink;
void delend()
{
node *temp;
temp=first;
while(temp->rlink->rlink!=NULL)
{
temp=temp->rlink;
}
temp->rlink->llink=NULL;
temp->rlink=NULL;
}
void display()
{
node * temp;
if (first= =NULL)
{
printf(“linked list is empty”);
exit();
}
else
{
printf(“the contents of doubly linked list are :\n”);
temp=first;
while(temp->rlink!=NULL)
{
printf(“%3d”,temp->data);
temp=temp->rlink;
} }
155
PROBLEM 118: Implement circular doubly linked list
PROCEDURE:-
1.CREATE()
a) set FIRSTNODE to NULL and TEMPNODE to FIRSTNODE
b) create NEWNODE if FIRSTNODE=NULL then FIRSTNODE=NEWNODE and
TEMPNODE=NEWNODE and LLINK[NEWNODE]=FIRST and RLINK[FIRST]=FIRST
c) else set RLINK[TEMPNODE]=NEWNODE and LLINK[NEWNODE]=TEMPNODE
d) set TEMPNODE=NEWNODE
e) to create another node goto step b
f) set RLINK[NEWNODE]=FIRST
2. INSERTBEG()
a) create a NEWNODE
b) set TEMP=FIRST traverse till the end of list using TEMP=RLINK[TEMP]
set RLINK[NEWNODE]=FIRST and LLINK[NEWNODE]=TEMP,
RLINK[TEMP]=NEWNODE
c) FIRST=NEWNODE
3. INSERTEND()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the last node using TEMP=RLINK[TEMP]
d) set RLINK[TEMP]=NEWNODE and LLINK[NEWNODE]=TEMP and
RLINK[NEWNODE]=FIRST
4. INSERTPOS()
a) create a NEWNODE
b) set TEMP=FIRST
c) traverse till the position required using TEMP=RLINK[TEMP]
d) set LLINK[ RLINK [TEMP]=NEWNODE
set RLINK[NEWNODE]=RLINK[TEMP]
set RLINK[TEMP]=NEWNODE;
set LLINK[NEWNODE]=TEMP
5. DELETEBEG()
a) set TEMP=FIRST traverse till the last node using TEMP=RLINK[TEMP]
set RLINK[TEMP]=RLINK[FIRST]
set FIRST=RLINK[FIRST]
b)LLINK[FIRST]=FIRST
6. DELETEEND()
a) set TEMP=FIRST
b) traverse till the last but one node using TEMP=RLINK[TEMP]
c) set RLINK[TEMP]=FIRST, set LLINK[FIRST]=TEMP
7. DELETEPOS()
a) set TEMP=FIRST
b) traverse till the position required using TEMP=LINK[TEMP]
c) set LLINK[RLINK[RLINK[TEMP]=TEMP
set RLINK[TEMP]=RLINK[RLINK[TEMP]]
156
CODE:-
#include<stdio.h>
struct abc
{
int a;
struct abc *p;
};
typedef struct abc node;
node *f=NULL,*t,*n;
void main()
{
int c;
void add(),addbeg(),addany(),del(),delbeg(),delany();
void display();
do
{
clrscr();
printf(“1) add node \n 2) add node at beginning \n 3) add node at desired position\n 4) delete
node\n 5) delete node at beginning\n 6)delete node at desired position\n 7) display\n 8) exit\n”);
scanf(“%d”,&i);
switch©
{
case 1:add();
break;
case 2:addbeg();
break;
case 3:addany();
break;
case 4:del();
break;
case 5:delbeg();
break;
case 6:delany();
break;
case 7:display();
break;
}
}while(c!=8);
}
vios add()
{
if(f==NULL)
157
{
f=(node *)malloc(sizeof(node));
printf(“enter value:”);
scanf(“%d”,&f->a);
f->lp=->lp=f;
}
else
{
n=(node *)malloc(sizeof(node));
printf(“Enter value:”);
scanf(“%d”,&n->a);
n->rp=f;
for(t=f;t->rp!=f;t=t->rp);
t->rp=n;
n->lp=t;
f->lp=n;
}
}
void addbeg()
{
n=(node *)malloc(sizeof(node));
printf(“Enter number:”);
scanf(“%d”,&n->a);
n->rp=f;
for(t=f;t->rp=f;t=t->rp);
t->rp=n;
n->lp=t;
f=n;
f->lp=n;
}
void addany()
{
int x.i;
printf(“Enter position”);
scanf(“%d”,&x);
n=(node *)malloc(sizeof(node));
printf(“Enter number”);
scanf(%d”,&n->a);
for(i=1,t=f;i<x-1;i++,t=t->rp);
n->rp=t->rp;
n->lp=t;
t->rp->lp=n;
t->rp=n;
}
158
void del()
{
for(t=f;t->rp->rp!=f;t=t->rp);
n=t->rp);
t->rp=f;
f->lp=t;
}
void delbeg()
{
n=f;
for(t=f;t->rp!=f;t=t->rp);
f=f->rp;
t->rp=f;
f->lp=t;
free(n);
}
void delany()
{
int I,x;
printf(“Enter position;
scanf(“%d”,&x);
for(i=1,t=f;i<x-1;i++,t=t->rp);
n=t->rp;
t->rp=t->rp->lp;
t->rp->lp=t;
free(n);
}
void display()
{
t=f;
do
{
printf(“%d”,t->a);
t=t->rp;
}
while(t!=f);
getvh();
}
159
PROBLEM 119:- Implement Polynomial subtraction using singly linked list
PROCEDURE:-
1.enter two polynomials in terms of two linked lists P1 P2
2. repeat steps 3 to 5 while P1!=NULL
3. take power field of the node and start comparing with power fields in P2 until
P2!=NULL
4.if power fields are equal find difference of corresponding coeffiecients and
place the result in third linked list
5. set P1=LINK[P1]
CODE:-
Struct poly
{
int coeff,power;
struct poly *link;
}*p1,*p2,*p3,*prev,*temp,*first;
void create(int n)
{
int i=1;
first=(struct poly*)malloc(sizeod(struct poly));
printf(“\n Enter coeff & power:”);
scanf(“%d%d”,&first->coeff,&first->pow);
first->link-NULL;
prev=first;
p1=first;
while(i<n)
{
temp=struct poly *)malloc(sizeof(sizeof(struct poly));
scanf(:%d%d”,&temp->coeff,&temp->pow);
prev->link=temp;
prev=prev->link;
i++;
}
prev->link=NULL;
}
main()
{
int n1,n2,x;
printf(“Enter no. of item of poly 1:”);
scanf(“%d”,&n1);
printf(“Enter no. of item of poly 2:”);
scanf(“%d”,&n2);
crete(p1);
p1=first;
160
create(p2);
temp=(struct poly *)malloc(sizeod(struct poly));
p3=temp;
prev=temp;
while(p1!=NULL && p2!=NULL)
{
temp=(struct poly *)malloc(sizeof(struct poly));
if(p1->pow > p2->pow)
{
temp->pow=p1->pow;
temp->coeff = p1->coeff;
p1=p1->link;
}
else if (p2->pow > p1->pow)
{
temp->pow – p2->pow;
temp->coef = p2->coef;p2=p2->link;
}
else
{
x=p1->coeff-p2->coeff;
if(x!=0)
{
temp->ceoff=x;
temp->pow=p1->pow;
}
p1=p1->link;
p2=p2->link;
}
prev->link=temp;
prev=prev->link;
}
if(p1!=NULL)
{
while(p1!=NULL)
{
temp-struct poly *)malloc(sizeof(sturct poly));
temp->coef=p1->coef;
temp->pow=p1->pow;
p1=p1->link;
prev->link=temp;
prev->link;
prev=prev->link;
}
}
else if(p2!=NULL)
161
{
while(p2!=NULL)
{
temp=struct poly *)malloc(sizeof(struct poly));
temp->coef=p2->coef;
temp->pow=p2->pow;
p2=p2->link;
prev->link=temp;
prev=prev->link;
}
}
prev->link-NULL;
temp=p3;
p3=p3->link;
free(temp);
temp=p3;
printf(“:poly after subtraction is \n”);
while(temp!-NULL)
{
printf(“%3d * %d”,temp->coeff,temp->pow);
temp=temp->link;
}
getch();
}
162
PROGRAMS ON TREES & GRAPHS
INORD(INFO,LEFT,RIGHT,ROOT)
163
4. Repeat Steps 5 to 7 while PTR ≠ NULL:[Backtracking.]
5. Apply Process to INFO[PTR].
6. [Right child?] If RIGHT[PTR] ≠ NULL, then:
(a) Set PTR:= RIGHT[PTR].
(b) Goto Step 3.
[End of If structure.]
7. Set PTR:=STACK[TOP] and TOP:=TOP-1 {Pops node.]
[End of Step 4 loop]
8. Exit.
POSTORD(INFO,LEFT,RIGHT,ROOT)
164
CODE:-
#include<stdio.h>
#include<alloc.h>
struct tree
{
char data;
struct tree *left;
struct tree *right;
}
typedef struct tree btree;
btree *root,*stack[100];
int top=0;
void rec();
void withoutrec();
void traversal();
void postorder();
void inorder();
void preorder();
void recpostorder();
void recinorder();
void recpreorder();
void push(btree *x)
{
stack[++top]=x;
}
btree *pop()
{
return(stack[top--]);
}
void create()
{
btree *p,*temp;
char ans;
stack[top]=NULL;
root=(btree *)malloc(sizeof(btree));
printf(“enter data for root node”);
scanf(“%c”,&root->data);
p=root;
while(p)
{
printf(“do u want to create a right child for node %c(y/n):”,p->data);
scanf(“%c”,&ans);
if(toupper(ans)= =’n’)
p->right=NULL;
165
else
{
temp=(btree *)malloc(sizeof(btree));
printf(“enter data for the node”);
scanf(“%c”,&temp->data);
p->right=temp;
push(temp);
}
printf(“do u want to create a left child for the node %c(y/n):”,p->data);
scanf(“%c”,&ans);
if(toupper(ans)= =’N’)
{
p->left=NULL;
p=pop();
}
else
{
temp=(btree *)malloc(sizeof(btree));
printf(“enter data for the node”);
scanf(“%c”,&temp->data);
p->left=temp;
p=p->left;
}
}
}
int menu()
{
int c;
printf(“MAIN MENU\n”);
printf(“1:create btree\n 2: traversal \n 3:exit\n enter ur choice\n”);
scanf(“%d”,&c);
return( c);
}
void recinorder(btree *r)
{
if(r!=NULL)
{
recinorder(r->left);
printf(“%c”,r->data);
recinorder(r->right);
}
}
166
{
printf(“%c”,r->data);
recpreorder(r->left);
recpreorder(r->right);
}
}
void recpostorder(btree *r)
{
if(r!=NULL)
{
recpostorder(r->left);
recpostorder(r->right);
printf(“%c”,r->data);
}
}
void preorder()
{
btree *t;
t=root;
top=0;
stack[top]=NULL;
printf(“the preorder form is:\n”);
while(t!=NULL)
{
printf(“%c”,t->data);
if(t->right!=NULL)
push(t->right);
if(t->left!=NULL)
t=t->left;
else
t=pop();
}
}
void inorder()
{
btree *t;
t=root;
printf(“the inorder form is :\n”);
top=0;
stack[top]=NULL;
a:
while(t!=NULL)
{
push(t);
t=t->left;
167
}
t=pop();
while(t!=NULL)
{
printf(“%c”,t->data);
if(t->right!=NULL)
{
t=t->right;
goto a;
}
t=pop();
}
}
void postorder()
{
btree *p,*temp;
printf(“the postorder form\n”);
top=0;
temp=NULL;
p=root;
while(p->left!=NULL)
{
push(p);
p=p->left;
}
while(p!=NULL)
{
if((p->right = = NULL) || (p->right= =temp))
{
printf(“%c”,p->data);
temp=p;
p=pop();
}
else
{
push(p);
p=p->right;
while(p->left!=NULL)
{
push(p);
p=p->left;
}
}
}
}
168
void main()
{
int ch,n;
top=0;
while(1)
{
ch=menu();
switch(ch)
{
case 1: create(); break;
case 2: traversal(); break;
case 3: exit(0;
}
}
}
void traversal()
{
int x;
printf(“1: with recursion\n 2: without recursion\n);
scanf(“%d”,&x);
switch(x)
{
case 1: rec(); break;
case 2: withoutrec(); break;
}
}
void rec()
{
while(1)
{
int x;
printf(“1: inorder 2: preorder 3: postorder\n enter ur choice”);
scanf(“%d”,&x);
switch(x)
{
case 1: recinorder(root); break;
case 2: recpreorder(root); break;
case 3: recpostorder(root); break;
case 4: return;
}
}
169
}
void withoutrec()
{
while(1)
{
int x;
printf(“1: inorder 2: preorder 3: postorder\n enter ur choice”);
scanf(“%d”,&x);
switch(x)
{
case 1: inorder(); break;
case 2: preorder(); break;
case 3: postorder(); break;
case 4: return;
}
}
}
170
PROBLEM 121:- Write a program to create and traverse a binary search tree in
a) Preorder.
b) Inorder.
c) Postorder.
d) Counting leaf nodes
e) Counting non leaf nodes
f) Counting total nodes
INORD(INFO,LEFT,RIGHT,ROOT)
171
3. Set PTR:=STACK[TOP] and TOP:=TOP-1.[Pops node from STACK.]
4. Repeat Steps 5 to 7 while PTR ≠ NULL:[Backtracking.]
5. Apply Process to INFO[PTR].
6. [Right child?] If RIGHT[PTR] ≠ NULL, then:
(a) Set PTR:= RIGHT[PTR].
(b) Goto Step 3.
[End of If structure.]
7. Set PTR:=STACK[TOP] and TOP:=TOP-1 {Pops node.]
[End of Step 4 loop]
8. Exit.
POSTORD(INFO,LEFT,RIGHT,ROOT)
172
2. or if left link is not NULL and right link is NULL
3. or if left link is not NULL and as well as right link is not NULL then in
4. all these cases increase the non leaf nodes count by one
PROCEDURE TO COUNT NO. OF NODES:-
1. no. of nodes=no.of leaf nodes+no.of non leaf nodes
CODE:-
#include<stdio.h>
#include<alloc.h>
struct tree
{
char data;
struct tree *left;
struct tree *right;
}
typedef struct tree btree;
btree *root,*stack[100];
int top=0;
btree * insert(int, btree *);
void countnode();
void rec();
void withoutrec();
void traversal();
void postorder();
void inorder();
void preorder();
void recpostorder();
void recinorder();
void recpreorder();
void push(btree *x)
{
stack[++top]=x;
}
btree *pop()
{
return(stack[top--]);
}
173
return(p);
}
if(data<p->data)
p->left=insert(data,p->left);
elseif if(data>p->data) p->right=insert(data,p->right);
else printf(“duplicate value not allowed”);
return(p);
}
int menu()
{
int c;
printf(“MAIN MENU\n”);
printf(“1:create btree\n 2: traversal \n 3:exit\n enter ur choice\n”);
scanf(“%d”,&c);
return( c);
}
void countnode()
{
btree *t;
int count=0;
t=root;
top=0;
while(top>=0)
{
if(t!=NULL)
{
if((t->left= =NULL) && (t->right= =NULL))
lnode++;
count++;
if(t->right!=NULL)
push(t->right);
t=t->left;
}
else
t=pop();
}
printf(“the total no. of nodes =%d\n”,count);
printf(“the count of leaf nodes is %d\n”,lnode);
printf(“the no. of interior nodes is %d”,count-lnode-1);
}
void recinorder(btree *r)
{
if(r!=NULL)
{
recinorder(r->left);
printf(“%c”,r->data);
174
recinorder(r->right);
}
}
void inorder()
{
btree *t;
t=root;
printf(“the inorder form is :\n”);
175
top=0;
stack[top]=NULL;
a:
while(t!=NULL)
{
push(t);
t=t->left;
}
t=pop();
while(t!=NULL)
{
printf(“%c”,t->data);
if(t->right!=NULL)
{
t=t->right;
goto a;
}
t=pop();
}
}
void postorder()
{
btree *p,*temp;
printf(“the postorder form\n”);
top=0;
temp=NULL;
p=root;
while(p->left!=NULL)
{
push(p);
p=p->left;
}
while(p!=NULL)
{
if((p->right = = NULL) || (p->right= =temp))
{
printf(“%c”,p->data);
temp=p;
p=pop();
}
else
{
push(p);
p=p->right;
while(p->left!=NULL)
176
{
push(p);
p=p->left;
}
}
}
}
void main()
{
int ch,n;
char c=’y’;
top=0;
while(1)
{
ch=menu();
switch(ch)
{
case 1: root=NULL;
while(c= =’y’)
{
printf(“enter data”);
scanf(“%d”,&n);
root=insert(a,root);
printf(“enter choice (y/n):”);
scanf(“%c”,&c);
} break;
case 2: traversal(); break;
case 3: exit(0;
}
}
}
void traversal()
{
int x;
printf(“1: with recursion\n 2: without recursion\n);
scanf(“%d”,&x);
switch(x)
{
case 1: rec(); break;
case 2: withoutrec(); break;
}
}
177
void rec()
{
while(1)
{
int x;
printf(“1: inorder 2: preorder 3: postorder\n enter ur choice”);
scanf(“%d”,&x);
switch(x)
{
case 1: recinorder(root); break;
case 2: recpreorder(root); break;
case 3: recpostorder(root); break;
case 4: return;
} }}
void withoutrec()
{
while(1)
{
int x;
printf(“1: inorder 2: preorder 3: postorder\n enter ur choice”);
scanf(“%d”,&x);
switch(x)
{
case 1: inorder(); break;
case 2: preorder(); break;
case 3: postorder(); break;
case 4: return;
}
}
}
178
PROBLEM 122:- DFS (Graph Traversal using stacks)
PROCEDURE:-
1. Initialize all nodes to the ready state (STATUS=1)
2. Push the starting node A onto STACK and change its status to the waiting state
(STATUS=2).
3. Repeat steps 4 and 5 until STACK is empty.
4. Pop the top node N of STACK. Process N and change its status to the processed
state (STATUS=3)
5. Push onto STACK all the neighbors of N that are still in the ready state
(STATUS=1),
and change their status to the waiting state (STATUS=2).
6. Exit.
CODE:-
#include<stdio.h>
char stack[10];
int top=-1;
char pop();
void push(char x);
void main()
{
int a[10][10],m,n;
int i,j,state[10];
char g[10],x;
printf(“enter the no. of nodes of graph”);
scanf(“%d”,&n);
printf(“enter the nodes of the graph”);
for(i=1;i<=n;i++)
g[i]=getchar();
printf(“enter the adjacency matrix of the graph”);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&a[i][j]);
for(i=1;i<=n;i++)
state[i]=1;
state[1]=2;
push(g[1]);
while(top!=-1)
{
x=pop();
for(i=1;i<=n;i++)
if(x= =g[i])
break;
state[i]=3;
179
printf(“%c”,g[i]);
for(j=1;j<=n;j++)
{
if((a[i][j]= =1) && (state[j] = =1))
{
state[j]=2;
push(g[j]);
}
}
}
}
void push(char x)
{
top++;
stack[top]=x;
}
char pop()
{
return(stack[top--]);
}
180
PROBLEM 123:- BFS (Graph Traversal using queues)
PROCEDURE:-
1. Initialize all nodes to the ready state (STATUS=1)
2. put the starting node A in QUEUE and change its status to the waiting state
(STATUS=2)
3. Repeat steps 4 and 5 until QUEUE is empty:
4. Remove the front node N of QUEUE. Process N and change the status of N
to the processed state (STATUS=3)
5. Add to the rear of QUEUE all the neighbors of N that are in the steady state
(STATUS=1)
and change their status to the waiting state (STATUS=2).
6. Exit.
CODE:-
#include<stdio.h>
char queue[10];
int front=0,rear=-1;
char delete();
void insert(char x);
void main()
{
int a[10][10],m,n;
int i,j,state[10];
char g[10],x;
printf(“enter the no. of nodes of graph”);
scanf(“%d”,&n);
printf(“enter the nodes of the graph”);
for(i=1;i<=n;i++)
g[i]=getchar();
printf(“enter the adjacency matrix of the graph”);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf(“%d”,&a[i][j]);
for(i=1;i<=n;i++)
state[i]=1;
state[1]=2;
insert(g[1]);
while(front<=rear)
{
x=delete();
for(i=1;i<=n;i++)
if(x= =g[i])
break;
state[i]=3;
printf(“%c”,g[i]);
for(j=1;j<=n;j++)
181
{
if((a[i][j]= =1) && (state[j] = =1))
{
state[j]=2;
insert(g[j]);
}
}
}
}
void insert(char x)
{
queue[++rear]=x;
}
char delete()
{
return(queue[front++]);
}
182
PROGRAMS ON SEARCHING & SORTING
CODE:-
#include<stdio.h>
void main()
{
int i,b,a[100],flag,n;
clrscr();
printf(“Entern:”);
scanf(“%d”,&n);
printf(“”Enter %d elements:”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the number to be searched”);
scanf(“%d”,&b);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
flag=1;
break;
}
else
flag=0;
}
if(flag==1)
printf(“The given element %d ois found in %d th position”,b,i+1);
else
no. is not found);
getch();
}
183
PROBLEM 125:- Write a program to perform binary search
PROCEDURE:-
1. enter n value
2. read n values into the array a[].
3. sort the array elements.
4. enter the element x which we want to seach
5. assign flag=0,low=0 and high =n-1;
6. while ( low<=high) repeat the process
7. find mid value of an array
mid=(low+high)/2.
8. if (a[mid])>x)
high=mid-1;
9. else if (a[mid]<x)
low=mid+1;
10 else
print “ element found”.
Flag =1;
11. if (flag==0)
print” element is not found”;
12. exit.
CODE:-
#include<stdio.h>
int a[50],I,x,n,z;
void main()
{
clrscr();
prinf(“Enter n:”);
scanf(“%d”,&n);
printf(“Enter %d elements:”,n);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
printf(“Enter element to be seached:”);
scanf(“%d”,&n);
z=bs();
if(z>0)
printf(“The element os found at %dth position”,z);
else
printf(“Element is not found”);
getch();
}
int bs()
{
int mid,lb=1,ub=n;
while(lb<=ub)
184
{
mid=(lb+ub)/2;
if(x<a[mid])
ub=mid-1;
else if(x>a[mid])
lb=mid+1;
else
terurn mid;
}
return(-1);
}
185
PROBLEM 126:- Write a program to sort data using bubble sort.
PROCEDURE:-
BUBBLE(DATA,N)
Here DATA is an array with N elements. This algorithm sorts the elements in DATA
1. Repeat steps 2 and 3 for k=1 to n-1
2. set PTR:=1
3. Repeat while PTR<=n-k
(a) if DATA[PTR]> DATA[PTR+1], then
interchange DATA[PTR] and DATA[PTR+1]
(b) set PTR:= PTR+1.
4. Exit.
CODE:-
#include<stdio.h>
void main()
{
int I,n,j,a[50],t;
clrscr();
prinf(“Enter how many no’s”);
scanf(“%d”,&n);
printf(“Enter the no’s:\n”);
for(i-1;i<=n;i++0
scanf(“%d”,&a[i]);
for (i=1;i<=n-1;i++)
{
for(j=1;j<=n;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
printf(“pass %d-“,i);
for(j=1;j<=n;j++)
printf(“%d”,j[a]);
printf(“\n”,);
}
getch();
}
186
PROBLEM 127:- Write a program to sort data using selection sort.
PROCEDURE:-
Min(a,k,n,loc)
1. set min=a[k] and loc=k
2. Repeat for j =k+1 …….n
if min>a[j], then set min=a[j] and loc=a[j] and loc=j
3. return.
Selection(a,n)
1. repeat steps 2 and 3 for k=1,2…..n-1
2. call min(a,k,n,loc)
3. set temp=a[k], a[k]=a[loc], a[loc]=temp
4. Exit.
CODE:-
Void main()
{
int I,n,j,a[50],k,f,min;
clrscr();
printf(“Enter hoe many no’s”);
scanf(%d”,&n);
printf(“Enter the no’s:\n”);
for(i=1;i<-n;i++)
scanf(“%d”,&i[a]);
for(i-1;i<=n-1;i++)
{
min=a[i];
for(j=i+1;j<=n;j++0
if(min>a[j])
{
min=a[j];
k=j;
}
if(a[i]!=min)
{
a[k]=a[i];
a[i]=min;
}
printf(“pass %d-“,i);
for(j=1;j<=n;j++)
printf(:%d”,j[a]);
printf(“\n”);
}getch();}
187
PROBLEM 128:- Write a program to sort data using insertion sort.
PROCEDURE:-
insertion (a,n)
1. set a[0]=-9999.
2. Repeat steps 3 t 5 for k=2,3….n;
3. set temp=a[k] and ptr=k-1;
4. repeat while temp<a[ptr]
(a) set a[ptr+1]=a[ptr]
(b) set ptr=ptr-1.
5. set a[ptr+1]=temp.
6. return.
CODE:-
#include<stdio.h>
int i,j,l,in[20];
void insertionsort();
void main()
{
clrscr();
printf(“Enter the no. of numbers U want to enter :”);
scanf(“%d”,&l);
printf(“\n Enter %d n’s:”,l);
for(i=1;i<l;i++)
scanf(“%d”,&in[i]);
printf(“\n sorted lis is :”);
insertionsort();
for(i=1;i<=l;i++)
printf(“%5d”,in[i]);
gerch();
}
void insertionsort()
{
int t,pass-1,k,ptr;
in[0]=-100;
for(i=2,i<=l;i++)
temp=in[i];
ptr=i-1;
while(temp<in[ptr])
{
in[ptr+1]=in[ptr];
ptr=ptr-1;
188
in[ptr+1]=temp;
printf(“\n pass %d:”,pass+1);
for(k=1;k<=l;k++)
printf(:%6d”,in[k]);
}
}
189
PROBLEM 129:- Program to sort data using quick sort.
PROCEDURE:-
quick (a,n,beg,end,loc)
Here a is an array with n elements. Parameters beg and end contain the boundary values of the
sublist of a to which this procedure applies. Loc keeps track of the position of the first element
a[beg] of the sublist during the procedure. The local variables left and right will contain the
boundary fvalues of the list of elements that have not been scanned.
1. set left=beg, right =end and loc=beg
2.
(a) repeat while a[loc]<=a[right] and loc!=right
right=right-1.
(b) if loc=right then return
(c ) if a[loc]>a[right] , then
(i) interchange a[loc] and a[right]
(ii) set loc=right
(iii) go to step 3.
3. (a) repeat while a[left]<=a[loc] and left!=loc;
left=left+1;
(b) if loc=left then return;
(c ) if a[left]>a[loc], then
(i) interchange a[left] and a[loc]
(ii) set loc=left
(iii) go to step 2.
1. top=null;
2. if n>1, then top =top+1, lower[1]=1, upper[1]=n
3. repeat steps 4 to 7 while top!=null
4. set beg=lower[top], end=upper[top]
top=top-1;
5. call quick(a,n,beg,end,loc)
6. if beg<loc-1 then
top=top+1, lower[top]=beg, upeer[top]=loc-1
7. if loc+1<end, then
top=top+1, lower[top]=loc+1, upper[top]=end.
8. exit.
CODE:-
#include<stdio.h>
int a[20],l;
void quicksort(int m,int p)
{
int i,j,x,t,k;
static int pass=1;
190
i=m;j=p;
x=a[(m+p)/2];
do
{
while((a[i]<x) && (i<p))
i++;
while((x<a[j] && (j<m))
j--;
if(i<=j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
i++;
j--;
}
}while(i<=j);
printf(“\n pass %d:”,pass);
for(k=0;k<l;k++)
printf(“%d \t”,a[k]);
pass++;
printf(“\n”);
if(m<j)
quicksot(m,j);
if(i<p)
quicksort(i,p);
}
void main()
{
int I,j,m,n,low high;
char k;
clrscr();
printf(“\n Enter the no of elements:”);
scanf(“%d”,&l);
printf(“Enter theelements”);
for(i=0;i<l;i++)
scanf(“%d”,&a[i]);
low-0;
high=l-1;
printf(“\n sorting is done as follows:”);
quicksort(low,high);
printf(“\n sorted list is : \n);
for(i-0;i<l;i++)
printf(“%d”,i++)
printf(“%d”\t”,a[i]); getch();}
191
PROBLEM 130:- Write a program to sort data using heap sort.
PROCEDURE:-
INHEAP(tree, n, item)
a heap h with n elements is stored in the array tree, and an item of information is given. This
procedure inserts item as a new element of h. ptr gives the location of item as it rises in the tree,
and par denotes the location of the parent of item.
DELHEAP(tree, n, item)
A heap h with n elements is stored in the array tree. This procedure assigns the root tree[1] of h
to the variable item and then reheaps the remaining elements. The variable last saves the value of
the original last node of h. The pointers ptr, left and right give the locations of last and its left
and right children as last sinks in the tree.
1. set item=tree[1]
2. set last=tree[n] and n=n-1.
3. set ptr=1, left=2 and right=3
4. repeat steps 5 to 7 while right<=n;
5. if last>= tree[left] and last>=tree[right], then
set tree[ptr]=last and return.
6. if tree[right]<=tree[left], then
set tree[ptr]=tree[left] and ptr=left
else
set tree[ptr]=tree[right] and ptr=right
7. set left=2*ptr and right=left+1
8. if left=n and if last<tree[left], then set ptr=left
9. set tree[ptr]=last
10. return
CODE:-
#include<stdio.h>
#include<conio.h>
int a[50],l;
int s,f,i,i1,k1=0,elt;
192
void sort(int);
void crheap(int n1) {
for(i=1;i<n1;i++) {
elt=a[i];
s=I;
f=(s-1)/2;
while(s>0 && a[f]<elt) {
a[s]=a[f];
s=f;
f=(s-1)/2i;
}
a[s]=elt;
} }
void sort(int n1) {
crheap(n1);
for(i=n1-1;i>o;i--) {
elt =a[i];
a[i]=a[0];
f=0;
if(i= =1)
s=-1;
else s=1;
if((i>z) && (a[z]>a[i]))
s=z;
while(s>=0 && elt<a[s]) {
a[f] = a[s];
f=s;
s=z*f+1;
if((s+1)<=i-1) && (a[s]<a[s+1]))
s=s+1;
if(s>i-1)
s=-1;
}
a[f]=elt;
k1++;
printf(“\n PASS %d”,k1);
for(i1=1,i1<=n;i1++)
printf(“%d”, a[i]);
}}
void main()
{
int I,t;
clrscr();
printf(“HEAP SORT”);
printf(“enter the no of elements”);
scanf(“%d”, &l;
193
printf(“Enter the elements”);
for(i=0;i<l;i++)
scanf(“%d”,&a[i]);
printf(sorted ls done as follws”);
sort(l);
[romtf(“sorted list is”);
for(i=0;i<l;i++)
printf(“%d”,a[i]);
getch();
}
194