C++ Programs For Computer Science Students
C++ Programs For Computer Science Students
IMPLEMENTATION OF
CIRCULAR QUEUE
OBJECTIVE:
Here we have implemented a program to implement a circular queue using linear array.
ALGORITHM:
ENQUEUE(QUEUE, FRONT, REAR,ITEM)
This procedure inserts an element ITEMinto the queue.
1. [Queue is already filled?]
If FRONT=1 and REAR = N or FRONT = REAR + 1, then :
Write: OVERFLOW and Return.
2. [Find new value of REAR.]
If FRONT = NULL, then : [Queue initially empty.]
Set FRONT = 1 and REAR = 1.
Else :
Set REAR = [ REAR + 1 ] MOD N.
[End of if structure.]
3. Set QUEUE[REAR]=ITEM. [Inserts new element.]
4. Return.
DEQUEUE(QUEUE,FRONT, REAR, ITEM)
This procedure deletes the front element of queue.
1. [ Queue already empty?]
If FRONT = NULL, then :
Write: UNDERFLOW and Return.
2. Set ITEM = QUEUE[ FRONT ].
3. [Find new value of FRONT.]
If FRONT = REAR, then : [Queue has only one element to start.]
Set FRONT = NULL and REAR = NULL.
Else : Set FRONT = [ FRONT + 1 ] MOD N.
[End of if structure.]
4. Return ITEM.
CODE:
#include<iostream.h>
#include<stdlib.h>
#define MAX 10
class queue{
intqu[MAX];
int front;
int rear;
public:
void insert(int);
intqdelete();
void display();
intisfull();
intisempty();
queue() {
front=rear=-1;
}
};
int queue::isfull()
{
if(((front==0)&&(rear==MAX-1))||(front==rear+1))
return 1;
else
return 0;
}int queue::isempty()
{
if(front==-1)
return 1;
else
return 0;
}
void queue::insert(int item)
{
if(front==-1)
/* Adjust rear */
front=rear=0;
else
rear=(rear+1)%MAX;
qu[rear]=item; /* Store element at new rear */
}
int queue::qdelete()
{
int item;
/* Store front in temporary variable */
item=qu[front];
if(front==rear) /* Adjust front */
front=rear=-1;
else
front=(front+1)%MAX;
return item;
/* return deleted element */
}
void queue::display(){
if(isempty())
cout<<"\nQueue is empty.\n";
else
{
cout<<"\nThe queue is : ";
for(int i=front;i<=rear;i++)
cout<<qu[i]<<"\t";
cout<<"\n";
}
}
int main()
{
queue q;
intch, item;
cout<<"\t\tCIRCULAR QUEUE USING LINEAR ARRAY\n";
while(1)
{
cout<<"\n\nOptions available\n-----------------";
cout<<"\n1. Insert element into queue.\n2. Delete element from queue.\n3. Exit.\n";
cout<<"\nEnter Your choice : ";
cin>>ch;
switch(ch)
{
case 1:
if(q.isfull())
cout<<"\nQueue is full.\n";
else
{
cout<<"\nEnter value : ";
cin>>item;
q.insert(item);
q.display();
}
break;
case 2:
if(q.isempty())
cout<<"\nQueue empty.\n";
else
{
cout<<"\n"<<q.qdelete()<<" is deleted.\n";
q.display();
}
break;
case 3:
return(0);
break;
default:
cout<<"\nWrong Input.\n";
}
}
}
OUTPUT:
CIRCULAR QUEUE USING LINEAR ARRAY
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 1
Entervalue : 6
The queue is : 5
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 1
Entervalue : 7
The queue is : 5
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 1
Entervalue : 8
The queue is : 5
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 2
6 is deleted.
The queue is : 7
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 2
7 is deleted.
The queue is : 8
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 2
8 is deleted.
Queue is empty.
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Options available
--------------------1. Insert element into queue.
2. Delete element from queue.
3. Exit.
Enter Your choice : 3
Press any key to continue
DISCUSSION:
1.
2.
3.
A queue, also called a First-In-First-Out (FIFO) system, is a linear list in which deletions can
take place only at one end called the front, and insertion can take place at the other end
called the rear.
In this program the queue can store integer type of data only.
The term circular comes from the fact that we assume that QUEUE[1] comes after
QUEUE[N] in the array.
OBJECTIVE:
Here we have implemented Merge Sort to sort an array in ascending order and then to search an
element from the sorted array using Binary Search.
ALGORITHM:
ALGORITHM FOR BINARY SEARCH:
MERGESORT( A, LB, UB )
This algorithm sorts the N-element array A using merge sort. LB and UB are respectively the lower
and upper bound of the array A.
1. If LB<UB, then:
Repeat Steps 2 to 5.
2.
Set MID = ( LB + UB ) /2.
3.
Call MERGESORT ( A, LB, MID ) .
4.
Call MERGESORT( A, MID + 1, UB ) .
5.
Call MERGESUBARRAY ( A, LB, MID, MID + 1, UB ) .
[ End of If structure. ]
6. Exit.
MERGESUBARRAY( A,LB,LE,RB,RE )
Here A is a linear array, variable LB and LE represents the beginning and ending index of the left sub
array and RB and RE represents the beginning and ending index of right sub array. This algorithm
merges these two sub arrays. It uses local variables NA, NB as counters to keep track of the elements
of left and right sub array respectively. We use a temporary array C. NC keeps track of the index of
the array C.
1. [ Initialize. ] Set NA = LB, NB = RB, NC = LB.
2. Repeat while NA<= LE and NB<= RE:
If A[ NA ] <B [ NB ] , then:
(a) [ Assign element from left sub array to C. ] Set C[ NC ] = A [ NA ] .
(b) [ Update pointer. ] Set NA = NA +1.
Else:
(a) [ Assign element from right sub array to C. ] Set C[ NC ] = A [ NB ] .
(b) [ Update pointer. ] Set NB = NB + 1.
[ End of If structure. ]
[ Update pointer. ] Set NC = NC +1.
[ End of loop. ]
3. [ Assign remaining elements to C. ]
If NA>LE, then:
Repeat while NB< = RE:
(a) Set C[ NC ] = A [ NB ] .
(b) Set NB = NB + 1.
(c) Set NC = NC + 1.
[ End of loop. ]
Else:
Repeat while NA< = LE:
(a) Set C[ NC ] = A [ NA ] .
(b) Set NA = NA + 1.
(c) Set NC = NC + 1.
[ End of loop. ]
[ End of If structure. ]
4. Repeat for K = LB to RE:
(a) Set A [ K ] = C [ K ] .
(b) Set K = K + 1.
[ End of loop. ]
7. Exit.
CODE:
#include<iostream.h>
constint MAX=20;
template<class T>
class search
{
int n;
T a[MAX];
public:
voidgetdata(int x) {
n=x;
for(int i=0;i<n;i++)
cin>>a[i];
}
void display() {
for(int i=0;i<n;i++)
{
cout<<a[i];
cout<<"\t";
}
cout<<"\n";
}
intBinarySearch(intlb, intub, T info){
/* Here LIST is a linear array and N is the total no. of elements in the array*/
int mid=-1;
if(lb>ub) /* item not found */
return(mid);
else
{
mid=(lb+ub)/2;
if(a[mid]==info) /* item found */
return(mid);
else if(a[mid]>info)
return(BinarySearch(lb,mid-1,info));
/* take 1st half of list */
else
return(BinarySearch(mid+1,ub,info));
/* take 2nd half of list */
}
}
voidMergeSort(intl,int r){
int mid;
if(l<r)
{
mid=(l+r)/2;
MergeSort(l,mid);
MergeSort(mid+1,r);
MergeList(l,mid,mid+1,r);
}
}
voidMergeList(intls,intle,intrs,int re)
{
int i=ls,j=rs,k=ls;
T c[MAX];
while((i<=le)&&(j<=re))
{
if(a[i]<a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
if(i>le)
{
while(j<=re) /* remaining elements of right sub array */
c[k++]=a[j++];
}
else {
while(i<=le) /* remaining elements of left sub array */
c[k++]=a[i++];
}
for(i=ls;i<=re;i++)
a[i]=c[i];
}
};
int main()
{
intx,loc,ch,it;
floatft;
charct;
search<int> i;
search<float> f;
search<char> c;
cout<<"\t\t\tSORT AN ARRAY USING MERGE SORT\n\tAND SEARCH AN ELEMENT
FROM THE SORTED LIST USING BINARY SEARCH\n\n";
while(1) /* Get input in array from user */
{
cout<<"\nSELECT ONE:\n-----------";
cout<<"\n1. Sort n Search on an integer array.\n2. Sort n Search on a float array.";
cout<<"\n3. Sort n Search on a character array.\n4. Exit.\n";
cout<<"Enter your choice : ";
cin>>ch;
try {
if(ch>=1&&ch<=3) {
cout<<"\nEnter no. of elements in the list : ";
cin>>x;
try
{
if((x<MAX)&&(x>=0)) {
cout<<"\nEnter elements for the list :\n";
switch(ch)
{
case 1:
i.getdata(x);
cout<<"\nYou have entered the list as :\n";
i.display(); /* Display the unsorted list */
i.MergeSort(0,x-1);/* Call of the sorting funtion to sort the list */
cout<<"\nThe Sorted list is :\n"; /* Display the sorted list */
i.display();
cout<<"\n\nEnter element to be searched : ";
cin>>it;
/* Get the element to be searched */
loc=i.BinarySearch(0,x-1,it);/* Call of searching function to search item */
if(loc==-1)/* Display location of item in sorted array */
cout<<"\n"<<it<<" not found.\n\n";
else
cout<<"\nLocation of "<<it<<" = "<<loc<<"\n\n";
break;
case 2:
f.getdata(x);
cout<<"\nYou have entered the list as :\n";
f.display();
f.MergeSort(0,x-1);
cout<<"\nThe Sorted list is :\n";
f.display();
cout<<"\n\nEnter element to be searched : ";
cin>>ft;
loc=f.BinarySearch(0,x-1,ft);
10
if(loc==-1)
cout<<"\n"<<ft<<" not found.\n\n";
else
cout<<"\nLocation of "<<ft<<" = "<<loc<<"\n\n";
break;
case 3:
c.getdata(x);
cout<<"\nYou have entered the list as :\n";
c.display();
c.MergeSort(0,x-1);
cout<<"\nThe Sorted list is :\n";
c.display();
cout<<"\n\nEnter element to be searched : ";
cin>>ct;
loc=c.BinarySearch(0,x-1,ct);
if(loc==-1)
cout<<"\n"<<ct<<" not found.\n\n";
else
cout<<"\nLocation of "<<ct<<" = "<<loc<<"\n\n";
break;
}
}
else
throw(x);
}
catch(int)
{
cout<<"\nException detected : Illegal boundary value.\n\n";
}
}
else if(ch==4)
return(0);
else
throw(ch);
}
catch(int)
{
cout<<"\nException detected : Wrong Input.\n\n";
}
}
}
OUTPUT:
SORT AN ARRAY USING MERGE SORT
AND SEARCH AN ELEMENT FROM THE SORTED LIST USING BINARY SEARCH
SELECT ONE:
----------------1. Sort n Search on an integer array.
2. Sort n Search on a float array.
11
31
65
SELECT ONE:
----------------1. Sort n Search on an integer array.
2. Sort n Search on a float array.
3. Sort n Search on a character array.
4. Exit.
Enter your choice : 2
Enter no. of elements in the list : 5
Enter elements for the list :
2.36
5.47
-0.12
2.47
0.12
You have entered the list as :
2.36 5.47 -0.12 2.47 0.12
The Sorted list is :
-0.12 0.12 2.36 2.47 5.47
12
SELECT ONE:
----------------1. Sort n Search on an integer array.
2. Sort n Search on a float array.
3. Sort n Search on a character array.
4. Exit.
Enter your choice : 3
Enter no. of elements in the list : 8
Enter elements for the list :
A
S
D
P
M
T
H
R
You have entered the list as :
A
S
D
P
M
T
The Sorted list is :
A
D
H
M
SELECT ONE:
----------------1. Sort n Search on an integer array.
2. Sort n Search on a float array.
3. Sort n Search on a character array.
4. Exit.
Enter your choice : 6
Exception detected : Wrong Input.
SELECT ONE:
----------------1. Sort n Search on an integer array.
2. Sort n Search on a float array.
3. Sort n Search on a character array.
4. Exit.
13
1.
2.
3.
4.
DISCUSSION:
Binary search is a search technique that is applied to a list of ordered keys. At each step of the search,
the list is partitioned into two equal parts, with the selection of the appropriate partition to probe in
the next iteration made on the basis of relative key values.
To execute the search properly, the array must be sorted. After taking values to the array the
program itself sorts the list in ascending order using merge sort. Thus it is not compulsory for the
user to provide input in sorted order.
This program searches an element from an array of integers in recursive way.
This program is implemented on generic data types using a template class.
14
POLYNOMIAL
ADDITION
OBJECTIVE:
We have implemented a C++ program toperform the addition of two polynomials.
ALGORITHM:
POLYNOMIALADDITION( POLY1, POLY2, POLY3, COEF, POWR, NEXT )
This algorithm adds two polynomials POLY1, POLY2 and Save the result as POLY3. Each
polynomial node contains a COEF, i.e. the coefficient of the term, a POWR, i.e. the power of the
power of the term and a NEXT that holds the address of the next node.
1. Repeat Step to while POLY1 <> NULL and POLY3 <> NULL :
2.
If POLY1 [ POWR ] > POLY2 [ POWR ], then :
POLY3 [ COEF ] = POLY1 [ COEF ].
POLY3 [ POWR ] = POLY1 [ POWR ].
POLY3 = POLY3 [ NEXT ].
3.
Else if POLY1 [ POWR ] < POLY2 [ POWR ], then :
POLY3 [ COEF ] = POLY1 [ COEF ].
POLY3 [ POWR ] = POLY1 [ POWR ].
POLY3 = POLY3 [ NEXT ].
4.
Else :
POLY3 [ COEF ] = POLY1 [ COEF ] +POLY2 [ COEF ].
POLY3 [ POWR ] = POLY1 [ POWR ].
POLY3 = POLY3 [ NEXT ].
[ End of If Structure. ]
5.
If POLY [ COEF ] <> 0, then :
Add POLY3 to resultant list.
[ End of If Structure. ]
[ End of loop. ]
6. Add nodes left in 1st polynomial to resultant list.
7. Add nodes left in 2nd polynomial to resultant list.
8. Return.
CODE:
#include<iostream.h>
#include<stdlib.h>
typedef class node
{
public:
floatcoeff;
15
int power;
class node *next;
} node;
class polynomial
{
node *poly;
public:
voidreadnode(node **);
void display(node *);
void sort(node **);
voidaddpoly(node**,node*,node*);
voidaddnode(node **,float,int);
polynomial()
{
poly=NULL;
}
};
void polynomial::readnode(node **head)
{
*head=new node;
/* Create a new node */
charch;
float c;
int p;
cout<<"\nEnter Coefficient : ";
cin>>c;
cout<<"Enter Power : ";
cin>>p;
(*head)->power=p;
(*head)->coeff=c;
/* Assign value to the new node */
cout<<"\nWant to add more nodes[Y/N]...";
cin>>ch;
if(ch=='N'||ch=='n')
(*head)->next=NULL;
else
readnode(&(*head)->next);
/* Create the next node */
return;
}
void polynomial::sort(node **root)
{
node *curr,*save,*pre;
floattempc;
inttempp;
for(curr=*root;curr->next!=NULL;curr=curr->next)
{
for(save=curr->next;save!=NULL;save=save->next)
{
if(curr->power<save->power)
{
pre=save;
tempc=curr->coeff;
tempp=curr->power;
curr->coeff=save->coeff;
16
curr->power=save->power;
save->coeff=tempc;
save->power=tempp;
}
}
}
}
void polynomial::display(node *poly)
{
node *ptr;
ptr=poly;
if(ptr==NULL)
{
cout<<"\nEmpty\n";
return;
}
while(ptr!=NULL)
{
if(ptr->coeff==0)
ptr=ptr->next;
else
{
if(ptr->coeff>0)
cout<<"+ ";
if(ptr->power==0)
cout<<ptr->coeff;
else if(ptr->power==1)
{
if(ptr->coeff==1)
cout<<"x ";
else if(ptr->coeff==-1)
cout<<"-x ";
else
cout<<ptr->coeff<<"x ";
}
else
{
if(ptr->coeff==1)
cout<<"x^"<<ptr->power<<" ";
else if(ptr->coeff==-1)
cout<<"-x^"<<ptr->power<<" ";
else
cout<<ptr->coeff<<"x^"<<ptr->power<<" ";
}
ptr=ptr->next;
}
}
cout<<"\n";
}
void polynomial::addnode(node **ptr,floatcoef,intpwr)
{
node *temp;
17
temp=new node;
temp->coeff=coef;
temp->power=pwr;
if(*ptr==NULL)
{
temp->next=NULL;
*ptr=temp;
}
else
{
temp->next=*ptr;
*ptr=temp;
}
}
void polynomial::addpoly(node **list3,node *list1,node *list2)
{
floatcoef;
intpwr;
while((list1!=NULL)&&(list2!=NULL))
{
if(list1->power>list2->power)
{
/* If of larger power add to new list and move to next node */
coef=list1->coeff;
pwr=list1->power;
list1=list1->next;
}
else if(list2->power>list1->power)
{
coef=list2->coeff;
pwr=list2->power;
list2=list2->next;
}
else if(list2->power==list1->power)
{
/* If of same power add the coefficients */
coef=list1->coeff+list2->coeff;
pwr=list1->power;
list1=list1->next;
list2=list2->next;
}
if(coef!=0)
addnode(list3,coef,pwr);
/* Add the resultant node to new list */
}
if(list1==NULL)
{
/* If more nodes left in 1st polynomial add them in new list */
while(list2!=NULL)
{
addnode(list3,list2->coeff,list2->power);
list2=list2->next;
}
}
18
if(list2==NULL)
{
/* If more nodes left in 2nd polynomial add them in new list */
while(list1!=NULL)
{
addnode(list3,list1->coeff,list1->power);
list1=list1->next;
}
}
}
int main()
{
polynomial p;
node *poly1=NULL,*poly2=NULL,*poly3=NULL;
cout<<"\t\t\tPOLYNOMIAL ADDITION\n";
cout<<"\nEnter 1st Polynomial :\n";
p.readnode(&poly1);
cout<<"\n\nEnter 2nd Polynomial :\n";
p.readnode(&poly2);
p.sort(&poly1); /* Sort the nodes order by power */
cout<<"\n1st Polynomial : ";
p.display(poly1);
p.sort(&poly2); /* Sort the nodes order by power */
cout<<"\n2nd Polynomial : ";
p.display(poly2);
p.addpoly(&poly3,poly1,poly2);
cout<<"\nSum of Polynomial : ";
p.sort(&poly3); /* Sort the nodes order by power */
p.display(poly3);
cout<<"\n";
return(0);
}
OUTPUT:
POLYNOMIAL ADDITION
Enter 1st Polynomial :
Enter Coefficient : 5
Enter Power : 3
Want to add more nodes[Y/N]...y
Enter Coefficient : 2
Enter Power : 5
Want to add more nodes[Y/N]...y
Enter Coefficient : 0
Enter Power : 2
19
20
DISCUSSION:
1.
2.
3.
Here the linked list that is used to represent a polynomial contains one coefficient part, a
power part and an address part to hold the address of next node.
Above program takes input of coefficient and power separately of 2 different polynomials
add them up to a new polynomial.
If user enters the term not maintaining the decreasing order of power, the program itself can
sort the terms in decreasing order of power.
21
FUNCTION
OVERLOADING
OBJECTIVE:
We have implemented a C++ program to implement an overloaded function to perform different
tasks.
ALGORITHM:
Here we have used the function ADD to perform different operations with different datatypes.
ADDITION OF TWO INTEGERS:
ADD(N1,N2, SUM)
Here N1 AND N2 are two integers. This algorithm adds the two numbers and returns the sum as
SUM.
1. Set SUM = N1 + N2.
2. Return SUM.
3. Exit.
ADDITION OF THREE INTEGERS:
ADD ( N1, N2, N3 SUM )
Here N1, N2 AND N3 are three integers. This algorithm adds the three numbers and returns the sum
as SUM.
1. Set SUM = N1 + N2 + N3.
2. Return SUM.
3. Exit.
ADDITION OF A INTEGER AND A FLOAT:
ADD (I,F, SUM )
Here Iis an integer AND F is a float. This algorithm adds the two numbers and returns the sum as
SUM.
1. Set SUM =I + F.
2. Return SUM.
3. Exit.
CONCATENATION OF TWO CHARACTERS:
ADD ( C1, C2, NEWSTR )
Here C1 AND C2 are two characters. This algorithm concatenates the two characters and returns the
new string as NEWSTR.
1. Set NEWSTR[ 0 ] = C1.
2. Set NEWSTR[ 1 ] = C2.
3. Set NEWSTR[ 3 ] = NULL.
4. Return NEWSTR.
5. Exit.
22
CODE:
#include <iostream>
#include <string>
using namespace std;
/* Function prototypes */
void add(int,int);
void add(int,int,int);
float add(int,float);
int add(float,int);
int add(char,char,char);
string add(char,char);
string add(string,string);
/* add() for adding two integers */
void add(int x, int y)
{
int s=x+y;
cout<<"\nA = "<<x<<"\nB = "<<y<<"\nSum = "<<s;
}
/* add() for adding three integers */
void add(int x, int y, int z)
{
int s=x+y+z;
cout<<"\nA = "<<x<<"\nB = "<<y<<"\nC = "<<z<<"\nSum = "<<s;
}
/* add() for adding a integer and a float */
float add(int x, float y)
{
float s=x+y;
cout<<"\nA = "<<x<<"\nB = "<<y;
return s;
}
23
24
25
return(0);
break;
default:
cout<<"\nWrong Input.\n";
break;
}
}
}
OUTPUT:
FUNCTION OVERLOADING
1. Add two integers.
2. Add three integers.
3. Add a integer and a float.
4. Concat two characters.
5. Concat two strings.
6. Add ASCII value of three characters.
7. Exit.
Enter your choice : 1
Enter 1st integer : 15
Enter 2nd integer : 10
A = 15
B = 10
Sum = 25
1. Add two integers.
2. Add three integers.
3. Add a integer and a float.
4. Concat two characters.
5. Concat two strings.
6. Add ASCII value of three characters.
7. Exit.
Enter your choice : 2
Enter 1st integer : 9
Enter 2nd integer : 6
Enter 3rd integer : 5
A=9
B=6
C=5
Sum = 20
1. Add two integers.
2. Add three integers.
3. Add a integer and a float.
4. Concat two characters.
5. Concat two strings.
6. Add ASCII value of three characters.
7. Exit.
26
27
1.
2.
3.
4.
DISCUSSION:
Using the concept of function overloading, we can design a family of functions with one function
name but with different argument lists.
Here we have used overloaded function add() to perform different operations with integers, floats,
characters and strings, using them as arguments.
The function would perform different operations depending on the argument list in the function call.
The correct function to be invoked is determined by checking the number and type of the arguments
but not on the function type.
28
INHERITANCE, VIRTUAL
FUNCTION AND ABSTRACT
CLASS
OBJECTIVE:
We have implemented a C++ program to illustrate inheritance, virtual function and abstract class.
ALGORITHM:
1. Create a class shape with two protected variables D1 an D2 and two public member
functions get_data() and display().
2. Make display() as a pure virtual function.
3. Create three more classes triangle, rectangle and cylinder.
4. These three new classes are derived from class shape.
5. Input base of triangle in D1 and height of triangle in D2.
6. [ Calculate Area of triangle. ]
Set Area = ( D1 + D2 ) / 2.
Display components of triangle by redefining display().
7. Input height of rectangle in D1 and width of rectangle in D2.
8. [ Calculate Area of rectangle. ]
Set Area = D1 * D2.
Display components of rectangle by redefining display().
9. Input radius of cylinder in D1 and height of cylinder in D2.
10. [ Calculate Area of triangle. ]
Set Area = ( D1 + D2 ) / 2.
Display components of cylinder by redefining display().
11. Exit.
CODE:
#include<iostream.h>
#define pi 3.14
class shape
/* This is an abstract class */
{
protected:
double d1,d2;
public:
voidget_data(double,double);
virtual void display()=0;/* Pure virtual function definition */
};
/* derived classes */
classtriangle:public shape
{
29
double area;
public:
void calculate()
{
this->area=(d1*d2)/2; /* Use of this pointer */
}
void display() /* Redefinition of display() function */
{
cout<<"\nBase = "<<d1;
cout<<"\nHeight = "<<d2;
calculate();
cout<<"\nArea = "<<area<<"\n\n";
}
};
classrectangle:public shape
{
double area;
public:
void calculate()
{
area=d1*d2;
/* Without using this pointer */
}
void display() /* Redefinition of display() function */
{
cout<<"\nLength = "<<d1;
cout<<"\nWidth = "<<d2;
calculate();
cout<<"\nArea = "<<area<<"\n\n";
}
};
classcylinder:public shape
{
double area;
public:
void calculate()
{
this->area=pi*d1*d1*d2; /* Using this pointer */
}
void display() /* Redefinition of display() function */
{
cout<<"\nBase = "<<d1;
cout<<"\nHeight = "<<d2;
calculate();
cout<<"\nArea = "<<area<<"\n\n";
}
};
void shape::get_data(double x, double y)
{
d1=x;
d2=y;
}
30
int main()
{
triangle t;
rectangle r;
cylinder c;
doublea,b;
cout<<"\t\tINHERITANCE, ABSTRUCT CLASS AND VIRTUAL FUNCTION\n\n";
cout<<"\n\t\t+++++++++Enter data for triangle+++++++++\n";
cout<<"\nEnter value for base : ";
cin>>a;
cout<<"\nEnter value for heigth : ";
cin>>b;
t.get_data(a,b);
t.display();
cout<<"\n\t\t+++++++++Enter data for rectangle+++++++++\n";
cout<<"\nEnter value for length : ";
cin>>a;
cout<<"\nEnter value for width : ";
cin>>b;
r.get_data(a,b);
r.display();
cout<<"\n\t\t+++++++++Enter data for cylinder+++++++++\n";
cout<<"\nEnter value for radius : ";
cin>>a;
cout<<"\nEnter value for height : ";
cin>>b;
c.get_data(a,b);
c.display();
return 0;
}
OUTPUT:
INHERITANCE, ABSTRUCT CLASS AND VIRTUAL FUNCTION
+++++++++Enter data for triangle+++++++++
Enter value for base : 5
Enter value for heigth : 9
Base = 5
Height = 9
Area = 22.5
+++++++++Enter data for rectangle+++++++++
Enter value for length : 8
Enter value for width : 7
Length = 8
Width = 7
31
Area = 56
+++++++++Enter data for cylinder+++++++++
Enter value for radius : 5
Enter value for height : 7
Base = 5
Height = 7
Area = 549.5
Press any key to continue
1.
2.
3.
DISCUSSION:
We have used this pointer to access the variable area in the class triangle and cylinder. The pointer
this acts as an implicit argument to all the member functions. The same operation can be performed
without using this as in class rectangle.
The function display() in the base class shape is defined as a pure virtual function and is redefined in
all the derived classes.
As the shape contains the pure virtual function display() and no object of shape is created yet, shape
is an abstract base class. The main objective of an abstract base class is to provide some traits to
derived classes and create a base pointer required for achieving runtime polymorphism.
32
QUICKSORT ON AN ARRAY
OF STRINGS :
MANIPULATING STRINGS
OBJECTIVE:
Here we have implemented quick sort to sort an array of strings to sort them in dictionary order.
ALGORITHM:
QUICKSORT (A, LB, UB)
This algorithm sorts the N-element array A using quicksort. LB and UB are respectively the lower
and upper bound of the array A.
1. If LB>=UB, then:
Return.
Else :
(a) Call PARTITION ( A, LB, UB, LOC ).
(b) Call QUICKSORT (A, LB, LOC - 1).
(c) Call QUICKSORT (A, LOC+1, UB).
[End of If structure.]
Exit.
PARTITION(A,BEG,END,LOC)
Here A is a linear array, BEG and END represents lower and upper bound of the array. This
algorithm
finds the proper position of the element in the location LOC in the array.
1. [ Initialize. ] Set LEFT = BEG, RIGHT = END, LOC = BEG.
2. Repeat Step 3 to 7 while LOC <> LEFT or LOC <> RIGHT :
3. Repeat while A[ LOC ]<= A[ RIGHT ] and LOC<>RIGHT :
4.
5.
6.
7.
33
8.
[ End of If structure. ]
[ End of Step 2 loop. ]
Exit.
CODE:
#include<iostream>
#include<string>
using namespace std;
#define MAX 80
void partition(string *A,intbeg,int end, int *loc)
{
stringpivot,temp;
intleft,right;
*loc=left=beg;
right=end;
while(*loc!=left||*loc!=right)
{
while((A[*loc]<=A[right])&&(*loc!=right))
/* Scan elements from right */
right--;
int x=A[*loc].compare(A[right]);
if(x>0)
/* if A[loc]>A[right] interchange these elements */
{
temp=A[*loc];
A[*loc]=A[right];
A[right]=temp;
}
if(*loc!=right)
while((A[*loc]>=A[left])&&(*loc!=left))
/* Scan elements from left */
left++;
x=A[*loc].compare(A[left]);
if(x<0)
/* if A[loc]<A[left] interchange these elements */
{
temp=A[*loc];
A[*loc]=A[left];
A[left]=temp;
}
}
}
voidQuickSort(string *X,intlb,intub)
{
intloc;
if(lb>=ub)
return;
partition(X,lb,ub,&loc); /* Split list */
QuickSort(X,lb,loc-1);
/* Quicksort on left subarray */
QuickSort(X,loc+1,ub);
/* Quicksort on right subarray */
}
int main()
{
stringstr[MAX];
34
char temp[MAX],c;
int n=0,i,flag=1;
cout<<"\t\t\tSORTING OF STRINGS USING QUICKSORT\n";
cout<<"\nPress # to terminate\n";
cout<<"\nEnter Strings :\n";
while(1)
{
gets(temp);
str[n].assign(temp);
c=str[n].at(0); /* Get character in 0th position of str[n] */
if(c=='#')
break;
n++;
}
QuickSort(str,0,n-1);
cout<<"\nSorted Strings are :\n";
for(i=0;i<n;i++)
{
cout<<str[i];
cout<<"\n";
}
cout<<"\n";
return 0;
}
OUTPUT:
SORTING OF STRINGS USING QUICKSORT
Press # to terminate
Enter Strings :
SHOPPING MALL
PARADISE
DICTIONARY
ROUTING
STRING ARRAY
QUICK SORT
#
Sorted Strings are :
DICTIONARY
PARADISE
QUICK SORT
ROUTING
SHOPPING MALL
STRING ARRAY
Press any key to continue
35
DISCUSSION:
1.
2.
3.
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two
smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort
the sub-lists.
Each recursive call to this quicksort function reduces the size of the array being sorted by at
least one element, since in each invocation the element at pivotis placed in its final position.
Therefore, this algorithm is guaranteed to terminate after at most n recursive calls. However,
since partition reorders elements within a partition, this version of quicksort is not a stable
sort.
This program sorts an array of strings. We have used the string classand its member
functions and operators provided by C++ to manipulatethe strings instead of using a
character array.
36
TRANSFORMATION OF INFIX TO
PREFIX EXPRESSION
AND PARENTHESIS CHECKER
OBJECTIVE:
We have implemented a C++ program to transform an infix expression into an equivalent prefix
expression.
ALGORITHM:
INFIXTOPREFIX ( Q, P, STACK )
This algorithm finds the equivalent prefix expression P of an infix expression Q.
1. Push ( onto STACK and add ) to the end of Q.
2. Scan Q from right to left and repeat Steps 3 and 6 for each element of Q until the STACK is
empty.
3.
If an operand is encountered, add it to P.
4.
If an right parenthesis encountered, push it onto STACK.
5.
If an operator 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 .
(b) Add to STACK.
[ End of If structure. ]
6.
If a left parenthesis is encountered then :
(c) Repeatedly pop from STACK and add to P each operator (on the top of STACK)
until a right parenthesis in encountered.
(d) Remove the right parenthesis. [Do not add right parenthesis to P.]
[ End of If structure. ]
[ End of Step 2 loop. ]
7. Reverse P.
8. Exit.
CODE:
#include<iostream>
#include<string>
using namespace std;
#define MAX 20
class convert
{
char stack[MAX];
int top;
public:
char pop();
void push(char);
37
int prcd(char);
int isoperator(char);
void convertip(char *,char *);
int parancheck(char *);
convert()
{
top = -1;
}
};
void convert::push(char item)
{
if(top == (MAX-1))
cout<<"\nStack Overflow\n";
else
stack[++top] = item;
}
/*End of push()*/
char convert::pop()
{
if(top == -1)
return(0);
else
return(stack[top--]);
}
/*End of pop()*/
int convert::prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
return 6;
case '(':
case ')':
case '#':
return 1;
}
return(0);
}
int convert::isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '(':
38
case ')':
return 1;
default:
return 0;
}
}
void convert::convertip(char *infix,char *prefix)
{
int i,symbol,j=0;
char temp[40]={'\0'};
for(i=0;i<strlen(infix);i++)
{
temp[j++]=infix[i];
if(isoperator(infix[i+1])==1)
temp[j++]=' ';
}
temp[j]='\0';
strcpy(infix,temp);
j=0;
infix=strrev(infix);
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
prefix[j++]=symbol;
else
{
if(symbol==')')
push(symbol);
else if(symbol=='(')
{
while(stack[top]!=')')
prefix[j++]=pop();
pop(); /* Pop out ( */
}
else
{
if(prcd(symbol)>prcd(stack[top]))
{
push(symbol);
push(' ');
}
else
{
while(prcd(symbol)<=prcd(stack[top]))
prefix[j++]=pop();
push(symbol);
}
/* End of else */
}
/* End of else */
}
/* End of else */
}
/* End of for */
while(stack[top]!='#')
prefix[j++]=pop();
prefix[j]='\0';//null terminate string.
39
prefix=strrev(prefix);
}
int convert::parancheck(char *exp)
/* Ckheck whether fully paranthesised */
{
char temp;
int i,valid=1,l;
l=strlen(exp);
for(i=0;i<l;i++) /* Can't accept a brace or bracket */
{
if(exp[i]=='{'||exp[i]==']')
{
cout<<"\nOnly paranthesis '()' are accepted.\n";
return(0);
}
}
for(i=0;i<l;i++)
{
if(exp[i]=='(')
push( exp[i] );
if(exp[i]==')') {
if(top == -1) /* Open paranthesis not found */
valid=0;
else
{
temp=pop();
if( exp[i]==')' && temp=='(')
valid=1;
}
/*End of else */
}
}
/*End of for*/
if(top>=0)
/* Closing paranthesis not found */
valid=0;
return(valid);
}
int main()
{
char infix[20],prefix[20];
convert c;
int t;
cout<<"\t\t\tTRANSFORMATION OF INFIX TO PREFIX\n\n";
cout<<"\nEnter A Valid Expression : ";
gets(infix);
t=c.parancheck(infix);
if(t==1)
{
c.convertip(infix,prefix);
cout<<"\nThe Equivalent Prefix Expression is : ";
puts(prefix);
cout<<"\n";
}
else
cout<<"\nInvalid expression.\n\n";
return 0;
}
40
OUTPUT:
TRANSFORMATION OF INFIX TO PREFIX
Enter A Valid Expression : 9 - 8 * ( 4 + 8 ) / 2 ^ 2
The Equivalent Prefix Expression is : ^ / * - 9 8 + 4 8 2 2
Press any key to continue
DISCUSSION:
1.
Here we have implemented the program to transform an infix expression to its equivalent
prefix expression as well as to check whether the infix expression is properly parenthesized.
4.
For the parenthesis checker we have considered only the standard parenthesis (). For an
input expression, it verifies that for each left parenthesis, there is a corresponding closing
symbol and the symbols are appropriately nested.
5. For the infix to prefix approach the given expression may contain left and right parenthesis
besides operators and operands.
We have assumed that the expression contains only the operators +,-,*,/ and ^, and the operands are
given as integers.
41
OBJECTIVE:
This program creates a doubly linked list and performs the following basic operations on it:
1. Creating and deleting a list.
2. Insertion : At beginning, At a given location, At end.
3. Deletion: From beginning, From a given location, From End.
4. Display its forward and backward traversal and sorting.
5. Searching a given node and Count the total no. of nodes.
ALGORITHM:
ALGORITHM FOR CREATING A LIST:
CREATELIST (START, END, DATA, NEXT, PREV )
This algorithm creates a doubly linked list with root node START and tail node END. Each node has
a data part, a PREV pointer to previous node and a NEXT pointer to next node. Here ITEM is an
integer value to be assigned to a node.
1. Create a new node NEWNODE.
2. Set NEWNODE[ DATA ] = ITEM.
NEWNODE[ NEXT ] = NEWNODE[ PREV ] = NULL.
3. Set START= NEWNODE.
4. If more nodes to be inserted, then:
Call CREATELIST(START[ NEXT ], END, DATA, NEXT, PREV ).
Else: END = NEWNODE.
5. Exit.
ALGORITHM FOR INSERTING AN ELEMENT AT THE BEGINNING OF THE LIST:
INSERTBEG (START,END, DATA, NEXT, PREV )
This algorithm inserts ITEM as the first node in the list.
1. Create a new node PTR.
2. Set PTR[ DATA ] = ITEM. [ Copies new data into new node. ]
PTR[ NEXT ] = PTR[ PREV ] = NULL.
3. Set PTR[ NEXT ] = START and START[ PREV ] = PTR. [ Add before START. ]
4. Set START = PTR. [ Changes START so that it points to the new node. ]
5. Exit.
ALGORITHM FOR INSERTION AT A GIVEN LOCATION:
INSERTLOC ( START, END, DATA, NEXT, PREV, ITEM, LOC )
This algorithm inserts ITEM at LOC position.
1. [ Initialize location counter. ] Set POS = 0.
2. Set TEMP = START.
3. If LOC = 0, then: Call INSERTBEG( START, END, DATA,NEXT, PREV,ITEM) and Exit.
4. Repeat while TEMP <> NULL and POS <> LOC: [Search for LOC. ]
42
43
44
3.
4.
5.
6.
CODE:
#include <conio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
typedef class node
{
public:
int data;
class node *next;
class node *prev;
}node;
int size=sizeof(node);
class list
{
node *root,*end;
friend void access();
static int k;
public:
void createlist(node **, node **);
void display(node *,node *);
void insert(node **,node **,int);
void deletenode(node **,node **);
void sort(node **,node **);
int search(node *,int);
int count_nodes(node *,node *);
void deletelist(node **,node **);
list()
{ /* Default constructor definition */
root=end=NULL;
}
};
int list::k; /* Initialize static variable */
void list::createlist(node **head, node **tail)
{
k++;
node *ptr,*newn;
char chk;
do{
newn=(node*)malloc(size);
/* Create a new node */
cout<<"\n\nEnter Value:";
45
cin>>newn->data;
newn->next=NULL;
newn->prev=NULL;
if(*head==NULL)
*head=newn;
else
{
ptr->next=newn;
newn->prev=ptr;
}
ptr=newn;
cout<<"\nWant to add another node [Y/N] : ";
cin>>chk;
}while(chk=='y'||chk=='Y');
*tail=newn;
}
void list::display(node *head, node *tail)
{
node *temp;
temp=head;
cout<<"\nForward Travarsal : root";
while(temp!=NULL) {
cout<<" -> "<<temp->data;
temp=temp->next;
}
cout<<" -> end\n";
temp=tail;
cout<<"Backward Travarsal : end";
while(temp!=NULL) {
cout<<" -> "<<temp->data;
temp=temp->prev;
}
cout<<" -> root\n";
}
void list::insert(node **head, node **tail,int item)
{
int choice,loc=1,info,flag=0;
node *ptr,*temp,*pre;
cout<<"\n\t+++++++++OPTIONS FOR INSERTION+++++++++";
cout<<"\n\t1. Insert at beginning.n\t2. Insert at given location.\n\t3. Insert at end.\n";
cout<<"\n\tSelect where you want to insert...";
cin>>choice;
ptr=(node *)malloc(size);
/* Create a new node */
ptr->data=item;
ptr->next=ptr->prev=NULL;
switch(choice) {
case 1:
ptr->next=*head;
/* Insert before head */
(*head)->prev=ptr;
/* Set as head */
*head=ptr;
flag=1;
break;
46
case 2:
cout<<"\n\tEnter location where "<<item<<" to be inserted : ";
cin>>info;
temp=*head;
if(info==1) { /* Insert as 1st node */
ptr->next=*head;
(*head)->prev=ptr;
*head=ptr;
flag=1;
}
else {
while((temp!=NULL)&&(loc!=info)) { /* Find the location */
pre=temp;
temp=temp->next;
loc++;
}
if(loc!=info)
cout<<"\n\tLocation not found.List has fewer nodes\n";
else {
if(temp==NULL){
pre->next=ptr;
ptr->prev=pre;
*tail=ptr;
flag=1;
}
else {
ptr->next=temp; /* Insert at given location */
temp->prev=ptr;
pre->next=ptr;
ptr->prev=pre;
flag=1;
}
}
}
break;
case 3:
ptr->prev=*tail;
(*tail)->next=ptr;
flag=1;
*tail=ptr;
break;
default:
cout<<"\n\tWrong input.\n";
break;
}
if(flag==1)
cout<<"\n\t"<<item<<" has been inserted in list\n";
}
void list::deletenode(node **head,node **tail)
{
int choice,loc=1,info,item,flag=0;
node *temp,*pre;
47
48
*head=NULL;
*tail=NULL;
flag=1;
}
else{
pre=*tail;
*tail=(*tail)->prev; /* Set the 2nd node as head */
(*tail)->next=NULL;
item=pre->data;
free(pre);
flag=1;
}
break;
default:
cout<<"\n\tWrong input.\n";
break;
}
if(flag==1)
cout<<"\n\t"<<item<<" has been deleted from list\n";
}
void list::sort(node **head,node **tail)
{
node *curr,*save;
int temp;
for(curr=*head;curr->next!=NULL;curr=curr->next){
for(save=curr->next;save!=NULL;save=save->next){
if(curr->data>save->data) { /* Swap values */
temp=curr->data;
curr->data=save->data;
save->data=temp;
}
}
}
}
int list::search(node *head,int item)
{
node *temp;
int loc=1;
temp=head;
while((temp!=NULL)&&(temp->data!=item)) {
/* Search for element */
temp=temp->next;
loc++; /* Store location */
}
if(temp==NULL) /* Search unsuccessful */
return(-1);
else /* item found */
return(loc); /* Return location of item */
}
int list::count_nodes(node *head,node *tail)
{
int count=0;
node *curr;
49
for(curr=head;curr!=NULL;curr=curr->next)
count++; /* Increase counter */
return(count);
}
void list::deletelist(node **head,node **tail)
{
node *ptr;
while(*head!=NULL){
ptr=*head;
*head=(*head)->next;
free(ptr);
}
k=0;
}
void access()
{
list l;
char ck;
int ch,val,count=0,loc;
while(1){
/* Display Menu */
cout<<"\n\t++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++";
cout<<"\n1. Create List.\n2. Display.\n3. Insert.\n4. Delete.\n5. Sort list.";
cout<<"\n6. Search an element.\n7. Count total no. of nodes.\n8. Remove list.\n9. Exit.";
cout<<"\nEnter your choice:";
cin>>ch;
switch(ch){
case 1:
if(l.k!=0){
cout<<"\nA list is already exists.Want to replace it?[Y/N] : ";
cin>>ck;
if(ck=='Y'||ck=='y')
l.createlist(&l.root,&l.end);
}
else
l.createlist(&l.root,&l.end); /* create a new list */
break;
case 2:
if(l.k==0)
cout<<"\n\nCreate a list first\n";
else{
if(l.root==NULL)
cout<<"\nList is empty.\n";
else
l.display(l.root,l.end);
/* call display function */
}
break;
case 3:
if(l.k==0)
{
cout<<"\nList is not created yet.\n\nDo you want to create a list[Y/N]... ";
cin>>ck;
50
if(ck=='Y'||ck=='y')
l.createlist(&l.root,&l.end);
else
break;
}
else /* insert a value in list */
{
cout<<"\nEnter Value to be inserted:";
cin>>val;
l.insert(&l.root,&l.end,val);
l.display(l.root,l.end);
/* call display function */
}
break;
case 4:
if(l.k==0)
cout<<"\nCreate a list first\n";
else
{
if(l.root==NULL)
{
cout<<"\nList is Empty.\n";
break;
}
else /* delete a node from list */
{
l.deletenode(&l.root,&l.end);
l.display(l.root,l.end);
/* call display function */
}
}
break;
case 5:
if(l.k==0)
cout<<"\nCreate a list first\n";
else
{
if(l.root==NULL)
cout<<"\nList is empty.\n";
else
{
l.sort(&l.root,&l.end);
/* sort list in ascending order */
l.display(l.root,l.end);
}
}
break;
case 6:
if(l.k==0)
cout<<"\nCreate a list first\n";
else
{
if(l.root==NULL)
cout<<"\nList is empty.\n";
else
51
{
cout<<"\nEnter value of node to be searched : ";
cin>>val;
loc=l.search(l.root,val);
if(loc==-1)
cout<<"\n"<<val<<" is not in list.";
else
cout<<"\nLocation of "<<val<<" is "<<loc;
}
}
break;
case 7:
if(l.k==0)
cout<<"\nCreate a list first\n";
else
{
count=l.count_nodes(l.root,l.end);
cout<<"\nTotal no. of nodes = "<<count;
}
break;
case 8:
if(l.k==0)
cout<<"\nNo list has been created yet.\n";
else
{
cout<<"\nAll data you inserted is being removed from memory. Do you
agree?[Y/N] ";
cin>>ck;
if(ck=='Y'||ck=='y')
{
l.deletelist(&l.root,&l.end);
/* remove list from memory */
cout<<"\nList has been deleted.\n";
}
}
break;
case 9:
cout<<"\n\n\t\t+++++++++THANK YOU+++++++++\n\n";
exit(0);
break;
default:
cout<<"\n\tWrong input.\n";
break;
}
}
}
int main()
{
access();
return(0);
}
52
OUTPUT:
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 1
Enter Value : 3
Want to add another node [Y/N] : y
Enter Value : 7
Want to add another node [Y/N] : n
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 2
Forward Travarsal : root -> 3 -> 7 -> end
Backward Travarsal : end -> 7 -> 3 -> root
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 3
Enter Value to be inserted : 8
+++++++++OPTIONS FOR INSERTION+++++++++
1. Insert at beginning.
2. Insert at given location.
3. Insert at end.
53
54
Forward Travarsal : root -> 8 -> 7 -> 3 -> 7 -> 9 -> end
Backward Travarsal : end -> 9 -> 7 -> 3 -> 7 -> 8 -> root
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 5
Forward Travarsal : root -> 3 -> 7 -> 7 -> 8 -> 9 -> end
Backward Travarsal : end -> 9 -> 8 -> 7 -> 7 -> 3 -> root
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 7
Total no. of nodes = 5
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 6
Enter value of node to be searched : 8
Location of 8 is 4
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
55
56
57
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 1
A list is already exists.Want to replace it?[Y/N] : n
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 8
All data you inserted is being removed from memory. Do you agree?[Y/N] : y
List has been deleted.
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 2
Create a list first
++++++++++++++LIST OF OPTIONS AVAILABLE++++++++++++++
1. Create List.
2. Display.
3. Insert.
4. Delete.
5. Sort list.
6. Search an element.
7. Count total no. of nodes.
8. Remove list.
9. Exit.
Enter your choice : 9
+++++++++THANK YOU+++++++++
Press any key to continue
58
DISCUSSION:
1.
2.
3.
4.
Every node of a doubly linked list contains an information part which contains the integer
value held by the node and two address part which points to the previous and next nodes.
The normal and reverse both traversal of the list have been displayed. Insertion (or deletion)
of a node can be made at (or from) any position of a list.
To sort the list Bubble Sort technique has been applied.
To search an element from the list linear search has been used.
59
EVALUATION OF POSTFIX
EXPRESSION
OBJECTIVE:
We have implemented a C++ program to transform an infix expression into its equivalent postfix
expression and then toevaluate the postfix equation.
ALGORITHM:
INFIXTOPOSTFIX ( Q, P, STACK )
This algorithm finds the equivalent postfix expression P of an infix expression Q.
1. Push ( onto STACK and add ) to the end of Q.
2. Scan Q from left to right and repeat Steps 3 and 6 for each element of Q until the STACK is
empty.
3. If an operand is encountered, add it to P.
4. If an left parenthesis encountered, push it onto STACK.
5. If an operator is encountered then :
(e) 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 .
(f) Add to STACK.
[ End of If structure. ]
6.
7.
60
CODE:
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
#define MAX 40
class convert
{
char stack[MAX];
double post[MAX];
int top;
public:
char pop();
void push(char);
int prcd(char);
int isoperator(char);
void convertip(char *,char *);
int parancheck(char *);
convert()
{
top = -1;
}
};
class eval
{
double post[MAX];
int top;
public:
double pop();
void push(double);
double evalute(char *);
double calc(double,double,char);
eval()
{
top = -1;
}
};
void convert::push(char item)
{
if(top == (MAX-1))
cout<<"\nStack Overflow\n";
else
stack[++top] = item;
}
/* End of push() */
char convert::pop()
{
if(top == -1)
return(0);
else
return(stack[top--]);
61
}
/* End of pop() */
void eval::push(double item)
{
if(top == (MAX-1))
cout<<"\nStack Overflow\n";
else
post[++top] = item;
}
/* End of push() */
double eval::pop()
{
if(top == -1)
return(0);
else
return(post[top--]);
}
/* End of pop() */
int convert::prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
return 6;
case '(':
case ')':
case '#':
return 1;
}
return(0);
}
int convert::isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '(':
case ')':
return 1;
default:
return 0;
}
}
double eval::calc(double a,double b,char c)
{
/* Calculate result */
62
switch(c)
{
case '+':
return(a+b);
case '-':
return(a-b);
case '*':
return(a*b);
case '/':
return(a/b);
case '^':
return(pow(a,b));
}
return(0);
}
double eval::evalute(char *exp)
{
convert k;
float op1,op2,value;
char op[5]={'\0'};
while(*exp)
{
if(isdigit(*exp)||*exp=='.')
/* if a digit or a decimal found */
{
int i=0;
while(*exp!=' ')
/* retrive the full number */
{
op[i++]=*exp;
exp++;
}
op[i]='\0';
double c=atof(op);/* convert the number from character to type double */
push(c);
}
else if(k.isoperator(*exp))
/* if an operator found */
{
/* perform calculation */
op2=pop();
op1=pop();
value=calc(op1,op2,*exp);
push(value);
/* save the intermediate value in stack */
}
exp++;
}
return(pop());
}
void convert::convertip(char *infix,char *postfix)
{
int i,symbol,j=0;
char temp[MAX]={'\0'};
for(i=0;i<strlen(infix);i++)
{
temp[j++]=infix[i];
63
if(isoperator(infix[i+1])==1)
temp[j++]=' ';
}
temp[j]='\0';
strcpy(infix,temp);
j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
postfix[j++]=symbol;
else
{
if(symbol=='(')
push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j++]=pop();
postfix[j++]=' ';
}
pop(); /* Pop out '(' */
}
else
{
if(prcd(symbol)<=prcd(stack[top]))
{
postfix[j++]=pop();
postfix[j++]=' ';
push(symbol);
}
else
push(symbol);
/*End of else */
}
/* End of else */
}
/* End of else */
}
/* End of for */
while(stack[top]!='#')
{
postfix[j++]=' ';
postfix[j++]=pop();
postfix[j++]=' ';
}
postfix[j]='\0';//null terminate string.
}
int convert::parancheck(char *exp)
{
char temp;
64
int i,valid=1,l;
l=strlen(exp);
for(i=0;i<l;i++) /* Can't accept a brace or bracket */
{
if(exp[i]=='{'||exp[i]==']')
{
cout<<"\nOnly parenthesis '()' are accepted.\n";
return(0);
}
}
for(i=0;i<l;i++)
{
if(exp[i]=='(')
push( exp[i] );
if(exp[i]==')')
{
if(top == -1) /* Open parenthesis not found */
valid=0;
else
{
temp=pop();
if( exp[i]==')' && temp=='(')
valid=1;
}
/* End of else */
}
}
/* End of for */
if(top>=0)
/* Closing parenthesis not found */
valid=0;
return(valid);
}
int main()
{
char infix[MAX],postfix[MAX];
eval e;
convert c;
int t;
cout<<"\t\t TRANSFORMATION OF INFIX TO POSTFIX\n\t\tAND EVALUATION OF
THE
POSTFIX EQUATION\n\n";
cout<<"\nEnter A Valid Expression : ";
gets(infix);
t=c.parancheck(infix);
if(t==1)
{
c.convertip(infix,postfix);
cout<<"\nThe Equivalent postfix Expression is : ";
puts(postfix);
cout<<"\nResult = "<<e.evalute(postfix);
cout<<"\n\n";
}
else
cout<<"\nInvalid expression.\n\n";
return 0;
}
65
OUTPUT:
TRANSFORMATION OF INFIX TO POSTFIX
AND EVALUATION OF THE POSTFIX EQUATION
Enter A Valid Expression : 0 . 5 * ( ( 1 9 - 2 . 5 ) + 4 ) / 2 ^ 2
The Equivalent postfix Expression is : 0. 5 19 2. 5 - 4 + * 2 2 ^ /
Result = 2.5625
Press any key to continue
DISCUSSION:
1.
2.
3.
Here we have implemented the program to transform an infix expression to its equivalent
postfix expression as well as to evaluate the postfix expression.
For the infix to postfix approach the given expression may contain left and right parenthesis
besides operators and operands.
We have assumed that the expression contains only the operators +,-,*,/ and ^, and the
operands are given as integers.
66
10
BINARY SEARCH
TREE
OBJECTIVE:
This program creates a binary search tree performs the following operations on it:
1. Insert an element.
2. Delete an element.
3. Traverse in preorder.
4. Traverse in inorder.
5. Traverse in postorder.
ALGORITHM:
ALGORITHM FOR INSERTING AN ELEMENT IN THE TREE:
INSERT ( ROOT, DATA, LEFT, RIGHT, ITEM )
This algorithm inserts ITEM in the tree.
1. If ROOT = NULL, then:
(a) Create a new binary search tree.
(b) Insert ITEM as root.
(c) Set ROOT[ LEFT ] = NULL and ROOT[ RIGHT ] = NULL.
Else:
(a) If ITEM <ROOT[ DATA ], then: Insert ITEM in left sub-tree.
(b) Else If ITEM >ROOT[ DATA ], then: Insert ITEM in right sub-tree.
(c) Else Write: Duplicate Data.
[End of If structure.]
[End of If structure.]
2. Exit.
ALGORITHM FOR DELETING AN ELEMENT FROM THE TREE:
DELETE( ROOT, DATA, LEFT, RIGHT, ITEM )
This algorithm deletes ITEM in the tree T.
1. If ROOT = NULL, then :
Write : ITEM not in tree.
Return.
Else PAR = ROOT.
[ End of If Structure. ]
2. If ITEM <PAR[DATA], then :
Call DELETE ( PAR, DATA, LEFT, RIGHT, ITEM ).
3. Else If ITEM > DATA, then :
Call DELETE ( PAR, DATA, LEFT, RIGHT, ITEM ).
4. Else If PAR has left and right child, then :
Replace PAR with largest node in left child.
5. Else
(a) If PAR is terminal node, then :
67
CODE:
#include<iostream.h>
#include<stdlib.h>
typedef class node{
public:
int info;
class node *left,*right;
} BST;
/* define tree structure */
class tree{
BST *root;
friend void access();
public:
BST *getnode();
void insert();
void del(BST **,int);
BST *findlargest(BST *);
voidinorder(BST *);
void preorder(BST *);
voidpostorder(BST *);
tree() {
root='\0';
}
};
BST *tree::getnode() {
68
BST *p;
p=new BST; /* create node */
return(p);
}
void tree::insert() {
int data;
BST *ptr,*prev,*p;
cout<<"\nEnter value : ";
cin>>data; /* take input of data of the child node */
ptr=root;
while(ptr!='\0'&&ptr->info!=data) {
if(ptr->info<data)
{
prev=ptr;
ptr=ptr->right;
}
else
{
prev=ptr;
ptr=ptr->left;
}
}
if(ptr!='\0')
cout<<"\nDuplicate value is not allowed.\n";
else
{
p=getnode();
p->info=data;
p->left=p->right='\0';
if(prev->info<data){
cout<<"\nInserted at RIGHT of "<<prev->info<<"\n";
prev->right=p;
}
else
{
cout<<"\nInserted at LEFT of "<<prev->info<<"\n";
prev->left=p;
}
}
}
BST *tree::findlargest(BST *tree){
if((tree==NULL)||(tree->right==NULL))
return tree;
else
returnfindlargest(tree->right);
}
void tree::del(BST **tree, int data){
BST *ptr;
if(*tree==NULL)
cout<<data<<" not in tree\n";
else if(data<(*tree)->info)
del(&((*tree)->left),data);
else if(data>(*tree)->info)
del(&((*tree)->right),data);
else if((*tree)->left&&(*tree)->right) {
ptr=findlargest((*tree)->left);
/* Replace with largest element of left sub tree */
69
(*tree)->info=ptr->info;
del(&((*tree)->left),ptr->info);
}
else
{
ptr=*tree;
/* terminal node */
if(((*tree)->left==NULL)&&((*tree)->right==NULL))
*tree=NULL;
else if((*tree)->left!=NULL)
/* Left child only */
*tree=(*tree)->left;
else
/* Right child only */
*tree=(*tree)->right;
free(ptr);
}
}
void tree::inorder(BST *p) {
if(p!='\0')
{
inorder(p->left);
cout<<p->info<<"\t";
/* display the data after inorder traversing */
inorder(p->right);
}
}
void tree::preorder(BST *p)
{
if(p!='\0') {
cout<<p->info<<"\t";
/* display the data after preorder traversing */
preorder(p->left);
preorder(p->right);
}
}
void tree::postorder(BST *p){
if(p!='\0')
{
postorder(p->left);
postorder(p->right);
cout<<p->info<<"\t";
/* display the data after postorder traversing */
}
}
void access()
{
intele,ch;
tree t;
cout<<"\t\tIMPLEMENTATION OF BINARY SEARCH TREE";
cout<<"\n\nEnter value for root : ";
cin>>ele; /* take the input of the root */
t.root=t.getnode();
t.root->info=ele;
t.root->left=t.root->right='\0';
while(1)
{
cout<<"\n1. Insert\n2. Delete a node.\n3. Preorder Traversing.\n4.Inorder Traversing\n5.
Postorder Traversing.\n6. Exit.\n";
cout<<"\nEnter your choice: ";
cin>>ch;
70
switch(ch)
{
case 1:
t.insert(); /* call the function insert() to insert data in node */
break;
case 2:
cout<<"\nEnter value : ";
cin>>ele;
t.del(&t.root,ele);
break;
case 3:
cout<<"\nPreorder Traversal:\n";
t.preorder(t.root);
cout<<"\n"; /* call inorder function for inorder traversing */
break;
case 4:
cout<<"\nInorder Traversal:\n";
t.inorder(t.root);
/* call preorder function for preorder traversing */
cout<<"\n";
break;
case 5:
cout<<"\nPostorder Traversal:\n";
t.postorder(t.root);/* call postorder function for postorder traversing */
cout<<"\n";
break;
case 6:
exit(0);
default:
cout<<"\nInvalid choice.\n";
}
}
}
int main()
{
access();
return(0);
}
OUTPUT:
IMPLEMENTATION OF BINARY SEARCH TREE
Enter value for root : 25
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
71
Enter value : 32
Inserted at RIGHT of 25
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
Enter value : 15
Inserted at LEFT of 25
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
Enter value : 68
Inserted at RIGHT of 32
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
Enter value : 28
Inserted at LEFT of 32
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
72
Enter value : 18
Inserted at RIGHT of 15
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 1
Enter value : 11
Inserted at LEFT of 15
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 3
Preorder Traversal :
25 15 11 18
32
28
68
32
68
32
25
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 4
InorderTraversal :
11 15 18 25
28
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 5
PostorderTraversal :
11 18 15 28
68
73
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 2
Enter value : 32
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 3
Preorder Traversal :
25 15 11 18
28
68
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 4
InorderTraversal :
11 15 18 25
28
68
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
5. Postorder Traversing.
6. Exit.
Enter your choice : 5
PostorderTraversal :
11 18 15 68
28
1. Insert
2. Delete a node.
3. Preorder Traversing.
4. Inorder Traversing
25
74
5. Postorder Traversing.
6. Exit.
Enter your choice : 6
Press any key to continue
DISCUSSION:
1.
2.
The value of key in left sub-tree is always smaller than root and the value of key in right subtree is always larger than root. All sub-trees of the left & right children observe these two
rules.
3.
4.
While deleting a node from the tree we can replace the node with the largest element of its
left sub tree or the smallest element of its right sub tree. Here we have used largest of left sub
tree.
75