Sei sulla pagina 1di 194

PROBLEM 1: To find volume of a cylinder: l*b*h

PROCEDURE:-

1: input values for length,breadth,height


2: find the product (length*breadth*height)
3:print the above result

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);
}

Input:- enter values for length, breadth,height of cylinder


A = 5, B=5, C=5

Ouput:- volume of cylinder is 125

1
PROBLEM 2: To find area of triangle : sqrt(s*(s-a)*(s-b)*(s-c))

PROCEDURE:-

1.Input values for three sides of triangle


2.find s value with the formulae (a+b+c)/2
3.find area with the formulae sqrt(s(s-a)(s-b)(s-c))
4.print the above result

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);
}

Input :- enter values for three sides of triangle


a=2, b=2, c=2

Output:- area of triangle with sides a=2, b=2, c=2 is 1.732

2
PROBLEM 3: Convert Celcious temperature to Farenheit.

PROCEDURE:-

1. input value for celcious


2. find farenheit value with the formulae (9/5)c+32
3. print the above result

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);
}

Input:- enter a value in celcious


35

Output:- temperature in farenheit is 95.0000

3
PROBLEM 4: Calculate Simple Interest using (p*t*r)/100.

PROCEDURE:-

1. input values for principal amount, time,rate of interest


2. find simple interest with the formulae (p*t*r)/100
3. print the above result

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);
}

Input: - enter values p,t,r


P=10000, t=10, r=3

Output:- Simple interest is =Rs.3000

4
PROBLEM 5:-Find Value of S=ut+1/2*a*t**2.

PROCEDURE:-

1.enter values for u,a,t to find distance


2.find distance with the formulae ut+1/2at2
3.print the above result

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);
}

Input:- enter values u,t,a


U=10,t=4,a=4.9

Output:- S =79.200

5
PROBLEM 6:- Find Sum to first n numbers (using goto).

PROCEDURE:-

1. input value for n


2. set initial values for sum as 0 and I as 1
3. add I to sum and increment I by 1
4. if I is less than or equal to n goto step 3
5. print the sum

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);
}

Input:- enter value for n


n=5

Output:- sum upto 5 numbers is 15

6
PROBLEM 7:- Swap two numbers.( using temporary variable).

PROCEDURE:-

1.input values for a and b


2. store value of a in t
3. store value of b in a
4. store value of t in b
5.print value of a and b after swapping

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);
}

Input:- enter value for a,b


a=5, b=6

Output:- after swapping a=6 b=5

7
PROBLEM 8:- Swap Two numbers (without using temporary variable)

PROCEDURE:-

1.input values for a and b


2. compute a= a+b
3. compute b =a-b
4. compute a=a-b
5.print value of a and b after swapping

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);
}

Input:- enter value for a,b


a=5, b=6

Output:- after swapping a=6 b=5

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

Input:-enter a character
A
Output:-a

9
PROGRAMS USING IF,IF-ELSE,CASE.
PROBLEM 10:- Greatest of 3 numbers.( Nested IF-ELSE)

PROCEDURE:-

1. input values for a,b,and c.


2. check whether a is greater than b and c
3. if so a will be greatest
4. if not c will be greatest
5. if a is not greater than b and c
6. then check whether b is greater than c
7. if yes b is greatest
8. if no c is greatest

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);
}
}

Input:- enter values for a,b,c


a=5, b=6, c=7

Output:- 7 is geatest

10
PROBLEM 11:- Find greatest of 3 numbers.(Using conditional operator)

PROCEDURE:-

1.input values for a,b,and c.


2.check whether a is greater than b and c
3.if so a will be greatest
4.if not c will be greatest
5.if a is not greater than b and c
6.then check whether b is greater than c
7.if yes b is greatest
8.if no c is greatest

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);
}

Input:- enter values for a,b,c


a=6, b=8, c=7

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;
}
}

Input:- Enter a number 123


Output:-one two three

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:-

1.input no. of units consumed


2.according to the above specifications find the amount to be paid
3.print the above result

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);
}

