0% found this document useful (0 votes)
25 views105 pages

DS LAB Manual

The document outlines the Data Structures using C Lab course objectives and outcomes for B.Tech students, focusing on algorithmic complexities, recursive functions, and data structure implementation. It includes detailed exercises for implementing various algorithms such as Fibonacci, factorial, GCD, sorting techniques, and data structures like stacks, queues, trees, and graphs. Each exercise provides a clear aim, algorithm, and sample C program to guide students in practical coding applications.

Uploaded by

buradabalaji66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views105 pages

DS LAB Manual

The document outlines the Data Structures using C Lab course objectives and outcomes for B.Tech students, focusing on algorithmic complexities, recursive functions, and data structure implementation. It includes detailed exercises for implementing various algorithms such as Fibonacci, factorial, GCD, sorting techniques, and data structures like stacks, queues, trees, and graphs. Each exercise provides a clear aim, algorithm, and sample C program to guide students in practical coding applications.

Uploaded by

buradabalaji66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

RAGHU ENGINEERING COLLEGE

(Autonomous)
(Approved by AICTE, New Delhi, Permanently Affiliated to JNTU Kakinada,
Accredited by NBA & Accredited by NAAC with A grade)

Data Structures using C Lab


AR20- B.Tech(Common to CSE and all specializations)
I-B.Tech., II-Semester

Course Objectives:
The objectives of Data Structures are

 To get exposure to algorithmic complexities, recursive functions, searching and


sorting
 To apply stack techniques
 To design & develop of C programs
 To design and develop trees and graphs

Course Outcomes:
By the end of the lab, the student,

 Able to implement the code for all basic algorithms like searching, sorting etc
 Able to write code for linear data structures like stacks, queues and linked list
 Able to design and develop non-linear data structures like trees and graphs
 Able to develop efficient modular programming
Exercise 1: Write recursive program which computes the nth Fibonacci number, for appropriate
values of n. Analyze behavior of the program Obtain the frequency count of the statement for
various values of n.
Exercise 2: Write recursive program for the following
a) Write recursive and non-recursive C program for calculation of Factorial of an integer
b) Write recursive and non-recursive C program for calculation of GCD (n, m)
c) Write recursive and non-recursive C program for Towers of Hanoi : N disks are to be
transferred from peg S to peg D with Peg I as the intermediate peg.
Exercise 3:
a) Write C program that use both recursive and non-recursive functions to perform Linear
search for a Key value in a given list.
b) Write C program that use both recursive and non-recursive functions to perform Binary
search for a Key value in a given list.
c) Write C program that use both recursive and non-recursive functions to perform Fibonacci
search for a Key value in a given list.
Exercise 4
a) Write C program that implement Bubble sort, to sort a given list of integers in ascending
order
b) Write C program that implement Quick sort, to sort a given list of integers in ascending
order
c) Write C program that implement Insertion sort, to sort a given list of integers in ascending
order
Exercise 5:
a) Write C program that implement heap sort, to sort a given list of integers in ascending order
b) Write C program that implement radix sort, to sort a given list of integers in ascending order
c) Write C program that implement merge sort, to sort a given list of integers in ascending
order
Exercise 6:
a) Write C program that implement stack (its operations) using arrays
b) Write C program that implement stack (its operations) using Linked list
Exercise 7:
a) Write a C program that uses Stack operations to Convert infix expression into postfix
expression a) Write C program that implement Queue (its operations) using arrays.
b) Write C program that implement Queue (its operations) using linked lists
Exercise 8:
a) Write a C program that uses functions to create a singly linked list
b) Write a C program that uses functions to perform insertion operation on a singly linked list
c) Write a C program that uses functions to perform deletion operation on a singly linked list
Exercise 9: a) Adding two large integers which are represented in linked list fashion.
b) Write a C program to reverse elements of a single linked list.
c) Write a C program to store a polynomial expression in memory using linked list
d) Write a C program to representation the given Sparse matrix using arrays.
e) Write a C program to representation the given Sparse matrix using linked list
Exercise10:
a) Write a C program to Create a Binary Tree of integers
b) Write a recursive C program for Traversing a binary tree in preorder, inorder and postorder.
c) Write a non-recursive C program for Traversing a binary tree in preorder, inorder and post-
order.
d) Program to check balance property of a tree.
Exercise 11:
a) Write a C program to Create a BST
b) Write a C program to insert a node into a BST.
c) Write a C program to delete a node from a BST.
Ex. No: 1 FIBONACCI NUMBER USING RECURSION
Aim: Write recursive programme which computes the nth Fibonacci number, for appropriate
values of n.
Analyze behavior of the programme Obtain the frequency count of the statement for various
values of n.
Algorithm:
/* Fibonacci_series */
Input: Read n value
Output: Prints the nth Fibonacci term
Step1: Start
Step2: Read n value for computing nth term in Fibonacci series
Step3: call sub-routine Fibonacci (n)
Step4: Print the nth term
Step5: End

Sub-routine Fibonacci (n)


Step1: If n = 0 then go to step2 else go to step3
Step2: return 0
Step3: If n = 1 then go to step4 else go to step5
Step4: return 1
Step5: term= Fibonacci (n-1) + Fibonacci (n-2)
Step6: return term

Program:
/* Finding nth Fibonacci number using recursion */
#include <stdio.h>
#include <conio.h>
int Fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
void main()
{
int n;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
printf("\n nth Fibonacci value=%d",Fibonacci(n));
getch();
}

OUTPUT:
Ex. No: 2(a) FACTORIAL USING RECURSION
Aim: Write recursive C programme for calculation of Factorial of an integer
Algorithm:
/* factorial_recursive */
Input: integer n
Output: factorial of given number
Step 1: Start
Step 2: read n
Step 3: call sub-routine fact_rec(n)
Step 4: print factorial
Step 5: Stop
Algorithm for sub routine fact_rec(int n)
Step 1: begin
Step 2: f 1
Step 3: if n = 0 go to step 4 else go to step 5
Step 4: return 1
Step 5: f  n* fact_rec(n-1)
Step 6: return f

Program:
#include <stdio.h>
#include <conio.h>
/* compute n! recursively */
int fact_rec(int n)
{
/* error check */
if (n < 0)
return(-1);
/* base case */
if (n == 0)
return(1);
/* recursion */
return(n * fact_rec(n-1));
}
void main()
{
int n;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
printf("\n Factorial value=%d",fact_rec(n));
getch();
}

Output:
EX. NO: 2(B) GCD USING RECURSION

Aim: Write recursive C program for calculation of GCD (n, m)


Algorithm:
/* GCD_recursive */
Input: integer a, b
Output: GCD of a, b
Step 1: Start
Step 2: read a, b
Step 3: call sub routine gcd_rec(a, b)
Step 4: print GCD
Step 5: Stop
Algorithm for Sub Routine gcd_rec (int a, int b)
Step 1: begin
Step 2: if a = 0 then go to step3 else go to step4
Step 3: return b
Step 4: if b = 0 then go to step5 else go to step6
Step 5: return a
Step 6: g= gcd_rec (b, a mod b)
Step 7: return g
Program:
/* recursive GCD calculation */
#include <stdio.h>
#include <conio.h>
int gcd_rec(int m, int n)
{
/* base case(s) */
if (m == 0)
return(n);
if (n == 0)
return(m);
/* now recursion */
return(gcd_rec(n, m % n));
}
void main(void)
{
int m, n; /* numbers to take the GCD of */
int g; /* the GCD of m and n */
clrscr();
/* asking for numbers and printing the GCD */
printf("Enter two nombers :");
scanf("%d%d", &m,&n);
printf("The GCD of %d and %d is %d.", m, n,gcd_rec(m,n));
}

Output:
EX. NO: 2(C) TOWERS OF HANOI USING RECURSION

Aim: Write recursive C programme for Towers of Hanoi: N disks are to be transferred from
peg S to peg D with Peg I as the intermediate peg.

Algorithm:
/* Towers of Hanoi recursive */
Input: integer n
Output:
Step 1: Start
Step 2: read n value as the no. of disks
Step 3: call sub-routine toh (n, S, D, I)
Step 4: Stop
Algorithm for sub routine toh (n, source, dest, aux)
Step 1: begin
Step 2: if n = 1 then
Step 3: Move the single disk from source to dest and stop
Step 4: else
Step 5: Move the top n-1 disks from S to I, using D as auxiliary
Call sub routine toh (n-1, source, aux, dest)
Step 6: Move the remaining disk from S to D
Step 7: Move the n-1 disks from I to D, using S as auxiliary
Call sub routine toh (n-1, aux, dest, source)
Step 8: end
Program:
#include<stdio.h>
#include<conio.h>
/* source peg----s, destination peg --- d
Intermediate peg----t */
void tower(int n,char s,char d, char t)
{
if(n==1)
{
printf("\nMove disk %d from %c to %c",n,s,d);
return;
}
else
/* Move top n-1 disks from S to I, using D as auxiliary */
tower(n-1,s,t,d);
/* Move remaining disk from S to D */
printf("\nMove disk %d from %c to %c",n,s,d);
/* Move n-1 disk from I to D usiong S as auxiliary */
tower(n-1,t,d,s);
}
void main()
{
int n;
clrscr();
printf("Enter number of disks ");
scanf("%d",&n);
tower(n,'S','D','I');
getch();
}

Output:
EX. NO: 3(A) Linear Search Using Recursive & Non- Recursive Functions

Aim: Write C programs that use both recursive and non recursive functions to perform
Linear search for a Key value in a given list.
Algorithm:
/* Linear_ Search */
Input: n, ser_val, a[50]
Output: found = true and loc = position of item if the search is successful;
otherwise, found is false.