Input:- enter the number of units


320

Output:-the total bill is 800.00

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”);
}
}

Input:- enter the marks of the students 755


Output:- distinction

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);
}

Input:- enter the salary of the employee 60000


Output:- the net salary of the employee is 10600

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);
}

Input:- enter value for n 4


enter 4 different values 20 20 20 20
Output:- sum of 4 numbers is 80

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);
}

Input:- enter value for n 4


enter 4 different values 10 11 12 13
Output:- Even sum =22 Odd sum =24

17
PROBLEM 18:- Reversing a number.

PROCEDURE:-

1.enter integer value n


2.repeat step 3 to 5 until n is greater than 0
3. find the modulo 10 for n and store result in r
4.print r
5. find new value of n by dividing it by 10

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;
}
}

Input:- enter value for n 124


Output:- 421

18
PROBLEM 19:- Sum of digits of a number down to a single digit.

PROCEDURE:-

1.enter integer value n


2.repeat step 3 to 8 until n is greater than 9
3.set sum to 0
4.repeat step 5 to 7 until n is greater than
5. find the modulo 10 for n and store result in r
6.add r to previous sum
7. find new value of n by dividing it by 10
8 set n to sum
9. print sum

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);
}

Input:- enter value for n 137


Output:- sum of 137 down to single digit is 2

19
PROBLEM 20. Number system conversion.(Decimal to Binary)

PROCEDURE:-

1.enter integer value n set sum to 0 and f to 1


2.repeat step 3 to 6 until n is greater than 0
3. find the modulo 2 for n and store result in r
4.set sum to sum+r*f
5.set f to f*10
6. find new value of n by dividing it by 2
7. print sum

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);
}

Input:- enter number in decimal system 7


Output:- the binary value for the decimal number 7 is 111

20
PROBLEM 21:- Find factorial of a number.

PROCEDURE:-

1.input an integer value n


2.set fact to 1 and i to 1
3.repeat step 4,5 until i less than or equal to n
4.set fact to fact*i
5.increment i by 1
6.print fact

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);
}

Input:- enter value for n 5


Output:- factorial for the number 5 is 120

21
PROBLEM 22:- Find G.C.D.(Greatest Common Divisor) of two numbers.

PROCEDURE:-

1.input two interger values a and b


2.if a is greater than b
3.set n=b
4.else set n=a
5.repeat steps 6 and 9 until n is greater than 0
6 find a modulo n and b modulo n, if modulo value is 0
7. print gcd value as n
8.stop
9else decrement n by 1

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);
}

Input:- enter two numbers for a ,b to find GCD 16 24


Output:- GCD for 16 and 24 is 8

22
PROBLEM :-23 Checking whether a number is Prime.

PROCEDURE:-

1.input an interger value n


2.start finding modulo value for n with i=2 to n-1 value incrementing i by 1 each time
3.if at any point remainder becomes 0
4.print that number is not prime
5.else print that the number is prime

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);
}

Input:- enter a number 5


Output:-the given number 5 is prime number

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:-

1.input an interger value n


2. set sum to 0
2.start finding modulo value for n with i=1 to n-1 value incrementing i by 1 each time
3.if at any point remainder is 0 add i to sum
4.if sum is same as the original input n then n is perfect number
5.else n is not perfect number

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);
}

Input:- enter a number 6


Output:-the given number 6 is perfect number

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:-

1.set i to 3, set a=0,b=1,


2. repeat steps 3 to 5 until i is less than or equal 100 incrementing i by 1 each time
3. compute c=a+b
4.print value of c
5. set a=b,b=c

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++;
}
}

Output:- Fibonacci series below 100 are


0 1 1 2 3 5 8 13………………

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++;
}
}

Output:- (3,5) (5,7) (11,13)…………………

30
PROBLEM 31. Sum of the series to 25 terms 1+1/4+1/9+.....

PROCEDURE:-

1.set sum to 0 and set i to 1