Step 1: Start
Step 2: read n // no of elements
Step 3: repeat step 4 until for i: 0 to n
Step 4: read a[i]
Step 5: read ser_val // search value
Step 6: read the choice to use the either recursive or non-recursive function
Step 7: if ch=1 then do the following otherwise go to step8
Step7.1: res  call sub routine Linear_search(a, n, ser_val)
Step7.2: if res! = -1
Step7.3: print ‘ser_val found at by non recursive function = res’
Step 7.4: else
Step 7.5: print ‘not found in list’
Step8: if ch=2 then do the following otherwise go to step9
Step 8.1: res  call sub routine Linear_search_rec(a, n, ser_val)
Step 8.2: if res! = -1
Step 8.3: print ‘ser_val found at by recursive function = res’
Step 8.4: else
Step 8.5: print ‘not found in list’
Step 9: print ‘invalid choice’
Step10: Stop
Algorithm for sub-routine Linear_search(int a[], int n, int ser_val)
Step 1: begin
Step 2: repeat steps 3 to 7 until for i: 0 to n
Step 3: if a[i] = ser_val then go to step4 else go to step6
Step 4: return (i)
Step 5: break and goto step7
Step 6: return (-1)
Step 7: end
Algorithm for sub-routine Linear_search_rec(int a[], int n, int ser_val)
Step 1: begin
Step 2: if n==0 then go to step3 else go to step4
Step 3: return -1
Step 4: if a[n-1] = ser_val then go to step5 else go to step6
Step 5: return (n-1)
Step 6: return (Linear_search_rec(a, n1, ser_val)
Program:
/* Linear search using recursive and non-recursive functions */
#include<stdio.h>
#include<conio.h>
int Linear_search( int array[], int length, int value);
int Linear_search_rec( int array[], int length, int value);
int main()
{
int a[20],i,n,x,xloc=-1,ch;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element you want to search for\n");
scanf("%d",&x);
printf("Which function you want to use\n");
printf("1. Non-recursive\n2. recursive\n");
printf("Enter the choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:
xloc = Linear_search(a,n,x);
if(xloc!=-1)
printf("%d is found at %d location by non recursive function\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
case 2:
xloc = Linear_search_rec(a,n,x);
if(xloc!=-1)
printf("%d is found at %d location by recursive function.\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
default:printf("Invalid choice.");
}
getch();
}

Linear_search(int a[], int n,int x)


{
int i,xloc;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
xloc=i;
break;
}
}
return xloc;
}
int Linear_search_rec(int a[],int n,int x)
{
if(n==0) return -1;
else if (a[n-1]==x) return n-1;
else return Linear_search_rec(a,n-1,x);
}

Output:
Ex. No: 3(B) Binary Search Using Recursive & Non- Recursive Functions

Aim: Write C programs that use both recursive and non recursive functions to perform
Binary search for a Key value in a given list.

Algorithm:
/* Binary_ Search */
Input: n, ser_val, a[50]
Output: found = true and loc = position of item if the search is successful;
otherwise, found is false.

Step 1: Start
Step 2: read n // no of elements
Step 3: repeat step 4 until for i: 0 to n
Step 4: read a[i]
Step 5: read ser_val // search value
Step 6: low0, highn-1
Step 7: read the choice to use either recursive or non-recursive functions
Step 8: if ch=1 then do the following otherwise go to step8
Step8.1: res  call sub routine Binary_search(a, low, high, ser_val)
Step 8.2: if res ! = -1
Step 8.3: print ‘ser_val found at by non recursive function = res’
Step 8.4: else
Step 8.5: print ‘not found in list’
Step9: if ch=2 then do the following otherwise go to step9
Step9.1: res  call sub routine Binary_search_rec(a, low, high, ser_val)
Step 9.2: if res != -1
Step 9.3: print ‘ser_val found at by recursive function = res’
Step 9.4: else
Step 9.5: print ‘not found in list’
Step 10: print ‘invalid choice’
Step 11: Stop

Algorithm for sub-routine Binary_search(int a[], int low, int high, int ser_val)
Step 1: begin
Step 2: repeat steps 3 to 10 until low <= high
Step 3: mid(low+high)/2
Step 4: if a[mid] = ser_val then go to step5 else go to step7
Step 5: locmid
Step 6: return loc and break
Step 7: if ser_val < a[mid] then go to step8 else go to step9
Step 8: highmid-1 and go to step 10
Step 9: lowmid+1
Step 10: end
Algorithm for sub-routine binary_search_rec(int a[], int lo, int high, int ser_val)
Step 1: begin
Step 2: if high<low then go to step3 else go to step4
Step 3: return -1;
Step 4: midlow + ((high-low)/2);
Step 5: if a[mid] > ser_val then go to step6 else go to step7
Step 6: return Binary_search_rec (a, low, mid-1, ser_val)
Step 7: if a[mid] < ser_val then go to step8 else go to step10
Step 8: return Binary_search_rec (a, mid+1, high, ser_val)
Step 9: return mid;
Step 10: end

Program:

/* Binary search using recursive and non-recursive functions */

#include<stdio.h>
#include<conio.h>
int Binary_search(int a[], int low, int high, int x);
int Binary_search_rec(int a[], int low, int high, int x);
void main()
{
int a[20],i,n,x,xloc=-1;
int low,high,ch;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element you want to search for\n");
scanf("%d",&x);
low = 0;high = n-1;
printf("Which function you want to use\n");
printf("1. Non-recursive\n2. recursive\n");
printf("Enter the choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:
xloc = Binary_search(a,low,high,x);
if(xloc!=-1)
printf("%d is found at location %d by non recursive function\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
case 2:
xloc = Binary_search_rec(a,low,high,x);
if(xloc!=-1)
printf("%d is found at location %d by recursive function.\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
default:printf("Invalid choice.");
}
getch();
}

int Binary_search( int a[], int low, int high, int x)


{
int mid;
while(low<=high)
{
mid = (low+high)/2;
if(a[mid]==x)
return mid;
else if(x<a[mid])
high = mid - 1;
else
low = mid + 1;
}
return -1;
}

int Binary_search_rec( int a[], int low, int high, int x)


{
int mid;
if(high<low)
return -1;
mid=low + ((high-low)/2);
if(a[mid]>x)
return Binary_search_rec( a, low, mid-1, x);
else if(a[mid]<x)
return Binary_search_rec( a, mid+1, high,x);
else
return mid;
}
Output:
Ex. No: 3(C) Fibonacci Search Using Recursive & Non- recursive
Functions

Aim: Write C programs that use both recursive and non recursive functions to perform Fibonacci
search for a Key value in a given list.
Algorithm: /* Fibonacci search recursive and non-recursive */

Input: n, ser_val, a[50], l[50]


Output: found = true and loc = position of item if the search is successful;
otherwise, found is false.
Step 1: enter the choice for 1.recursive or 2. Nonrecursive to the integer variable ch
scanf ("%d",ch);
Step 2: if choice==1 call non-recurs ()
Step 3: if choice==2 call recurse ()
Step 4: else print wrong entry and go to main menu.
Step 5: stop
Algorithm for fibonacii search non-recurcive
Step 1: declare n,i,k,p,q,r,m,t,f0=0,f1=1,f2=1,item, found=0;
Step 2: keep first 3 elements of the fibonacii series in array a
a[0]=0;
a[1]=1;
a[2]=1;
Step 3: scan the size of the new list 'n'
scanf("%d",&n);
Step 4: store the elements of the new list in array l
for(i=0 to n)
scanf("%d",&l[i]);
Step 5: store the elemnt to be searhed in variable ITEM.
scanf("%d",&item);
Step 6: find the items for the fibonacii series [array a] upto size n
while( a[k]<n)
{ f0=f1; f1=f2;f2=f1+f0; k++;a[k]=f2;}
Step 7: store last but one three elements of fibonacii seriese in p,q,r
p=a[k-1]; q=a[k-2]; r=a[k-3];
Step 8: find m the difference between p+q and item
m=item+1-(p+q);
Step 9: compare item with pth element of new list if it is grater update p by adding m to it
if(item > l[p]) p=p+m;
Step 10: compare l[p] with item and find out the element
while((p!=0) && found==0)
{
Step 10.1: if equal print the position p+1*/
if(l[p]==item)
printf("element found in %d position",p+1);
Step 10.2: if item is less then pth element of new list update p, q, r with nearest possible
values
else if(item<l[p])
{
p=p-r;
t=q;
q=r;
r=t-r;
}
Step 10.3: if it is greater update with the nearest possible value
else
{
p=p+r;
q=q-r;
r=r-q;
}
Step 10.4: if(found==0)
printf(" key not present");
}
Step 11: stop
Algorithm fibonacii search recursive
Step 1: Declare k,n,i,p,q,r,m,f0=0,f1=1,f2=1,item;
Step 2: Initialize first three elements of the fibonacii seriese into array a.
a[0]=0;
a[1]=1;
a[2]=1;
Step 3: Scan the size of the new array as 'n'
scanf("%d",&n);
Step 4: Scan the elements of the array in which you want to search an element
for(i=0; i<n; i++)
scanf("%d",&l[i]);
Step 5: Store the item you want to search in the variable "item"
scanf("%d",&item);
Step 6: find the fibonacii seriese upto n
while(a[k]<n)
{
f0=f1;f1=f2;f2=f1+f0;
k++; a[k]=f2;
}
Step 7: Update p,q,r to the last but one three values of the fibonacii seriese
p=a[k-1];
q=a[k-2];
r=a[k-3];
Step 8: calculate m
m=item+1-(p+q);
Step 9: Update p if item<l[p]
if(item > l[p])
p=p+m;
Step 10: Call Fibonacii function to serch recursively
Fibsearch(n,item,p,q,r);
Step 11: stop

Agorithm for Fibsearch (int n, int item,int p, int q, int r)


Step 1: if(p<q) print "element not prsent ". exit.
Step 2: else if(l[p]==item) print "element found in p+1 position. exit.
Step 3: else if(item<l[p])
if(r==0) p=0;
else { p=p-r; t=q; q=r; r=t-r; }
Fibsearch(n,item,p,q,r);
Step 4: else if(item>l[p])
if(q==1) p=0;
else { p=p+r;q=q-r;r=r-q;}
Fibsearch(n,item,p,q,r);
Step 5: else if(p==0) print "element not found".
Step 6: stop.

Program:

#include<process.h>
#include<stdio.h>
#include<conio.h>
int a[100];
int l[100];
void non_recurs();
void recurs();
void Fibsearch(int, int, int, int, int);

void main()
{
int ch;
printf("enter your choice for reursive(1) or non-recursive(2) for fibonaci search");
scanf("%d",&ch) ;
switch(ch)
{

case 1: recurs();break;
case 2: non_recurs();break;
}
}
/*fibonacii search non-recurcive*/
void non_recurs()
{
int n,i,k,p,q,r,m,t,f0=0,f1=1,f2=1,item, found=0;
/*keep first 3 elements of the fibonacii series in array a*/
a[0]=0;
a[1]=1;
a[2]=1;
k=2;
/*scan the size of the new list 'n'*/
printf("\nit is a non-recursive program for fibonacii search");
printf("\nEnter the size of the array");
scanf("%d",&n);

/*store the elements of the new list in array l */


printf(" Enter the elements of the array ");
for(i=0; i<n; i++)
scanf("%d",&l[i]);
/*store the elemnt to be searhed in variable ITEM.*/
printf("\nEnter the item to be searched");
scanf("%d",&item);
/*find the items for the fibonacii seriese[array a] upto size n*/
while( a[k]<n)
{
f0=f1;
f1=f2;
f2=f1+f0;
k++;
a[k]=f2;
}
/*store last but one three elements of fibonacii seriese in p,q,r*/
p=a[k-1];
q=a[k-2];
r=a[k-3];
/*find m the difference between p+q and item*/
m=item+1-(p+q);
/*compare item with pth element of new list if it is grater update p by adding
m to it*/
if(item > l[p])
p=p+m;
/*compare l[p] with itemand find out the element*/
while((p!=0) && found==0)
{
/*if equal print the position p+1*/
if(l[p]==item)
{
printf("element found in %d position",p+1);
found=1;
}
/*if item is less then pth element of new list update p,q,r with nearest possible
values */
else if(item<l[p])
{
if(r==0)
p=0;
else
{
p=p-r;
t=q;
q=r;
r=t-r;
}
}
/*if it is grater update the with nearest possible value*/
else
{
if(q==1)
p=0;
else
{
p=p+r;
q=q-r;
r=r-q;
}
}
}
if(found==0)
printf(" key not present");
} /*fibonacii search recursive*/
void Fibsearch(int n,int item,int p, int q, int r)
{
int t;
if(p<q)
{
printf("element not prsent ");
return;
}
else if(l[p]==item)
{
printf("element found in %d position",p+1);
return;
}
else if(item<l[p])
{
if(r==0)
p=0;
else
{
p=p-r;
t=q;
q=r;
r=t-r;
}
Fibsearch(n,item,p,q,r);
}
else if(item>l[p])
{
if(q==1)
p=0;
else
{
p=p+r;
q=q-r;
r=r-q;
}
Fibsearch(n,item,p,q,r);
}
else if(p==0)
{
printf("element not found");
}
}
void recurs(void)
{
int k,n,i,p,q,r,m,f0=0,f1=1,f2=1,item;

a[0]=0;
a[1]=1;
a[2]=1;
k=2;
printf("it is a recursive program for fibonacii search");
printf("Enter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements of the array ");
for(i=0; i<n; i++)
scanf("%d",&l[i]);
printf("\nEnter the item to be searched");
scanf("%d",&item);
while(a[k]<n)
{
f0=f1;
f1=f2;
f2=f1+f0;
k++;
a[k]=f2;
}
p=a[k-1];
q=a[k-2];
r=a[k-3];
m=item+1-(p+q);
if(item > l[p])
p=p+m;
Fibsearch(n,item,p,q,r);
}

Output:
EX. NO: 4(A) BUBBLE SORT

Aim: Write C programs that implement Bubble sort, to sort a given list of integers in
ascending order
Algorithm:
/* Bubble_ Sort */

Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: repeat step 6 for i: from 0 to n-1
Step 6: repeat step 7 for j: from 0 to n-1-i
Step 7: if a[j+1] < a[j] perform steps 8 to 10
Step 8: temp  a[j+1]
Step 9: a[j+1]  a[j]
Step 10: a[j]  temp
Step 11: repeat step 12 for i: from 0 to n-1
Step 12: print a[i]
Step 13: Stop

Program:

/* Program to sort a given list of integers using Bubble sort */


#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,j,n,temp;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n-1;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("After sorting, the element are\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}

Output:
EX. NO: 4 (B) QUICK SORT

Aim:

Write C programs that implement Quick sort, to sort a given list of integers in ascending order
Algorithm:
/* Quick_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

Step 1: Start
Step 2: read n // n number of elements
Step 3: repeat step4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: call sub routine quick_sort(a, 0, n-1)
Step 6: repeat step7 for i: from 0 to n-1
Step 7: print a[i]
Step 8: Stop

Algorithm for swap(int a[], int i, int j)


Step 1: begin
Step 2: tempa[i]
Step 3: a[i] a[j]
Step 4: a[j]temp
Step 5: end

Algorithm for quick_sort(int list[], int first, int last)


Step 1: begin
Step 2: if (first<last) then go to step3 else go to step16
Step 3: pivota[first]
Step4: ifirst
Step5: jlast
Step6: repeat steps from 7 to 12 if (i<j) else go to step13
Step 7: repeat step8 if (a[i]<= pivot && i<last)
Step 8: ii+1
Step 9: repeat step10 if (a[j]>=pivot && j>first)
Step 10: j j-1
Step 11: if(i<j) then go to step12 else go to step13
Step 12: call sub-routine swap (a, i, j)
Step 13: call sub-routine swap (a, first, j)
Step 14: call sub-routine quick (a,first,j-1)
Step 15: call sub-routine quick(a, j+1, last)
Step 16: end
Program:

#include<stdio.h>
#include<conio.h>
int i,j,n,pivot,a[20];
void quick(int a[],int left,int right);
void swap(int a[],int i,int j);
void main()
{
int n,a[20];
clrscr();
printf("\n\nQUICK SORT");
printf("\n\nEnter the array size");
scanf("%d",&n);
printf("\n\nEnter the element\n\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick(a,0,n-1);
printf("\n\nThe sorted list is \n\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot&&i<last)
i++;
while(a[j]>=pivot&&j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void swap(int a[],int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}

Output:
EX. NO: 4 (C) INSERTION SORT

Aim:

Write C programs that implement Insertion sort, to sort a given list of integers in ascending
order

Algorithm:
/* Insertion_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: repeat steps 6 to 10 for j: from 1 to n-1
Step 6: key  a[i]
Step 7: j  i-1
Step 8: repeat step 9 while j >= 0 and a[j] > x
Step 9: a[j+1] a[j--]
Step 10: a[j+1]  x
Step 11: for i: 0 to n-1
Step 12: print a[i]
Step 13: Stop

Program:

#include <stdio.h>
#include<conio.h>
void main()
{
void insertion_sort(int [],int);
int A[100];
int x=0,n=0;
int key,i,j;
clrscr();
printf("******INSERTION SORT******");
printf("\n\nENTER THE LIMIT : ");
scanf("%d",&n);
printf("\n\nENTER THE ELEMENTS ONE BY ONE\n\n");
for(x=0;x<n;x++)
scanf("%d",&A[x]);
printf("\n\nNON SORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\t%d",A[x]);
}
for(j=1;j<n;j++)
{
key=A[j];
i=j-1;
while(A[i]>key && i>=0)
{
A[i+1]=A[i];
i--;
}
A[i+1]=key;
}
printf("\n\nSORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\t%d",A[x]);
}
getch();
}

Output:
EX. NO: 5 (A) HEAP SORT

Aim: Write C programs that implement heap sort, to sort a given list of integers in
ascending order

Algorithm: /* Heap_ Sort */


Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

BUILD_HEAP (A)
heap-size (A) ← length [A]
For i ← floor(length[A]/2) down to 1 do
Heapify (A, i)

HEAPSORT (A)
BUILD_HEAP (A)
for i ← length (A) down to 2 do
exchange A[1] ↔ A[i]
heap-size [A] ← heap-size [A] - 1
Heapify (A, 1)

function heapSort(a, count) is


input: an unordered array a of length count

(first place a in max-heap order)


heapify(a, count)

end := count-1 //in languages with zero-based arrays the children are 2*i+1 and 2*i+2
while end > 0 do
(swap the root(maximum value) of the heap with the last element of the heap)
swap(a[end], a[0]) (put the heap back in max-heap order)
siftDown(a, 0, end- (decrease the size of the heap by one so that the previous
max value will stay in its proper placement)
end := end - 1
function heapify(a, count) is
(start is assigned the index in a of the last parent node)
start := count / 2 - 1

while start ≥ 0 do (sift down the node at index start to the proper place such
that all nodes below the start index are in heap order)
siftDown(a, start, count-1)
start := start - 1
(after sifting down the root all nodes/elements are in heap order)

function siftDown(a, start, end) is


input: end represents the limit of how far down the heap
to sift.
root := start

while root * 2 + 1 ≤ end do (While the root has at least one child)
child := root * 2 + 1 (root*2 + 1 points to the left child)
swap := root (keeps track of child to swap with)
(check if root is smaller than left child)
if a[swap] < a[child]
swap := child
(check if right child exists, and if it's bigger than what we're currently swapping with)
if child+1 ≤ end and a[swap] < a[child+1]
swap := child + 1
(check if we need to swap at all)
if swap != root
swap(a[root], a[swap])
root := swap (repeat to continue sifting down the child now)
else
return

Program:
#include<stdio.h>
#include<conio.h>
void heapsort( int arr[], int count);
void makeheap( int arr[], int count);
int main()
{
int a[20],i,j,n,temp,k;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
makeheap( a,n)
heapsort(a,n ) ;
printf("After sorting, the element are\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
return 0;
}

void makeheap( int arr[], int count)


{
for ( int i = 1 ; i < count ; i++ )
{
int val = arr[i] ;
int s = i ;
int f = ( s - 1 ) / 2 ;
while ( s > 0 && arr[f] < val )
{
arr[s] = arr[f] ;
s=f;
f=(s-1)/2;
}
arr[s] = val ;
}
}

void heapsort( int arr[], int count)


{
int i;
for (i = count - 1 ; i > 0 ; i-- )
{
int ivalue = arr[i] ;
arr[i] = arr[0] ;
int f = 0 ;
int s ;
if ( i == 1 )
s = -1 ;
else
s=1;
if ( i > 2 && arr[2] > arr[1] )
s=2;
while ( s >= 0 && ivalue < arr[s] )
{ arr[f] = arr[s] ;
f=s;
s = 2*f+ 1 ;
if ( s + 1 <= i - 1 && arr[s] < arr[s + 1] )
s++ ;
if ( s > i - 1 )
s = -1 ;
}
arr[f] = ivalue ;
}
}

Output:
EX. NO: 5 (B) RADIX SORT

Aim: Write C programs that implement radix sort, to sort a given list of integers in ascending
order
Algorithm: /* Radix_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

radixsort( L, n, r, d )
/* radix sort sorts a list L of n keys, each comprising d digits with radix r * */
Initialize each of the Q[0:r-1] linked queues representing the bins to be empty;
For i = d to 1 step -1 /* for each of the d passes over the list */
Sort the list L of n keys Ki=k1k2k3…..kd based on the digit i, inserting each of the keys K into
the linked queue Q [ ki ], 0 ≤ ki < r ; /* distribute the keys into Q [ 0 : (r-`) ] based on the
radix value of the digits */
Delete the keys from the queues Q [ 0: r-1 ] in order, and append the elements to the output
list L;
end;
Return ( L );
end radixsort.

Algorithm:
Step 1: set LARGE = large element in the array
Step 2: set NUM=total no of digits in the largest element of the array
Step 3: set DIGIT = NUM
Step 4: set PASS = 1
Step 5: repeat steps 6 to 12 while PASS <= NUM
Step 6: Initialize buckets
Step 7: set i=0
Step 8: repeate steps 9 to 11 while i<=n-1
Step 9: Set l=PASS-1 , position of number a[i] [0th position of number 123 is 3]
Step 10: put the number a[i] in the bucket l
Step 11: set i=i+1 [end of step 8 loop]
Step 12: set PASS=PASS+1 [end of step 5 loop]
Step 13: write all the numbers from the bucket in order
Step 14: stop.

Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void radix(int a[],int n,int m)
{
typedef struct node
{
int data;
struct node * next;
}NODE;
NODE * ptr,*start,*prev;
NODE *front[10], *rear[10];
int k=1,i,j,y,p;;
/*creating initial linked list*/
start=NULL;
for(i=0;i< n;++i)
{
ptr=(NODE *)malloc(sizeof(NODE));
ptr->data=a[i];
ptr->next=NULL;
if(start==NULL)
start=ptr;
else
prev->next=ptr;
prev=ptr;
}
/*radix sort*/
for(i=1;i<=m;++i)
{
for(j=0;j< 10;++j)
front[j]=NULL;
/*placing elements into queues*/
ptr=start;
while(ptr!=NULL)
{y=ptr->data/k %10;/*y is the digit*/
if(front[y]==NULL)
{
front[y]=ptr;
rear[y]=ptr;
}
else
{
rear[y]->next=ptr;
rear[y]=ptr;
}
ptr=ptr->next;
}
start=NULL;
for(j=0;j< 10;++j)
if(front[j]!=NULL)
{
if(start==NULL)
start=front[j];
else rear[p]->next=front[j];
p=j;
}
rear[p]->next=NULL;
k=k*10;
}
/*copying back to array*/
ptr=start;
for(i=0;i< n;++i,ptr=ptr->next)
a[i]=ptr->data;
}
void main()
{
int a[100],n,i,m;
char temp;
do
{
clrscr();
printf("===========================RADIX
SORT===========================================\n");
printf("ENTER NUMBER OF NUMBERS AND NUMBER OF DIGITS\n");
scanf("%d%d",&n,&m);
printf("ENTER ELEMENTS\n");
for(i=0;i< n;++i)
scanf("%d",&a[i]);
radix(a,n,m);
printf("SORTED LIST\n");
for(i=0;i< n;++i)
printf("%d ",a[i]);
printf("\nDO YOU wish to continue?[y/n]\n");
scanf("%c",&temp);
}while(temp=='y'|| temp=='Y');
printf("\n \n");
getch();
}

Output:
EX. NO: 5 (C) MERGE SORT

Aim: Write C programs that implement merge sort, to sort a given list of integers in
ascending order
Algorithm: /* Merge_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array

Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: call function merge_sort(a, 0, n-1)
Step 6: repeat step 9 while j >= 0 and a[j] > x
Step 7: print a[i]
Step 8: Stop

Algorithm for function merge_sort(int x[], int start, int end)


Step 1: begin
Step 2: n(end-start)+1
Step 3: if (end= =start)
Step 4: return
Step 5: mid(end+start)/2
Step 6: merge_sort(x, start, mid)
Step 7: merge_sort(x, mid+1, end)
Step 8: repeat step 9 until j< n
Step 9: ex[j]x[start+1]
Step 10: mrg1  0, mrg2  (mid-start)+1
Step 11: repeat steps until j<n
Step 12: if (mgr2<=end-start)
Step 13: if(mrg1<=mid-start)
Step 14: if(ex[mrg1]>ex[mrg2])
Step 15: x[j+start]ex[mrg2++]
Step 16: else
Step 17: x[j+start]ex[mrg1++]
Step 18: else
Step 19: x[j+start]ex[mrg2++]
Step 20: else
Step 21: x[j+start]ex[mrg1++]
Step 22: end

Program:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[], int low, int high);
void merge(int a[], int low, int high, int mid);
int main()
{
int a[20],i,n;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort( a,0,n-1);
printf("After sorting, the element are\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
return 0;
}
void mergesort(int a[], int low, int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
return;
}
void merge(int a[], int low, int high, int mid)
{
int i, j, k, c[50];
i=low;
j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<a[j])
{
c[k]=a[i];
k++;
i++;
}
else
{
c[k]=a[j];
k++;
j++;
}
}
while(i<=mid)
{
c[k]=a[i];
k++;
i++;
}
while(j<=high)
{
c[k]=a[j];
k++;
j++;
}
for(i=low;i<k;i++)
{
a[i]=c[i];
}
}

Output:
EX. NO: 6 (A) STACK USING ARRAY

Aim: Write C programs that implement stack (its operations) using arrays

Algorithm: /* Stack_Array */
Input: int a[size], top, i, ch
Output:
Define size 20
top = -1
Step 1: Start
Step 2: do
Step 3: print choice [1] push. [2] pop. [3] display. [4] exit
Step 4: read choice ch
Step 5: switch ch
Step 6: case 1: call sub-routine push()
Step 7: break
Step 8: case 2: call sub-routine pop()
Step 9: break
Step 10: case 3: call sub-routine disp()
Step 11: break
Step 12: case 4: break
Step 13: default: print invalid choice
Step 14: read choice
Step 15: while ch! = 4
Step 16: Stop
Algorithm for sub routine push()
Step 1: begin
Step 2: if top equal to size-1
Step 3: print ‘Stack over flow’
Step 4: else
Step 5: top top+1
Step 6: read a[top]
Step 7: end
Algorithm for sub routine pop()
Step 1: begin
Step 2: if top equal to -1
Step 3: print ‘stack under flow’
Step 4: else
Step 5: print ‘popped element is a[top]
Step 6: top top-1
Step 7: end
Algorithm for sub routine disp()
Step 1: begin
Step 2: if top equal to -1
Step 3: print ‘ Stack is empty’
Step 4: else
Step 5: repeat step 6 for: i from top to 0
Step 6: print a[i]
Step 7: end
Program:
#include<stdio.h>
#include<process.h>
#include<conio.h>
#define SIZE 3
int stack[SIZE], top=-1;
void push(int);
void pop(void);
int topmost(void);
void display();
void main()
{
int item, ch;
clrscr();
while(1)
{
printf("\n1.push");
printf("\n2.pop");
printf("\n3.Top ELEMENT");
printf("\n4.display");
printf("\n5.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element to be pushed\n");
scanf("%d",&item);
push(item);
printf("\nPress enter");
getch();
break;
case 2: pop();
printf("\nPress enter");
getch();
break;
case 3: item=topmost();
printf("\n Topmost element is %d", item);
printf("\nPress enter");
getch();
break;
case 4: display();
printf("\nPress enter");
getch();
break;
default : exit(0);
}
}
}
void push(int i)
{
if(top==(SIZE-1))
{
printf("\nStack Overflow");
return;
}
top=top+1;
stack[top]=i;
}
void pop()
{
int i;
if(top==-1)
{
printf("\nStack Underflow");
return;
}
i=stack[top];
top=top-1;
printf("\nDeleted item is %d",i);
return;
}
int topmost()
{
return stack[top];
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty");
return;
}
printf("\nContents of the stack are\n");
for(i=top;i>=0;i--)
printf("%d\t",stack[i]);
}
Output:
EX. NO: 6 (B) STACK USING LINKED LISTS
Aim: Write C programs that implement stack (its operations) using Linked list

Algorithm: /* Stack_ Pointers */


Input: char ch;
Output:

define struct stack


int item
struct stack *next
typedef struct stack node
node *top  NULL
Step 1: start
Step 2: do
Step 3: print choice [1] push. [2] pop. [3] display. [4] exit
Step 4: read choice ch
Step 5: switch ch
Step 6: case 1: call sub-routine push()
Step 7: break
Step 8: case 2: call sub-routine pop()
Step 9: break
Step 10: case 3: call sub-routine disp()
Step 11: break
Step 12: case 4: break
Step 13: default: print invalid choice
Step 14: read choice
Step 15: while ch!=4
Step 16: stop

Algorithm for sub routine push()


Step 1: begin
Step 2: declare node *tmp, int pitem
Step 3: tmp= (node *) malloc(sizeof(node))
Step 4: read pitem
Step 5: tmp->item=pitem
Step 6: tmp->next = top
Step 7: toptmp
Step 8: end

Algorithm for sub routine pop()


Step 1: begin
Step 2: declare node *tmp
Step 3: if top = = NULL
Step 4: print ‘ Stack is empty’
Step 5: else
Step 6: tmp  top
Step 7: toptop->next
Step 8: free (tmp)
Step 9: end
Algorithm for sub routine disp()
Step 1: begin
Step 2: declare node *ptr
Step 3: ptrtop
Step 4: if ptr equal to NULL
Step 5: print ‘ Stack is empty’
Step 6: else
Step 7: repeat steps 8 and 9 until ptr!=NULL
Step 8: print ptr-> item
Step 9: ptrptr-> next
Step 10: end
Program:
//Write C programs that implement stack (its operations) using Linked list
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct stack
{ int info;
struct stack *next;
};
void push(int);
void pop(void);
int topmost(void);
void display();
struct stack *getnode(int x); /* pointer declaration to point to the top of the stack */
struct stack *top;
void main()
{
int item, ch;
top = NULL;
clrscr();
while(1)
{
printf("\n1.push");
printf("\n2.pop");
printf("\n3.Top ELEMENT");
printf("\n4.display");
printf("\n5.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element to be pushed\n");
scanf("%d",&item);
push(item);
printf("\nPress enter");
getch();
break;
case 2: pop();
printf("\nPress enter");
getch();
break;
case 3: item=topmost();
printf("\n Topmost element is %d",item);
printf("\nPress enter");
getch();
break;
case 4: display();
printf("\nPress enter");
getch();
break;

default : exit(0);
}
}
}
void push( int x)
{
struct stack *p;
p = getnode(x );
/* checking for an empty stack */
if ( top == NULL)
{
top = p;
}
else
{
p->next = top;
top = p;
}
} /* end of push( )*/

struct stack *getnode(int x)


{
struct stack *p;
p=(struct stack *) malloc(sizeof(struct stack));
p->info=x;
p->next = NULL;
return(p);
}
void pop( void)
{
struct stack *temp;
int x; /* check for an empty stack */
if (top == NULL)
{
printf ("Cannot remove nodes from an empty stack");
getch();
}
else
{
temp = top;
x = top->info;
top = top->next;
free( temp);
printf("\nDeleted item is %d",x);
return;
}
}
int topmost( void)
{
return top->info;
}

void display()
{
struct stack *p;
p=top;
if (top == NULL)
{
printf("\nStack is Empty");
return;
}
printf("\nContents of the stack are\n");
for(p=top; p!= NULL; p=p->next)
printf("%d\t",p->info);
}

Output:
EX. NO: 7(A) CONVERT INFIX EXPRESSION INTO POSTFIX EXPRESSION

Aim: Write a C program that uses Stack operations to convert infix expression into postfix
expression
Algorithm: /* Infix_to_Postfix */
Input:
Output:
Define size 20
declare char a[size], integer top  -1

Step 1: Start
Step 4: declare integer i, j0, n,u,v; char infix[size], postfix[size]
Step 5: read infix expression
Step 6: nstring length (infix)
Step 7: repeat steps 8 to 20 for i : from 0 to n-1
Step 8: if ((infix[i]>=’a’ && infix[i]<=’z’) || (infix[i]>=’A’ && infix[i]>=’Z’))
Step 9: postfix[j] infix[i];
Step 10: j  j+1
Step 11: else if (infix[i]= = ‘*’ || infix[i]= = ‘/’|| infix[i]= = ‘+’|| infix[i]= = ‘-’)
Step 12: if top = = -1 then go to step13 else go to step14
Step 13: push(a[i])
Step 14: ucall sub routine preced(a[top])
Step 15: v call sub routine preced(infix[i])
Step 16: repeat steps 17 to 19 while v<=u
Step 17: postfix[j]  pop()
Step 18: j++
Step 19: u  preced(a[top]) // end of while
Step 20: push(in[i]) //end of else //end of for
Step 21: repeat steps 22, 23 while top!=-1
Step 22: post[j]pop()
Step 23: jj+1
Step 24: post[j]’\0’
Step 25: print ‘post string’, post
Step 26: end
Algorithm for sub routine push(char c)
Step 1: begin
Step 2: top+1
Step 3: a[top]c
Step 4: end
Algorithm for sub routine pop()
Step 1: begin
Step 2: char vala[top]
Step 3: top-1
Step 4: return(val)
Step 5: end
Algorithm for sub routine preced(char c)
Step 1: begin
Step 2: switch ch
Step 3: case ‘*’:
Step 4: case ‘/’: v2
Step 5: break
Step 6: case ‘+’:
Step 7: case ‘-‘ : v1
Step 8: break
Step 9: default: v0
Step 10: break
Step 11: return (v)
Step 12: end

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
char stack[MAX];
int top=-1;
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
break;
case '*':
case '/':return 4;
break;
case '^':
case '$':return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':return 1;
break;
default:return 0;
}
}

void convertip(char infix[],char postfix[])


{
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else {
if(symbol=='(')push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();//pop out (.
}
else{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';//null terminate string.
}
void main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,postfix);
printf("The corresponding postfix string is:\n");
puts(postfix);
getch();
}

void push(char item)


{
top++;
stack[top]=item;
}

char pop()
{
char a;
a=stack[top];
top--;
return a;
}

Output:
EX. NO: 7(B) QUEUE USING LINKED LISTS

Aim: Write C programs that implement Queue (its operations) using linked lists

Algorithm: /* Queue_ Pointers */


Input:
Output:
struct queue
int item
struct queue *next
typedef struct queue node
node * front  NULL
node * rear  NULL
Step 1: start
Step 2: do
Step 3: print choice [1] enqueue. [2] dequeue. [3] display. [4] exit
Step 4: read choice ch
Step 5: switch ch
Step 6: case 1: call sub-routine enque()
Step 7: break
Step 8: case 2: call sub-routine deque()
Step 9: break
Step 10: case 3: call sub-routine disp()
Step 11: break
Step 12: case 4: break
Step 13: default: print invalid choice
Step 14: read choice
Step 15: while ch!=4
Step 16: stop
Algorithm for sub routine enque()
Step 1: begin
Step 2: declare node *temp
Step 3: temp (node *) malloc(sizeof(node))
Step 4: read qitem
Step 5: temp->item  qitem
Step 6: temp->next  NULL
Step 7: if front = = NULL
Step 8: front  temp
Step 9: else
Step 10: rear->next  temp
Step 11: rear  temp
Step 12: end
Algorithm for sub routine deque()
Step 1: begin
Step 2: declare node *temp
Step 3: if front equal to NULL
Step 4: print ‘Queue is empty’
Step 5: else
Step 6: temp  front
Step 7: front  p->next
Step 8: if front equal to NULL
Step 9: rearNULL
Step 10: free(temp)
Step 11: end
Algorithm for sub routine disp()
Step 1: begin
Step 2: declare node *temp
Step 3: temp  front
Step 4: if(temp = = NULL)
Step 5: print “queue is empty’
Step 6: else
Step 7: while (temp->next!=NULL)
Step 8: print temp->item
Step 9: temp  temp->next
Step 10: end