2.repeat step 3 until i less than or equal 25 incrementing i by 1
3.set sum=sum+1/square(i)
4.print sum

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);
}|

Output:- sum of the series is =1.605724

31
PROBLEM 32:-. Evaluate the cos(x) series(x-x3/3!+x5/5!-……..)

PROCEDURE:-

1. input values for degrees x and the number of terms to be added n


2. convert the given degrees to radians
3. substitute in the series to find the sum
4. print the sum

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);
}

Input:- enter the number of terms and degrees 10 60

Output:-cos(60)=0.499999

32
PROBLEM 33:- Evaluate the sin(x) series(1-x2/2!+x4/4!-….)

PROCEDURE:-

1.input values for degrees x and the number of terms to be added n


2.convert the given degrees to radians
3.substitute in the series to find the sum
4.print the sum

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);
}

Input:- enter the number of terms and degrees 10 30

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

Output:- 121 is a palindrome

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”);
}
}

Input:-enter value for n 3


Output:-1
2 2
3 3 3

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”);
}
}

Input:-enter value for n 3


Output:- 1
2 2
3 3 3

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.

PROBLEM 41:- Sum & Average of a given n numbers.

PROCEDURE:-

1.read the no. of values to be entered n


2.read the n different elements while reading add it sum
3.find the average and print sum and average

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);
}

Input:-enter value for n 4


Enter the 4 elements 10 20 30 40
Output:-sum=100 average=25.00

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);
}

Input:-enter a number 1234


Output:-sum of digits in even places=6
Sum of digits in odd places=4

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

PROBLEM 51:- Count the number of words, characters in a string.

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);
}

Input:- Enter any String : I am fine


Output:- The Total No.of Words : 3
The Total No.of Characters 7

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”);
}

Input:- Enter first string : Hello


Enter second string: Hello
Output:-the strings are equal

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);
}

Input:- Enter first string : Hello

Output:- The original string: Hello


The copied string : Hello

53
PROBLEM 54:- Concatenate Two Strings.

PROCEDURE:-

1.read two strings


2.traverse till the end of string
3.add second string at the end of first string
4.terminate the string with null character
5.print the first string

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);
}

Input:- Enter first string : Hello


Enter second string: hai

Output:- After concatenating two strings : Hellohai

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);
}

Input:- Enter first string : Hello


Enter second string: hai
Enter position to insert string : 2

Output:- The result string is : Hhaiello

55
PROBLEM 56:- Delete n characters in the string from a particular position.
PROCEDURE:-

1.read a string st1


2.read the no. of characters to be deleted n and form which position m
3. set j to n+m so as to move characters positioned at j a head till null character is
encountered

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);
}

Input:-enter a string : HELLO


Enter the position and the number of characters to be deleted 1 3

Output:-the new string is :- HO

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]);
}

Input:-enter the string: HELLO

Output:-the reversed string is: OLLEH

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);
}

Input:-enter the string: MADAM

Output:-the string is 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:-

1. Read the numbers in to the array.


2. Imagine that the first no.in the array is the maximum no.
3. compare other no with max.
4. if no. is greater than max interchange the values.
5. print the max value.

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:-

1. Read the number n., set f=1


2. starting i=1,2….n repeat step 3
3. set f=f*i
4. print f

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);
}

Input:-enter value for n 3


Output:-factorial of 3 is 6

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);
}

void rev(char *s)


{
char *t;
t=s;
while(*s!=’\0’)
s++;
printf(“the reversed string is \n”);
while((s-t)>=0)
{
putchar(*s) ;
s--;
}
}

Input:-enter the string : HELLO


Output:-the reversed string is :OLLEH

63
PROBLEM 64:- Swap two numbers (Call by value).

PROCEDURE:-

1. Read two numbers a & b.


2. using a temporary variable interchange the values of a & b.
3. print the values of a & b.

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);
}

Input:-enter values for a and b 5 4

Output:-before swapping a=5 b=4


After swapping a=5 b=4

64
PROBLEM 65:- Swap two numbers (Call by reference).