Program:
/*Queue Using Linked List*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node
{
int info;
struct node* next;
}*front,*rear;
void enqueue(int elt);
int dequeue();
void display();
void first(void);
void last(void);
void main()
{
int ch,elt;
rear=NULL;
front=NULL;
clrscr();
while(1)
{
printf("\nEnter:\n1->Insert\n2->Delete\n3->Display\n4->First\n5->Last\n6->Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter The Element Value\n");
scanf("%d",&elt);
enqueue(elt);
break;
case 2:
elt=dequeue();
printf("The deleted element = %d\n",elt);
break;
case 3:
display();
break;
case 4:
first();
break;
case 5:
last();
break;
default:
printf("~~~Exit~~~");
getch();
return;
}} }
void enqueue(int elt)
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->info=elt;
p- >next=NULL;

if(rear==NULL||front==NULL)
front=p;
else
rear->next=p;
rear=p;
}
int dequeue()
{
struct node *p;
int elt;
if(front==NULL||rear==NULL)
{
printf("\nUnder Flow");
getch();
exit(0);
}
else
{
p=front;
elt=p->info;
front=front->next;
free(p);
}
return(elt);
}
void display()
{
struct node *t;
t=front;
printf("Queue content :\n");
while(t){
printf("\t%d",t->info);
t=t->next;
}
getch();
}
void first (void){
if(front)
printf("First Element is%d;",front->info);
}
void last (void){
if(rear)
printf("Last Element is%d;",rear->info);
}
Output:
EX. NO: 8 (A) CREATING A SINGLE LINKED LIST
Aim: Write a C program that uses functions to create a singly linked list
Algorithm:
/* Singly_linkedlist */
Input:
Output:
declare struct linkedlist
integer data
struct linkedlist *next