PROCEDURE:-

1 Read two numbers a & b.


2 using a temporary variable interchange the address locations of a & b.
3 print the values of a & b.

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;
}

Input:-enter values for a and b 5 4

Output:-before swapping a=5 b=4


After swapping a=4 b=5

65
PROBLEM 66:- A recursive function in C for finding the factorial of a given
number n.

PROCEDURE:-

1 Read the number n.


2 recursive call of n*fact(n-1) until n=0
3 print value

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));
}

Input:-enter value for n 3


Output:-factorial of 3 is 6

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));
}

Input:-enter value for n 4


Output:-sum upto 4 numbers is 10

69
PROBLEM 70:- Find Standard Deviation for a set of values .

PROCEDURE:-

1. Read value for n


2. read n different values find the total sum of them
3. find average of n nos.
4. for the n values find sd

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);
}

Input:-enter value for n 4


Enter 4 values 4 5 6 7

Output:-sd=0.25

70
PROGRAMS ON STRUCTURES:

PROBLEM 71: Program to calculate the subject-wise and student-wise totals


and store them as a part of the structure and arrays within a structure.
PROCEDURE:-
1.read the number of students and no. of subjects n m
2. read the m marks obtained by each of n students
3. put the data in tabular form find total sum of marks obtained by each student S
4. find marks total obtained in each subject by all the students T
5. find the grand total (S+T)
6.print all the details in tabular form
CODE:-
#include<stdio.h>
#define max 10
struct student
{
int s[max];
int ts[max];
int tst[max];
}st[max];
int i,j,s,gt,m,n;
void main()
{
printf(“enter no. of students”);
scanf(“%d”,&n);
printf(“enter no. of subjects”);
scanf(“%d”,&m);
printf(“enter %d students %d subjects marks\n”,n,m);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf(“%d”,&st[i].s[j]);
for(i=0;i<n;i++)
{
st[i].tst[i]=0;
for(j=0;j<m;j++)
st[i].tst[i]+=st[i].s[j];
}
}
for(j=0;j<m;j++)
{
st[j].ts[j]=0;
for(i=0;i<n;i++)
st[j].ts[j]+=st[i].s[j];
}
gt=0;

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:-

sub1 sub2 sub3 sub4 studenttotal


st1 10 10 10 10 40
st2 20 20 20 20 80
st3 30 30 30 30 120
st4 40 40 40 40 160
st5 50 50 50 50 200
subtot 150 150 150 150 1200

72
PROBLEM 72:- Write a simple program method of sending an entire
structure as a parameter to a function.

PROCEDURE:-

1.read values for a structure members through structure variables


2.send the entire structure to the function and modify the values in the function
3.after modification send back the entire structure and receive it in a structure variable
4.modifications are available in main program

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);
}

struct abc modify(struct abc s1)


{
s1.a=s1.a+10;
s1.b=s1.b+10;
return(s1);
}
Input:- the structure members before modification are : 10 10.5
Output:- the structure members after modification are : 20 20.5

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);
}

Input:- the union members values are:


Output:-10
10.50000

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:-

1.read value for n


2.read n different values while reading add it to sum
3.print the sum
CODE:-

#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);
}

Input:-enter value for n 3


Enter the 3 elements 10 20 30
Output:-the sum=60

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);
}

Input:-enter string: HELLO


Output:-the length of the string is 5

77
PROBLEM 77:- Write a program to sort a given set of numbers.

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 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));
}

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

78
PROBLEM 78: Write a program to find matrix multiplication.

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>
#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

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

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);
}

Input:- enter the string : HAI


Output:-the copied string is : HAI

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:-

1.read values for a structure members through structure variables


2.send the address of structure variable to the function and modify the values in the function
3..modifications are available in main program
CODE:-

#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);
}

void modify(struct abc *s1)


{
s1->a=s1->a+10;
s1->b=s1->b+10;
}

Input:- the structure members before modification are : 10 10.5


Output:- the structure members after modification are : 20 20.5

84
PROBLEM 83:- Write an example program which uses pointer to a structure.

PROCEDURE:-

1.read values for structure members


2.store the address of structure variable in a structure pointer
3.now members are accessed by -> operator

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);
}

Output:- the contents of the structure are 10 10.5

85
PROBLEM 84:- Write a program that uses a function returning a pointer.
PROCEDURE:-

1.this function returns the address


2.so values in function are available in main

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:-

1. open a DATA file to write integer data


2. open the same file for reading, and open ODD,EVEN files to write
3. read contents of DATA file and check whether it is even or odd number
4. if it is odd number write to ODD file else write to EVEN file
5. close all the files

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:-

1. open a TEXT file to write character data


2. open the same file for reading, and open VOWEL,CONSONANT files to write
3. read contents of TEXT file and check whether it is vowel or not
4. if it is vowel character write to VOWEL file else write to CONSONANT file
5. close all the files

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:-

1.open a file to store text


2. open the same file for modification
3. repeat step 4 until EOF is encountered
4. extract character by character , if character is ‘a’ replace the same with ‘#’
5. close the file

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:-

1.open a two files to store text F1,F2


2. open the F1 file for appending
3. repeat step 4 until EOF of F2 is encountered
4. extract character by character , and place it in F1
5. close the files

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:-

1.open a file to store text F1


2. open the F2 file in writing mode
3. repeat step 4 until EOF of F1 is encountered
4. extract character by character , and place it in F2
5. close the files

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:-

1.open a file to store text F1


2. open the F1 file in reading mode
3. repeat step 4 until EOF of F1 is encountered
4. extract character by character , and place it on screen
5. close the files

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:-

1. special functions feof() and fopen() are used to check


2. whether the opening file is available or not and to see that
3. reading of data beyond EOF mark is avoided

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);

fprintf(fp,”%s %d %.2f %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;

printf(“%-8s %7d %8.2f %11.2f\n”,item,num,price,qty,value);

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:-

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


{
FILE *f1;
f1=fopen(argv[1],”r”);
remove(f1);
fclose(f1);
}

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

PROBLEM 100:- Program to implement push and pop operations in a stack


using arrays.

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);
}
}

Input:- enter the infix expression a+(b*c/d)


Ouput:- Postfix expression is : abc*d/+

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:-

This procedure VALUE of an arithmetic expression P written in postfix notation.


1. Add a right parenthesis”)” at the end of P(sentinel).
2. Scan P from left to right and repeat steps 3 and 4 for each element of P until the sentinel
“)” is encountered.
3. If an operand is encountered, put it on STACK.
4. If an operator X is encountered, then:
a) Remove the two top elements of STACK, where A is the top element and B is the
next-to-top element.
b) Evaluate B X A.
c) Place the result of (b) back on STACK.
[End of If structure.]
5. Set VALUE equal to the top element on STACK.
6. Exit.

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();
}

Input:-enter postfix expression: abc*d/+


Enter values for a,b,c,d: 5 8 2 2

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

PROBLEM 105:- Write a program to implement Queue using arrays.

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

PROBLEM 108:- Write a program to implement singly 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]=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();
}

struct node *push(struct node *first)


{

struct node * newnode;


int newele;
printf(“enter value to be pushed”);
scanf(“%d”,&newele);
new_node=(struct node *)malloc(sizeof(struct node));
new_node->element=new_element;
new_node->next=first;
first=new_node;
return(first);
}

struct node *pop(struct node *first)