typedef struct linkedlist node;

Step 1: Start
Step 2: int num, loc; char ch; node start=NULL;
Step 3: repeat steps 4 to 6 until ch!=’5’
Step 4: print ‘1. insert 2. display 3. exit’
Step 5: read choice ch
Step 6: switch (ch)
case 1: read num
insert(&start,num)
break;
case 2: disp(&start)
break
case 3: exit
break
default: print ‘invalid choice’
break
Step 8: Stop

Algorithm to insert()
Step1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
If new==NULL print overflow; return;
Step 3: if memory available keeps the new element value in the node
else new->info=item;
Step 4:-traverse upto the last node
ptr=start;
while(ptr->next != NULL) ptr=ptr->next
Step 5: insert the new node with new information at the end
ptr->next=new;
new->next=NULL
Step 6: stop
Algorithm to display()
Step 1: if(first==NULL) then
printf("LIST EMPTY\n");
return;
Step 2: print ‘The contents of the list are’
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
Step 3: stop.

Program:
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void insert(int i)
{
NODE temp,cur;
temp=getnode();
temp->info=i;
temp->link=NULL;
if(first==NULL)
first=temp;
else
{
cur=first;
while(cur->link!=NULL)
cur=cur->link;
cur->link=temp;
}
return;
}
void main()
{
int ch,i;
clrscr();
for(;;)
{
printf("1.insert\n");
printf("2.display\n");
printf("3.exit\n");
printf("Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
printf("Enter the item to be inserted");
scanf("%d",&i);
insert(i);
getch();
break;
case 2 :
display();
getch();
break;
case 3: exit(0);
default :exit(0);
}
}
}

Output:
EX. NO: 8 (B) INSERTION OPERATIONS ON A SINGLY LINKED LIST

Aim: Write a C program that uses functions to perform insertion operation on a singly
linked list

Algorithm:
Algorithm to create a single linked list: create ()
Step 1: create a data type for the linked list
struct llist
{ int info; struct llist *next; };
Step 2: create a node
struct llist *start,*ptr;
strat= (struct llist *)malloc(sizeof(Struct llist));
ptr=start;/*ptr is taken to help in traversing*/
Step 3: stop

Algorithm to insert a node a single linked list:


/*Algorithm for main function:*/
Step 1:ask the user where to insert
1. At the beginning
2. At the end
3. After nth node
Step 2: scan the option “choice”
scanf(“%d”,&choice);
Step 3: if choice==1 call insert_at_beg();
else if choice==2 call insert_at_end();
Else if choice==1 call insert_after_n();
Step 4: stop

Algorithm to insert at athe beginning: insert_at_beg()


Step1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
if new==NULL print overflow; return;
Step 3: if memory available keep the new element value in the node
else new->info=item;
Step 4:insert the new node at the beginning
new->next=start; start=new

Algorithm to insert at the end: insert_at_end()


Step1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
If new==NULL print overflow; return;
Step 3: if memory available keep the new element value in the node
else new->info=item;
Step 4:-traverse upto the last node
ptr=start;
while(ptr->next != NULL) ptr=ptr->next
Step 5: insert the new node with new information at the end
ptr->next=new;
new->next=NULL
Step 6: stop

Algorithm to insert after a node: insert_after_n()


Step1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
if new==NULL print overflow; return;
Step 3: if memory available keep the new element value in the node
else new->info=item;
Step 4: While(count<=n){ptr=ptr->next; count++}
Step 5: insert the new node after the nth node
new->next=ptr->next
ptr->next=new
Step 6:stop

Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode(int i)
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
x->info=i;
return x;
}

void Insert(int k, int x)