{
struct node *temp;
int element;
if(first= =NULL)
printf(“empty”);
else
{

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;
}

int delete(struct queue *q)


{
int x;
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
if(q->front = =NULL)
printf(“underflow”);
new=q->front;
x=new->data;

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:-

1. create two linked lists L1 and L2


2. traverse till the last node in first list L1
3. set LINK field of that node to L2

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:-

1. create two linked lists L1 and L2


2. starting with first node in L1 ,set link of first node to first node in L2 called next
3. set next node in L1 as current first node , set current next node in L2 as next
4. repeat steps 2 and 3 till either of L1 or L2 becomes NULL
5. If L1=NULL add L2 ‘s remaining nodes at end of the merged list
6. if L2=NULL add L1’s remaining nodes at end of the merged list

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:-

1. create a one list L1


2. Find the no. of nodes to be in first list n
3. set temp to first node
4. traverse till the n’th node is reached set link field of that node as L2
5. set link field of n’th node as NULL

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:-

1. create a linked list f


2. set f1=f; set s=NULL;
3. repeat step 4 while(f1!=NULL)
4. set t=LINK[f1]; set link[f1]=s; set s=f1; set f1=t;
5. set f=s

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 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: 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

PROBLEM 120:- Write a program to create and traverse a binary tree in


a) Preorder.
b) Inorder.
c) Postorder.

PROCEDURE for Preorder Traversal:-

PREORD(INFO, LEFT, RIGHT, ROOT)

A binary tree T is in memory. This procedure does a preorder traversal of T, applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Initially push NULL onto STACK, and initialize PTR.]
Set TOP:=1, STACK[1]:=NULL and PTR:=ROOT.
2. Repeat steps 3 to 5 while PTR ≠ NULL:
3. Apply PROCESS to INFO[PTR].
4. [Right child?]
If RIGHT[PTR] ≠ NULL, then: [Push on STACK.]
Set TOP:= TOP+1, and STACK[TOP]:=RIGHT[PTR].
[End of If structure]
5. [Left child?]
If LEFT[PTR] ≠ NULL, then:
Set PTR:=LEFT[PTR].
Else: [Popfrom STACK.]
Set PTR:=STACK[TOP] and TOP:=TOP-1.
[End of If structure.]
[End of stop2 loop.]
6. Exit.

PROCEDURE for Inorder Traversal:-

INORD(INFO,LEFT,RIGHT,ROOT)

A binary tree T is in memory. This procedure does an inorder traversal of T applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Push NULL onto STACK and initialize PTR.]
Set TOP:=1, STACK[1]:= NULL and PTR:= ROOT.
2. Repeat while PTR ≠ NULL: [Pushes left-most path onto STACK.]
a) Set TOP:= TOP+1 and STACK[TOP:=PTR.[Saves node.]
b) Set PTR:= LEFT[PTR], [Updates PTR.]
[End of loop.]
3. Set PTR:=STACK[TOP] and TOP:=TOP-1.[Pops node from STACK.]

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.

PROCEDURE for Postorder Traversal:-

POSTORD(INFO,LEFT,RIGHT,ROOT)

A binary tree T is in memory. This procedure does a postorder traversal of T applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Push NULL onto STACK and initialize PTR.]
Set TOP:=1, STACK[1]:= NULL and PTR:= ROOT.
2 [Push left-most path onto STACK.].
Repeat steps 3 to 5 while PTR ≠ NULL:
3. Set TOP:= TOP+1 and STACK[TOP:=PTR
[Pushes PTR on STACK].
4. If RIGHT[PTR ]≠ NULL then: [Push on STACK]
Set TOP:= TOP+1 and STACK[TOP]:= -RIGHT[PTR].
[End of If structure.].
5. Set PTR: = LEFT[PTR]. [Updates pointer PTR.]
[End of step 2 loop.]
6. Set PTR: = STACK[TOP] and TOP: = TOP-1.
[Pops node from STACK.]
7. Repeat while PTR>0:
(a) Apply PROCESS to INFO[PTR].
(b) Set PTR: = STACK[ TOP] and TOP: = TOP-1.
[Pops node from STACK.]
[End of loop.]
8. If PTR<0, then:
(a) Set PTR: = -PTR.
(b) Go to Step 2.
[End of If structure.]
9. Exit.

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);
}
}

void recpreorder(btree *r)


{
if(r!=NULL)

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

PROCEDURE for Preorder Traversal:-

PREORD(INFO, LEFT, RIGHT, ROOT)

A binary tree T is in memory. This procedure does a preorder traversal of T, applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Initially push NULL onto STACK, and initialize PTR.]
Set TOP:=1, STACK[1]:=NULL and PTR:=ROOT.
10. Repeat steps 3 to 5 while PTR ≠ NULL:
11. Apply PROCESS to INFO[PTR].
12. [Right child?]
If RIGHT[PTR] ≠ NULL, then: [Push on STACK.]
Set TOP:= TOP+1, and STACK[TOP]:=RIGHT[PTR].
[End of If structure]
13. [Left child?]
If LEFT[PTR] ≠ NULL, then:
Set PTR:=LEFT[PTR].
Else: [Popfrom STACK.]
Set PTR:=STACK[TOP] and TOP:=TOP-1.
[End of If structure.]
[End of stop2 loop.]
14. Exit.

PROCEDURE for Inorder Traversal:-

INORD(INFO,LEFT,RIGHT,ROOT)

A binary tree T is in memory. This procedure does an inorder traversal of T applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Push NULL onto STACK and initialize PTR.]
Set TOP:=1, STACK[1]:= NULL and PTR:= ROOT.
2. Repeat while PTR ≠ NULL: [Pushes left-most path onto STACK.]
a) Set TOP:= TOP+1 and STACK[TOP:=PTR.[Saves node.]
b) Set PTR:= LEFT[PTR], [Updates PTR.]
[End of loop.]

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.

PROCEDURE for Postorder Traversal:-

POSTORD(INFO,LEFT,RIGHT,ROOT)

A binary tree T is in memory. This procedure does a postorder traversal of T applying an


operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Push NULL onto STACK and initialize PTR.]
Set TOP:=1, STACK[1]:= NULL and PTR:= ROOT.
2 [Push left-most path onto STACK.].
Repeat steps 3 to 5 while PTR ≠ NULL:
3. Set TOP:= TOP+1 and STACK[TOP:=PTR
[Pushes PTR on STACK].
4. If RIGHT[PTR ]≠ NULL then: [Push on STACK]
Set TOP:= TOP+1 and STACK[TOP]:= -RIGHT[PTR].
[End of If structure.].
5. Set PTR: = LEFT[PTR]. [Updates pointer PTR.]
[End of step 2 loop.]
6. Set PTR: = STACK[TOP] and TOP: = TOP-1.
[Pops node from STACK.]
7. Repeat while PTR>0:
i. Apply PROCESS to INFO[PTR].
ii. Set PTR: = STACK[ TOP] and TOP: = TOP-1.
[Pops node from STACK.]
[End of loop.]
8. If PTR<0, then:
i. Set PTR: = -PTR.
ii. Go to Step 2.
[End of If structure.]
9. Exit.
PROCEDURE TO COUNT NO. OF LEAF NODES:-
1.While tree traversal if nodes left link and it’s right link are both NULL
2. then increase leaf nodes count by 1
PROCEDURE TO COUNT NO. OF LEAF NODES:-
1.While tree traversal if nodes left link is NULL and right link is not NULL

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--]);
}

btree * insert(int data,btree *p)


{
if(!p)
{
p=(btree *)malloc(sizeof(btree));
p->data=data;
p->left=NULL;
p->right=NULL;

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 recpreorder(btree *r)


{
if(r!=NULL)
{
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”);

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

PROBLEM 124:- Write a program to perform linear search.


PROCEDURE:-
1. enter n value
2. read n values into the array a[].
3. enter the element x which we want to search
4. compare x value with each element of array elements from a[0] to a[n]
5. if element found
print “element found”
else
print “element is not found”
6. exit.

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.

Quick sort , this algorithm sorts an array a with n elements.

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.

1. set n=n+1 and ptr=n.


2. repeat steps 3 to 6 while ptr<1.
3. set par=ptr/2
4. if item <=tree[par], then
set tree[ptr]=item, and return
5. set tree[ptr]=tree[par]
6. set ptr=par.
7. set tree[1]=item
8. return

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

Potrebbero piacerti anche