{ // Insert x after the k'th element.
if (k < 0) printf("Position is not proper");

// p will eventually point to k'th node


NODE temp,p = first;
for (int index = 1; index < k && p; index++) // move p to k'th
p = p->link;
if (k > 0 && !p)
{
printf(" k'th insert not possible ");
return;
}
NODE y = getnode(x);
y->link=NULL;
if (k) {// insert after p
y->link = p->link;
p->link = y;}
else {// insert as first element
y->link = first;
first = y;}
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void main()
{
int x,pos,i=1;
NODE p;
int n,ch;
clrscr();
for(;;)
{
printf("1.insert at the Beginning\n");
printf("2. insert at the End\n");
printf("3. insert after the kth position\n");
printf("4.display\n");
printf("5.exit\n");
printf("Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
printf("Enter the item to be inserted");
scanf("%d",&i);
p=getnode(i);
p->link=first;
first=p;
break;
case 2 :
printf("Enter the item to be inserted");
scanf("%d",&i);
if(first)
{
for(p=first; p->link; p=p->link);
p->link=getnode(i);
p=p->link;
p- >link=NULL;
}
else
{
first=getnode(i);
first->link=NULL;
}
break;
case 3 : i=1;
printf("Enter how many elements to be inserted");
scanf("%d",&n);
while(i<=n)
{
printf("Enter the Position and element to be inserted");
scanf("%d%d",&pos,&x);
Insert(pos,x);
i++;
}
break;
case 4 :
display();
break;
default :exit(0);
}
}
}

Output:
EX. NO: 8(C) DELETION OPERATIONS ON A SINGLY LINKED LIST

Aim:Write a C program that uses functions to perform deletion operation on a singly linked
list

Algorithm:
create a data type for the linked list
struct llist
{ int info; struct llist *next; };
create a node
struct llist *start,*ptr;
strat= (struct llist *)malloc(sizeof(Struct llist));
ptr=start;/*ptr is taken to help in traversing*/

Algorithm for main function


Step 1: create a list call create ()
Step 2: ask the user from where to delete
1. At the beginning
2. At the end
3. After nth node
Step 3: scan the option “choice”
scanf(“%d”,&choice);
Step 4: if choice==1 call delete_at_beg();
else if choice==2 call delete_at_end();
else if choice==1 call delete_after_n();
Step 5: stop

Algorithm to getnode(int info)


Step 1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
if new==NULL print overflow; return;
Step 3: if memory available keeps the new element value in the node
else new->info=item;
Step 4: new->next=null
Step 5: return new

Algorithm to create a single linked list: create ()


Step 1: print ‘Enter the no of elements’
Step 2: read n
Step 3: print ‘Enter the Elements’
Step 4: read x
Step 5: first=getnode(x)
Step 6: first->link=NULL
Step 7: i=2
Step 8: repeat the steps until (i<=n)
{
i++
read x
temp=getnode(x)
temp->link=first
first=temp
}
Step 9: stop

Algorithm to delete the first node


Step 1: keep the information of the node to be deleted in a different variable ‘item’
item=start->info;
Step2: increament the start pointer to the second node
start=start->next
Step 3: display the deleted item
Print: item
Step 4:stop

Algorithm to delete the nth node


Step 1:traverse upto (n-1)th node
count=1; ptr =start;
while(count<n){ptr=ptr->next; count++}
Step 2: keep the information of the node to be deleted in a different variable ‘item’
item=ptr->next->info;
Step 3: delete the nth node
Ptr->next=ptr->next->next
Step 4: display the deleted item
print: item

Algorithm to delete the last node


Step 1:traverse upto the last node
ptr=ptr1=start;
while(ptr->next != NULL)
{Ptr1=ptr;ptr=ptr->next;}
Step 2: keep the information of the node to be deleted in a different variable ‘item’
item=ptr->info;
Step 3: delete the last node
ptr1->next=NULL;
Step 4: display the deleted item
Print: item

Algorithm for subroutine disp(node *sptr)


Step 1: begin
Step 2: if sptr== NULL
Step 3: print ‘list is empty’
Step 4: else
Step 5: repeat steps 6, 7 until sptr!= NULL
Step 6: print sptr-> data
Step 7: sptrsptr->next
Step 8: end
Program:
include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;

NODE getnode(int i)
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
x->info=i;
x->link=NULL;
return x;
}
void create(void)
{
int n,i,x;
NODE temp;
printf(" Enter the no of elements");
scanf("%d",&n);
printf("Enter the Elements");
scanf("%d",&x);
first=getnode(x);
first->link=NULL;
i=2;
while(i<=n)
{
i++;
scanf("%d",&x);
temp=getnode(x);
temp->link=first;
first=temp;
}
}

void EleDelete(int x)
{// Delete element x of linked list
//p will eventually point to node having value x
NODE p = first;
NODE q = first;
while(p && p->info!=x)
{
q=p;
p=p->link;
}
if(!p)
printf("no element");
else
{
if(p==first)
first=p->link;
else
q->link = p->link; // remove from linked list
free(p);
}
return;
}
void Delete(int k, int &x) {// Delete k'th element of chain.
if (k < 1 || !first) printf("no k'th element"); // p will eventually point to k'th node
NODE q,p = first; // move p to k'th & remove from chain
if (k == 1) // p already at k'th
first = first->link; // remove
else { // use q to get to k-1'st
q = first;
for (int index = 1; index < k - 1 && q; index++)
q = q->link;
if (!q || !q->link)
printf("no k'th element");
p = q->link; // k'th
q->link = p->link;
} // remove from chain
// save k'th element and free node p
x = p->info;
printf("Deleted element %d\n",x);
free(p);
return;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void main()
{
int ch,x,pos;
NODE p, q;
clrscr();
create();
for(;;)
{
printf("\n1.Delete first element\n");
printf("2. Delete last element \n");
printf("3. Delete the kth element\n");
printf("4. Delete the element e from list\n");
printf("5.display\n");
printf("6.exit\n");
printf("Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
if(first){
p=first;
x=p->info;
first=p->link;
printf("Deleted item is %d",x);
free(p);
}
else
printf("Deletion is not possible");
break;
case 2 :
if(first)
{
q=first;
for(p=first; p->link; p=p->link)
q=p;
x=p->info;
printf("Deleted item is %d",x);
q->link=NULL;
if(p==first)
first=NULL;
free(p);
}
else
{
printf("Deletion is not possible");
}
break;
case 3 :
printf("Enter the Position");
scanf("%d",&pos);
Delete(pos,x);
break;
case 4 :
printf("Enter the element to be deleted");
scanf("%d",&x);
EleDelete(x);
break;
case 5 :
display();
break;
default :exit(0);
}
}
}

Output:
EX. NO: 9(A) ADDITION OF TWO LARGE INTEGERS USING LINKED LIST

Aim: Write a C program for adding two large integers which are represented in linked list fashion.
Algorithm: /* Addition Of Two Large Integers Using Linked List */
Program:
/* Program for adding two large integers which are represented in linked list fashion. */
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void main()
{
node *head1,*head2,*head3,*temp1,*temp2;
node *get_node();
node *read_num(node *head1);
void Sum(node *head1,node *head2,node *head3);
void display_num(node *temp,node *head);
clrscr();
head1=get_node(); /*Allocating memory for header nodes*/
head2=get_node();
head3=get_node();
head1->next=head1;
head2->next=head2;
head3->next=head3; /*-999 is representing the last node */
head1->data=head2->data=head3->data=-999;
printf("\n Press ENTER key to terminate the number ... \n");
printf("\n Enter First number: ");
temp1=read_num(head1);
printf("\n Enter Second number: ");
temp2=read_num(head2);
printf("\n First Number is \n");
display_num(temp1,head1);
printf("\n Second Number is \n");
display_num(temp2,head2);
printf("\n The addition of two long integers is ... \n");
Sum(temp1,temp2,head3);
getch();
}
node *get_node()
{
node *New;
New=(node*)malloc(sizeof(node));
New->next=NULL;
return New;
}
node *read_num(node *head)
{
char ch;
int flag=1;
node *New,*temp;
while((ch=getchar())!='\n')
{
New=get_node(); /*converting characters to its equivalent value */
ch=ch-'0';
New->data=ch;
if(flag==1) /*creation of first node*/
{
New->next=head;
temp=New;
flag=0; /*first node is created*/
}
else
{
New->next=temp; /*making the list circular*/
temp=New;
}
}
return temp;
}
void Sum(node *head1,node *head2,node *head3)
{
long int carry,number,total,num,n;
node *temp;
void display_num(node *,node *);
temp=head3;
carry=0;
/*adding the two numbers from LSB and creating the third list*/
while(head1->data!=-999 &&head2->data!=-999)
{
n=head1->data+head2->data+carry; /*Getting the carry from sum of two numbers*/
num=n%10;
carry=n/10;
head1=head1->next;
head2=head2->next;
head3->data=num;
head3->next=get_node();
head3=head3->next;
}
while(head1->data!=-999) /*if first number is bigger than second*/
{
n=head1->data+carry;
num=n%10;
carry=n/10;
head3->data=num;
head1=head1->next;
head3->next=get_node();
head3=head3->next;
}
while(head2->data!=-999) /*if second number is bigger than first*/
{
n=head2->data+carry;
num=n%10;
carry=n/10;
head3->data=num;
head2=head2->next;
head3->next=get_node();
head3=head3->next;
}
if(carry!=0) /*addition of 2 numbers is over/*and only carry is remaining*/
{
head3->data=carry;
head3->next=get_node();/*separate node for storing the carry of leftmost umber*/
head3=head3->next;
}
head3->data=-999;
head3->next=temp; /*making the list circular*/
display_num(temp,head3);
}
void display_num(node *temp,node *head)
{
int stack[50],i,n;
i=0;
while(temp!=head)
{
stack[i]=temp->data;
temp=temp->next;
i++;
}
n=i-1;
for(i=n;i>=0;i--)
printf("%d",stack[i]);
}
Output:
EX. NO: 9(B) REVERSE ELEMENTS OF A SINGLE LINKED LIST

Aim: Write a C programme to reverse elements of a single linked list.


Algorithm:
struct node
{ int info; struct node *link; };
create a node
typedef struct node *NODE;
NODE *first;
Algorithm for main function
Step 1: print the number of elements in the list
Step 2: read n
Step 3: i=1
Step 4: repeat the following until i<=n
Print ‘Enter the item to be inserted
Read x
Call function insert(x)
ii+1
Step 5: call function display ()
Step 6: call function reverse ()
Step 7: print ‘after reversing’
Step 8: display ()
Step 9: stop
Algorithm for insert a new node insert ()
Step 1: call function for allocating memoryspace for element-
temp=getnode()
Step 2: temp->info-I;
Step 3: temp->link=NULL
Step 4: check whether the list is empty or not, if empty then make temp as first node
Otherwise add temp node to list
if(first==NULL)
{
first=temp;
return ;
}
Step 5: cur=first;
Step 6: add the temp at the end of the list, to reach the end do the following steps
while(cur->link!=NULL)
cur=cur->link;
Step 7: now add the temp at the end
cur->link=temp
Step 8: stop
Algorithm to getnode(int info)
Step 1: create a new node
NODE x;
x=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
if x==NULL print overflow; return;
Step 3: if memory available then
return x
Algorithm to reverse a list—reverse()
Step 1: create three nodes
NODE p,q,r;
Step 2: keep the p=first;
Step 3: if it is not the last element in the list
if(p&&p->link)
{
q=p->link;
while(q->link)
{
r=q->link;
q->link=p;
p=q;
q=r;
}
q- >link=p;
first->link=NULL;
first=q;
}
return;
}
Algorithm to display()
Step 1: if(first==NULL) then
printf("LIST EMPTY\n");
return;
Step 2: print ‘The contents of the list are’
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
Step 3: stop.

Program:
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>

struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void insert(int i)
{
NODE temp,cur;
temp=getnode();
temp->info=i;
temp->link=NULL;
if(first==NULL)
{
first=temp;
return ;
}
cur=first;
while(cur->link!=NULL)
cur=cur->link;
cur->link=temp;
return;
}
void reverse()
{
NODE p,q,r;
p=first;
if(p&&p->link)
{
q=p->link;
while(q->link)
{
r=q->link;
q->link=p;
p=q;
q=r;
}
q->link=p;
first->link=NULL;
first=q;
}
return;
}
void main()
{
first=NULL;
int n,i=1,x;
clrscr();
printf("Enter the no of elements in the list\t:");
scanf("%d",&n);
while(i<=n)
{
printf("Enter the item to be inserted\t:");
scanf("%d",&x);
insert(x);
i++;
}
display();
reverse();
printf("\nAfter reversing. ... \n");
display();
}

Output:
EX. NO: 9(C) Store A Polynomial Expression In Memory Using Linked List

Aim: Write a C program to store a polynomial expression in memory using linked list

Algorithm:

Program:
/* Program for storing a polynomial expression in memory using linked list */
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
float coeff;
int exp;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The Polynomial is\n");
temp=first;
while(temp)
{
printf("+%4.2fX\^%d ",temp->coeff,temp->exp);
temp=temp->link;
}
printf("\n");
}
void main()
{
NODE p;
int ch,i=1,n;
float c;
int e;
clrscr();
printf("Enter the no of terms in the polynomial\t:");
scanf("%d",&n);
while(i<=n)
{
printf("coefficient and the exponent : %d :",i);
scanf("%f%d",&c,&e);
i++;
if(first)
{
p=first;
while(p->link)
p=p->link;
p->link=getnode();
p=p->link;
p->coeff=c;
p->exp=e;
p- >link=NULL;
}
else
{
first=getnode();
first->coeff=c;
first->exp=e;
first->link=NULL;
}
}
display();
}
Output:
EX. NO: 9(D) REPRESENT THE GIVEN SPARSE MATRIX USING ARRAYS

Aim: Write a C programme to representation the given sparse matrix using arrays.
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int spm[25][3],a[5][5],i,j,count,n,m,k;
clrscr();
printf("Enter matrix size as mxn\t: :");
scanf("%d%d",&m,&n);
count=0;
k=1;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\nelement A %d%d",i,j);
scanf("%d",&a[i][j]);
/* }
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ */
if(a[i][j] !=0)
{
spm[k][0]=i;
spm[k][1]=j;
spm[k++][2]=a[i][j];
count++;
}
}
}
spm[0][0]=m;
spm[0][1]=n;
spm[0][2]=count;
printf("\nsparse matrix is : :\n");
for(i=0;i<=count;i++)
{
for(j=0;j<3;j++)
printf("%d ",spm[i][j]);
printf("\n");
}
getch();
}
Output:
EX. NO: 9(E) REPRESENT THE GIVEN SPARSE MATRIX USING LINKED LIST

Aim: Write a C programme to representation the given sparse matrix using linked list.
Algorithm:
Program: /* Program for representing a sparse matrix using linked list */

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct spars /*creating the data type for the node */
{
int row;
int col;
int item;
struct spars *next;
}*ptr;
struct head_sp /*creating the data type for header node header*/
{
int rows;
int cols;
int items;
struct spars *next;
}*header;
void main()
{
int i,j;
/*create the header node*/
header=(struct head_sp *)malloc(sizeof(struct head_sp));
/*store elements of the header node*/
printf("Enter the Header node information\n");
printf("Enter Number of rows,columns, and Non zero elements\t:");
scanf("%d%d%d",&header->rows,&header->cols,&header->items);
/*if sparse matrix is empty then return*/
if(header->items==0)
{
printf("If no Non-zero elements, Press any key to return");
getch();
exit(0);
} /*Otherwise, Head node pointer will point to the first element of the sparse matrix*/
header->next=(struct spars *)malloc(sizeof(struct spars));
/*keep elements in the first node*/
printf("Enter the ROW No., COL no., and Non-zero element\t:");
scanf("%d%d%d",&header->next->row,&header->next->col,&header->next->item );
/*initializing special pointer to the sparse matrix elements*/
ptr=header->next;
/*create nodes for sparse matrix elements and enter information in them*/
for(i=2;i<=header->items;i++)
{
ptr->next=(struct spars *)malloc(sizeof(struct spars));
ptr=ptr->next;
printf("enter the row no., col no., value of %dth element\t:",i);
scanf("%d%d%d",&ptr->row, &ptr->col, &ptr->item);
}
ptr->next=NULL; /*display the header node*/
printf("\n\nHeader node Information:\n\n");
printf(" No.of rows=%d\n No. of cols=%d\n No. of Non-zero elements=%d\n", header-
>rows,header->cols,header->items); /*display the matrix elemnts*/
printf("Elements of the matrix are:\nrow no. col no. value \n");
ptr=header->next;
for(i=0;i<header->rows;i++)
for(j=0;j<header->cols;j++)
{
printf("%d\t%d\t",i,j);
if(ptr!=NULL)
{
if((i==(ptr->row)) && (j==(ptr->col)))
{
printf("%d\n",ptr->item);
ptr=ptr->next;
}
else
printf("0 \n");
}
else printf("0 \n");
}
}
Output:
EX. NO: 10(A) CREATE A BINARY TREE OF INTEGERS

Aim: Write a C program to create a Binary Tree of integers

Algorithm:

Program:
/**********************************************************
Program for creating a Binary Tree and Displaying the tree
**********************************************************/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node{
int info;
struct node *left,*right;
};
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct node **root,int item)
{
char lch,rch;
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
nn->info=item;
nn->left=NULL;
nn->right=NULL;
if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->info);
lch=getche();
if(lch == 'y' || lch == 'Y')
insert(&(*root)->left,getitem());
printf("\n%d HAS ANY RIGHT(y/n)?::",(*root)->info);
rch=getche();
if(rch == 'y' || rch == 'Y')
insert(&(*root)->right,getitem());
}
void inorder(struct node *r)
{
if(r ==NULL)
return;
inorder(r->left);
printf("%d-->",r->info);
inorder(r->right);
}
void main()
{
struct node *root=NULL;
int item;
clrscr();
puts("\t\t\tImplementing a simple Binary Tree\n");
item=getitem();
insert(&root,item);
puts("\nDisplaying the Tree\n");
printf("\nRoot node is %d",root->info);
printf("\n\nINORDER TRAVERSAL : :\n");
inorder(root);
getch();
}

Output:
EX. NO: 10(B) TRAVERSING A BINARY TREE IN PREORDER, INORDER AND
POSTORDER USING RECURSION
Aim: Write a recursive C program, for traversing a binary tree in preorder, inorder and
postorder.

Algorithm:

Program:
/**********************************************************
Program for creation Of a Binary Tree and Display the tree
using recursive inorder, preorder and postorder traversals.
**********************************************************/
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
struct node{
int info;
struct node *left,*right;
};
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct node **root,int item)
{
char lch,rch;
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));

nn->info=item;
nn->left=NULL;
nn->right=NULL;

if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->info);
lch=getche();

if(lch == 'y' || lch == 'Y')


insert(&(*root)->left,getitem());

printf("\n%d HAS ANY RIGHT(y/n)?::",(*root)->info);


rch=getche();

if(rch == 'y' || rch == 'Y')


insert(&(*root)->right,getitem());
}
/* This function displays the tree in inorder fashion */
void inorder(struct node *r)
{
if(r ==NULL)
return;
inorder(r->left);
printf("%d-->",r->info);
inorder(r->right);

}
/* This function displays the tree in preorder fashion */
void preorder(struct node *r)
{
if(r== NULL)
return;
printf("%d-->",r->info);
preorder(r->left);
preorder(r->right);
}
/* This function displays the tree in postorder fashion */
void postorder(struct node *r)
{
if(r==NULL)
return;
postorder(r->left);
postorder(r->right);
printf("%d-->",r->info);
}
void main()
{
struct node *root=NULL;
int item;
int choice;
clrscr();
printf("\n\t Program For Binary Tree\n\n");
do
{
printf("\n1.Create\n2.Inorder Traversal\n3.Preorder Traversal\n4.Postorder
Traversal\n5.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
root=NULL;
item=getitem();
insert(&root,item);
break;
case 2:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nINORDER TRAVERSAL : :\n");
inorder(root);
}
break;
case 3:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nPREORDER TRAVERSAL ::\n");
preorder(root);
}
break;
case 4:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nPOST ORDER TRAVERSAL ::\n");
postorder(root);
}
break;
}
}while(choice!=5);
getch();
}

Output:
EX. NO: 10(C) TRAVERSING A BINARY TREE IN PREORDER, INORDER AND
POSTORDER NOT USING RECURSION
Aim: Write a non recursive C program, for traversing a binary tree in preorder, inorder and
postorder.
Algorithm: A binary tree T is in memory. The algorithm does a preorder traversal of T,
Applying a PROCESS to each of its nodes. An array STACK is used to temporarily hold the
address of nodes.
Algorithm for preorder (using stack):
Step 1: Initially push NULL into the STACK, and initialize PTR.
Set TOP=1 STACK[1]=NULL and PTR=ROOT
Step 2: repeate step 3 to 5 untill PTR != NULL
Step 3: Apply PROCESS to PTR->INFO
Step 4: check for right child
If PTR->RIGHT !=NULL then push on stack
Set TOP=TOP+1 and
STACK[TOP]=PTR->RIGHT
Step 5:Check for left child
If PTR->LEFT != NULL then PTR=PTR->left
Else set ptr=STASCK[TOP] and TOP=TOP-1
Step 6: stop.

Algorithm for postorder:


Step 1: Initially push NULL into the STACK, and initialize PTR.
Set TOP=1 STACK[1]=NULL and PTR=ROOT
Step 2: push left most path into the STACK
repeate step 3 to 5 untill PTR != NULL
step 3:pushes PTR on STACK
TOP=TOP+1 stack[top]=PTR
Step 4: if PTR-> RIGHT != NULL, then push on the STACK
Set TOP=TOP+1 STACK [TOP]=PTR->RIGHT
Step 5: PTR=PTR->LEFT
Step 6: PTR=STACk[TOP] TOP=TOP-1
step 7:repeate while ptr>0
(a) apply PROCESS to PTR->info
(b)set PTR=STACK[TOP TOP=TOP-1
Step 8:if PTR<=0,then
(a) set PTR=-PTR
(b) go to step 2
Step 9: end

Algorithm for inorder:


Step 1: Initially push NULL into the STACK, and initialize PTR.
Set TOP=1 STACK[1]=NULL and PTR=ROOT
Step 2: repeate while PTR!=NULL [pushes left most path in STACK]
(a) Set TOP=TOP+1 and STACK[TOP]= PTR [save nodes]
(b) Set PTR=PTR->LEFT [updates PTR]
Step 3: set PTR=STACK[TOP] and TOP=TOP-1 [pops node from stack
Step 4: repeate steps 5 to 7 while PTR != NULL [backtracking]
Step 5: apply PROCESS to INFO->PTR
Step 6: check for right child
If PTR->RIGHT != NULL, then
(a) Set PTR=PTR->RIGHT
(b) Go to step 3
Step 7: set PTR=STACK[TOP] and TOP=TOP-1 [pops node]
Step 9: end

Program:
/***********************************************************************
Program for Implementation of Simple Binary Tree and Non-recursive inorder, preorder and
postorder traversals.
**************************************************************************/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct bstnode
{
int data;
struct bstnode *lc,*rc;
}*root,*a[20],*b[20];
int top=-1,top1=-1,n,i;
push (struct bstnode *);
struct bstnode *pop();
void insert(struct bstnode **,int);
int getitem();
void Nonrecursive_Inorder(struct bstnode *);
void Nonrecursive_Postorder(struct bstnode *);
void Nonrecursive_Preorder(struct bstnode *);
void main()
{
int ch,item;
struct bstnode *root;
clrscr();
root=NULL;
while(1)
{
printf("\n **** M E N U **** \n");
printf("\nstep 1:Create\nstep 2:NON-RECURSIVE TRAVERSE\nstep 3:EXIT\n");
printf("Enter your choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1: root=NULL;
item=getitem();
insert(&root,item);
break;
case 2:
if(root==NULL)
printf("\nTREE IS EMPTY\n");
else
{
printf("\nINORDER\t:");
Nonrecursive_Inorder(root);
printf("\nPREORDER\t:");
Nonrecursive_Preorder(root);
printf("\nPOSTORDER\t:");
Nonrecursive_Postorder(root);
}
break;
case 3:
exit(0);
}
}
}
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct bstnode **root,int item)
{
char lch,rch;
struct bstnode *nn;
nn=(struct bstnode *)malloc(sizeof(struct bstnode));
nn->data=item;
nn->lc=NULL;
nn->rc=NULL;
if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->data);
lch=getche();

if(lch == 'y' || lch == 'Y')


insert(&(*root)->lc,getitem());

printf("\n%d HAS ANY RIGHT(y/n)?\t::",(*root)->data);


rch=getche();
if(rch == 'y' || rch == 'Y')
insert(&(*root)->rc,getitem());
}
/* This function displays the tree in Non-recursive Inorder fashion */
void Nonrecursive_Inorder(struct bstnode *x)
{
struct bstnode *l;
l=x;
do
{
while(l!=NULL)
{
push(l);
l=l->lc;
}
while(top>-1)
{
l=pop();
printf("%d--->",l->data);
if(l->rc!=NULL)
{
l=l->rc;
break;
}
else
l=NULL;
}
}while(l!=NULL);
}
/* This function displays the tree in Non-recursive Preorder fashion */
void Nonrecursive_Preorder(struct bstnode *x)
{
struct bstnode *l;
l=x;
do
{
printf("%d--->",l->data);
if(l->rc!=NULL)
push(l->rc);
l=l->lc;
if(l==NULL&&top>-1)
l=pop();
}while(l!=NULL);
}
/* This function displays the tree in Non-recursive Postorder fashion */
void Nonrecursive_Postorder(struct bstnode *x)
{
struct bstnode *l;
l=x;
do
{
while(l!=NULL)
{
push(l);
if(l->rc!=NULL)
{
push(l->rc);
b[++top1]=l->rc;
}
l=l->lc;
}
do
{
l=pop();
if(l!=b[top1])
printf("%d--->",l->data);
else
{
top1-=1;
break;
}
} while(top>-1);
}while(l!=NULL&&top>-1);
}
push(struct bstnode *y)
{
top+=1;
a[top]=y;
}
struct bstnode *pop()
{
return a[top--];
}
Output:
EX. NO: 11(A) CREATE A BST
Aim: Write a C program to create a BST

Algorithm:

Program:
/* Program For Implementation Of Binary Search Tree and display of tree. */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>

typedef struct bst


{
int data;
struct bst *left,*right;
}node;

void insert(node *,node *);


void inorder(node *);

void main()
{
int choice;
char ans='N';
node *New,*root;
node *get_node();
root=NULL;
clrscr();
printf("\n\t***** Binary Search Tree ****** ");
do
{
printf("\n1.Create\n2.Display\n3.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:root=NULL;
do
{
New=get_node();
printf("\n Enter The Element ");
scanf("%d",&New->data);
if(root==NULL) /* Tree is not Created */
root=New;
else
insert(root,New);
printf("\n Do u Want To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y'||ans=='Y');
break;
case 2:if(root==NULL)
printf("Tree Is Not Created\n");
else
{
printf("\n The Inorder display of the Tree is : ");
inorder(root);
}
break;
}
}while(choice!=3);
}

node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}

/*This function is for creating a binary search tree */


void insert(node *root,node *New)
{
if(New->data<root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data>root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}

/* This function displays the tree in inorder fashion */


void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}
}

Output:
EX. NO: 11(B) INSERT A NODE INTO A BST

Aim: Write a C programme to insert a note into a BST.


Algorithm:
Program: /*Program For Implementation Of Binary Search Tree, insert a new element
into BST and display of tree. */

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

typedef struct bst


{
int data;
struct bst *left,*right;
}node;
void insert(node *,node *);
void inorder(node *);
void main()
{
int choice;
char ans='N';
node *New,*root;
node *get_node();
root=NULL;
clrscr();
printf("\n\t***** Binary Search Tree ****** ");
do
{
printf("\n1.Create\n2.Insert\n3.Display\n4.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:root=NULL;
do
{
New=get_node();
printf("\n Enter The Element ");
scanf("%d",&New->data);
if(root==NULL) /* Tree is not Created */
root=New;
else
insert(root,New);
printf("\n Do u Want To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y'||ans=='Y');
break;
case 2: if(root==NULL)
printf("Tree is not CREATED ... \n");
else
{
New=get_node();
printf("Enter an element to insert into a BST\t:");
scanf("%d",&New->data);
insert(root,New);
}
break;
case 3:if(root==NULL)
printf("Tree Is Not Created\n");
else
{
printf("\n The Inorder display of the Tree is : ");
inorder(root);
}
break;
case 4:exit(0);
}
}while(choice!=4);
}
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
/*This function is for creating a binary search tree */
void insert(node *root,node *New)
{
if(New->data<root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data>root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}
/* This function displays the tree in inorder fashion */
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}
}

Output:
EX. NO: 11(C) INSERT A NODE INTO A BST

Aim: Write a C programme to insert a note into a BST.

Algorithm:

Program:
/*Program For Implementation of Binary Search Tree,perform deletion and display of tree. */

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct bst
{
int data;
struct bst *left,*right;
}node;
void insert(node *,node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
void search (node **root, int num,node **par, node **x, int *found );
void delete(node **root, int);
void main()
{
int choice,ele;
char ans='N';
node *New,*root;
node *get_node();
root=NULL;
clrscr();
printf("\n\t Program For Binary Search Tree ");
do
{
printf("\n1.Create\n2.Delete\n3.Recursive Traversals\n4.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: root=NULL;
do
{
New=get_node();
printf("\n Enter The Element ");
scanf("%d",&New->data);
if(root==NULL) /* Tree is not Created */
root=New;
else
insert(root,New);
printf("\n Do u Want To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y');
break;
case 2:printf("\n Enter The Element Which You Want To Delete");
scanf("%d",&ele) ;
delete(&root,ele);
break;
case 3:if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n The Inorder display of the Tree is : ");
inorder(root);
printf("\n The Preorder display of the Tree is : ");
preorder(root);
printf("\n The Postorder display of the Tree is : ");
postorder(root);
}
break;
}
}while(choice!=4);
}
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
/*This function is for creating a binary search tree */
void insert(node *root,node *New)
{
if(New->data<root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data>root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}
/* This function is for searching the node from binary Search Tree */
/* deletes a node from the binary search tree */
void delete (node **root, int num )
{
int found ;
node *parent, *x, *xsucc ;

/* if tree is empty */
if ( *root == NULL )
{
printf ( "\nTree is empty" ) ;
return ;
}
parent = x = NULL ; /* call to search function to find the node to be deleted */
search ( root, num, &parent, &x, &found ) ;

/* if the node to deleted is not found */


if ( found == FALSE )
{
printf ( "\nData to be deleted, not found" ) ;
return ;
}
/* if the node to be deleted has two children */
if ( x -> left != NULL && x -> right != NULL )
{
parent = x ;
xsucc = x -> right ;

while ( xsucc -> left != NULL )


{
parent = xsucc ;
xsucc = xsucc -> left ;
}

x -> data = xsucc -> data ;


x = xsucc ;
}

/* if the node to be deleted has no child */


if ( x -> left == NULL && x -> right == NULL )
{
if ( parent -> right == x )
parent -> right = NULL ;
else
parent -> left = NULL ;

free ( x ) ;
return ;
}
/* if the node to be deleted has only right child */
if ( x -> left == NULL && x -> right != NULL )
{
if ( parent -> left == x )
parent -> left= x -> right;
else
parent -> right= x -> right;

free ( x ) ;
return ;
}
/* if the node to be deleted has only left child */
if ( x -> left != NULL && x -> right == NULL )
{
if ( parent -> left == x )
parent -> left = x -> left ;
else
parent -> right = x -> left ;

free ( x ) ;
return ;
}
}

/*returns the address of the node to be deleted, address of its parent and whether the node is
found or not */
void search (node **root, int num,node **par, node **x, int *found )
{
node *q ;

q = *root ;
*found = FALSE ;
*par = NULL ;
while ( q != NULL )
{
/* if the node to be deleted is found */
if ( q -> data == num )
{
*found = TRUE ;
*x = q ;
return ;
}

*par = q ;
if ( q -> data > num )
q = q -> left;
else
q = q -> right;
}
}
/* This function displays the tree in inorder fashion */
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}
}
/* This function displays the tree in preorder fashion */
void preorder(node *temp)
{
if(temp!=NULL)
{
printf(" %d",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
/* This function displays the tree in postorder fashion */
void postorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf(" %d",temp->data);

}
}
Output:

You might also like