CS2209 - Oops Lab Manual
CS2209 - Oops Lab Manual
III SEMESTER
Prepared by:
E. Manosri
N.K Rejin Paul
S. Selvakanmani
SYLLABUS
1. Design C++ classes with static members, methods with default arguments, friend
functions. (For example, design matrix and vector classes with static allocation, and a
friend function to do matrix-vector multiplication)
2. Implement complex number class with necessary operator overloadings and type
conversions such as integer to complex, double to complex, complex to double etc.
3. Implement Matrix class with dynamic memory allocation and necessary methods. Give
proper constructor, destructor, copy constructor, and overloading of assignment
operator.
4. Overload the new and delete operators to provide custom dynamic allocation of memory.
5. Develop a template of linked-list class and its methods.
6. Develop templates of standard sorting algorithms such as bubble sort, insertion sort,
merge sort, and quick sort.
7. Design stack and queue classes with necessary exception handling.
8. Define Point class and an Arc class. Define a Graph class which represents graph as a
collection of Point objects and Arc objects. Write a method to find a minimum cost
spanning tree in a graph.
9. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle,
Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic
polymorphism and RTTI.
10. Write a C++ program that randomly generates complex numbers (use previously
designed Complex class) and writes them two per line in a file along with an operator (+,
-, *, or /). The numbers are written to file in the format (a + ib). Write another program to
read one line at a time from this file, perform the corresponding operation on the two
complex numbers read, and write the result to another file (one per line).
1. PC – 30 nos.
• Processor – 2.0 GHz or higher
• RAM – 256 MB or higher
• Hard disk – 20 GB or higher
• OS- Windows 2000/ Windows XP/ NT
2. Software – Turbo C (freeware) – to be installed in all PC’s.
LIST OF EXPERIMENTS
Aim:
To write a C++ program to demonstrate the static members
Algorithm:
Step 1: Start the program.
Step 2: Create a class with static data members and static function.
Step 3: The static value is initialized to zero during object creation. The static value is
incremented when a member function set is called for every object.
Step 4: We can also reinitialize the static member value during the static member definition.
Step 5: The result is displayed.
Step 6: Stop the process.
Program:
#include<iostream.h>
#include<conio.h>
class staticmember
{
int a;
static int count,cnt;
public:
void set()
{
a=++count;
cnt++;
}
void show()
{
cout<<"\n";
cout<<"Object Number:"<<a<<"\n";
}
static void showcount()
{
cout<<"Static count value:"<<count<<"\n";
cout<<"Static cnt value:"<<cnt<<"\n";
}
};
int staticmember::count;
int staticmember::cnt = 100;
void main()
{
staticmember s1,s2,s3;
clrscr();
s1.set();
s1.show();
cout<<endl;
s2.set();
staticmember::showcount();
s2.show();
cout<<endl;
s3.set();
staticmember::showcount();
s3.show();
cout<<endl;
getch();
}
Output:
Object Number:1
Object Number:2
Object Number:3
Result:
Thus the C++ program was executed and the output is verified.
CALCULATION OF BANK INTEREST USING DEFAULT ARGUMENT
AIM:
To calculate bank interest using the concept of default arguments
ALGORITHM:
1. Start the process.
2. Create a class with sufficient data members and two member functions.
3. The default values are specified in the class
4. The two member functions are defined outside the class.
5. The object is created for the class and the member function is called from the main
function.
6. The function assigns a default values to the parameter which does not have a matching
argument and function call.
7. If the values for the parameter are specified then the default value is not taken.
8. The bank interest is calculated.
9. Display the result.
10. Stop the process.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class arg
{
float sum,amount,p,n,r;
public:
float value(float p,int n,float r=0.15);
void print(char ch='*', int len=13);
};
float arg::value(float p,int n, float r)
{
int year=1;
float sum=p;
while(year<=n)
{
sum=sum*(1+r);
year=year+1;
}
return(sum);
}
void arg:: print(char ch, int len)
{
for(int i=1;i<=len;i++)
cout<<ch;
cout<<"\n";
}
void main()
{
arg a1;
float tot, res;
clrscr();
a1.print();
tot=a1.value(5000,5);
cout<<tot<<endl;
a1.print();
cout<<endl;
res=a1.value(5000,1,0.20);
cout<<res;
getch();
}
OUTPUT:
****************************
10056.786133
****************************
6000
RESULT:
Thus the program for calculation of simple interest using default arguments was executed.
MATRIX MULTIPLICATION USING FRIEND FUNCTIONS
AIM:
To write a program for matrix multiplication using friend functions using C++.
ALGORITHM:
PROGRAM
#include<iostream.h>
#include<conio.h>
class matrix
{
int a[5][5],b[5][5],d[5][5];
int i,j,k,l,m,r,c;
public:
void get();
friend void multiply(matrix m1);
};
void matrix::get()
{
cout<<"\n Enter the dimension (n*m) of the first matrix:";
cin>>r>>c;
cout<<"\n Enter "<< r*c <<" element:";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cin>>a[i][j];
}
}
cout<<"\n The value of the first matrix:";
for(i=0;i<r;i++)
{
cout<<"\n";
for(j=0;j<c;j++)
{
cout<<a[i][j]<<"\t";
}
}
}
void multiply(matrix m1)
{
int i,j,k;
char ch='y';
do
{
cout<<"\n Enter the dimension (n*m) for the second matrix:";
cin>>m1.l>>m1.m;
cout<<"\n Enter "<< m1.l*m1.m <<" element:";
for(i=0;i<m1.l;i++)
{
for(j=0;j<m1.m;j++)
{
cin>>m1.b[i][j];
}
}
cout<<"\n The value of the second matrix:";
for(i=0;i<m1.l;i++)
{
cout<<"\n";
for(j=0;j<m1.m;j++)
{
cout<<m1.b[i][j]<<"\t";
}
}
if(m1.r==m1.m)
{
for(i=0;i<m1.l;i++)
{
for(j=0;j<m1.m;j++)
{
m1.d[i][j]=0;
for(k=0;k<m1.m;k++)
m1.d[i][j]=m1.a[i][k]*m1.b[k][j]+m1.d[i][j];
}
}
cout<<"\n Resultant Matrix:";
for(i=0;i<m1.l;i++)
{
cout<<"\n";
for(j=0;j<m1.m;j++)
cout<<m1.d[i][j]<<"\t";
}
}
else
cout<<"\n Rows and Columns are inequal; Muliplication is not possible";
cout<<"\n Do you want to multiply one more matrix:";
cin>>ch;
}
while(ch=='y');
}
void main()
{
clrscr();
matrix m1;
m1.get();
multiply(m1);
getch();
}
OUTPUT:
Enter 4 element:1 2 3 4
Enter 4 element:4 5 6 7
RESULT:
Thus the program for matrix multiplication using friend functions was written and
executed.
IMPLEMENTATION OF COMPLEX NUMBER OPERATIONS USING OPERATOR
OVERLOADING
AIM :
To write a C++ program to implement the complex number operations using operator
overloading.
ALGORITHM:
#include <math.h>
#include <iostream.h>
#include <iomanip.h>
#include<conio.h>
class complex
{
private:
float real; // Real Part
float imag; // Imaginary Part
public:
complex(float,float);
complex operator +(complex);
complex operator -(complex);
complex operator *(complex);
complex operator /(complex);
void printdata();
};
// CONSTRUCTOR
complex::complex(float r=0.0f,float im=0.0f)
{
real=r;
imag=im;
}
complex complex::operator +(complex c)
{
complex tmp=c;
tmp.real=this->real+tmp.real;
tmp.imag=this->imag+tmp.imag;
return tmp;
}
complex complex::operator -(complex c)
{
complex tmp=c;
tmp.real=this->real - tmp.real;
tmp.imag=this->imag - tmp.imag;
return tmp;
}
complex complex::operator *(complex c)
{
complex tmp=c;
tmp.real=(real*tmp.real)-(imag*tmp.imag);
tmp.imag=(real*tmp.imag)+(imag*tmp.real);
return tmp;
}
complex complex::operator /(complex c)
{
complex tmp=c;
float res= (imag*tmp.real)-(real*tmp.imag);
float div=(tmp.real*tmp.real)+(tmp.imag*tmp.imag);
tmp.real=(real*tmp.real)+(imag*tmp.imag);
tmp.real/=div;
tmp.imag= res;
tmp.imag/=div;
return tmp;
}
void complex::printdata()
{
cout<<real<<" + ("<<imag<<")j\n";
}
void main()
{
complex c1(5,3),c2(3,2),c3; // Calls Constructor
clrscr();
c3=c1+c2; // Calls overloaded +
cout<<"\nComplex addition:\n";
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex subtraction:\n";
c3=c1-c2; // Calls overloaded -
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex multiplication:\n";
c3=c1*c2; // Calls overloaded *
c1.printdata();
c2.printdata();
c3.printdata();
cout<<"\nComplex division:\n";
c3=c1/c2; // Calls overloaded /
c1.printdata();
c2.printdata();
c3.printdata();
getch();
}
OUTPUT:
Complex addition:
5 + (3)j
3 + (2)j
8 + (5)j
Complex subtraction:
5 + (3)j
3 + (2)j
2 + (1)j
Complex multiplication:
5 + (3)j
3 + (2)j
9 + (37)j
Complex division:
5 + (3)j
3 + (2)j
1.615385 + (-0.076923)j
RESULT:
Thus the program to implement the complex number operations using operator overloading.
Complex Numbers with Operator Overloading and Type Conversion
Aim:
To write a C++ program to implement complex number class with necessary operator
overloading and type conversion
Algorithm:
Step 1: Start the program.
Step 2: Create a class Complex.
Step 3: Define the default and two parameterized constructors. One constructor is having two
integer arguments and another one will have the two double data type arguments
Step 4: Declare the operator function which are going to be overloaded.
Step 5: Define the overloaded functions such as +,-,*,/,>>,<<.
Step 6: Create the objects and pass the complex values.
Step 7: Invoke the overloaded functions.
Step 8: Display the converted result.
Step 9: Stop the process.
Program:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class complex
{
private:
float real;
float imag;
public:
complex()
{
real=imag=0.0;
}
complex(int r,int i) //conversion constructor
{
real = r;
imag = i;
}
complex(double r, double i)//conversion constructor
{
real = r;
imag = i;
}
friend istream& operator>>(istream &, complex &);
friend ostream& operator<<(ostream &, complex &);
complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
complex operator/(complex);
friend double condou(complex t); //complex–>double
};
double condou(complex t)
{
return t.real+t.imag;
}
istream& operator >>(istream &in, complex &c)
{
cout<<”\nReal Part:”;
in>>c.real;
cout<<”Imag Part:”;
in>>c.imag;
return in;
}
ostream& operator<<(ostream &out, complex &c)
{
if (c.imag<0)
out<<c.real<<c.imag<<”i”;
else
out<<c.real<<”+”<<c.imag<<”i”;
return out;
}
complex complex::operator+(complex c)
{
complex temp;
temp.real = real+c.real;
temp.imag = imag+c.imag;
return temp;
}
complex complex::operator-(complex c)
{
complex temp;
temp.real = real-c.real;
temp.imag = imag-c.imag;
return temp;
}
complex complex::operator*(complex c)
{
complex temp;
float t=c.real;
temp.real = real*c.real-imag*c.imag;
temp.imag = real*c.imag+imag*t;
return temp;
}
complex complex::operator/(complex c)
{
complex temp;
float qt;
float res=(imag*c.real-real*c.imag);
qt = c.real*c.real+c.imag*c.imag;
temp.real = (real*c.real+imag*c.imag)/qt;
temp.imag = res/qt;
return temp;
}
void main()
{
complex c1, c2, c3,c4(4,9),c5(3.23004,4.666304444);
double t;
clrscr();
t=condou(c5);
cout<<”\nEnter complex number 1: “;
cin>>c1;
cout<<”\nEnter complex number 2: “;
cin>>c2;
cout<<”\nEnter complex numbers are:”;
cout<<”\nComplex 1: “<<c1;
cout<<”\nComplex 2: “<<c2;
c3=c1+c2;
cout<<”\nResult of addition is:”<<c3;
c3=c1-c2;
cout<<”\nResult of subtraction is:”<<c3;
c3=c1*c2;
cout<<”\nResult of multiplication is:”<<c3;
c3=c1/c2;
cout<<”\nResult of division is:”<<c3;
cout<<”\nInteger–>complex:”<<c4;
cout<<”\nDouble–>complex:”<<c5;
cout<<”\nConverted to double”<<t;
getch();
}
OUTPUT:
Result:
Thus the program for operator overloading for complex numbers and their type
conversions was executed.
Matrix Class with Constructor, Destructor, Copy constructor and Assignment operator
overloading
Aim:
To implement Matrix class with dynamic memory allocation with constructors,
destructor, and overloading of assignment operator.
Algorithm:
1. Start the process.
2. Create a class matrix.
3. Declare and define default, parameterized, copy constructor.
4. Define member functions getmatrix and showmatrix.
5. Define destructor.
6. Get the size of the matrix and the elements of the matrix.
7. Depends on the size of the matrix, the memory is allotted for the matrix dynamically.
8. Get the elements of the matrix.
9. Call the copy constructor and copy the values of object m1 to m2.
10. With the help of assignment operator, we are assigning the values of m1 to m3.
11. Display the result.
12. Stop the process.
Program :
#include<iostream.h>
#include<conio.h>
class matrix
{
int **m;
int row, col;
public:
matrix()
{
row=col=0;
m=NULL;
}
matrix(int r ,int c);
~matrix();
void getmatrix();
void showmatrix();
matrix(matrix &m2); //copy constructor
matrix& operator=(matrix &m2);
};
matrix::~matrix()
{
for(int i=0;i<row;i++)
delete m[i];
delete m;
}
matrix::matrix(int r ,int c)
{
row=r;
col=c;
m=new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
}
matrix::matrix(matrix &m2)
{
cout<<"\nCopy constructor invoked\n";
row=m2.row;
col=m2.col;
m=new int*[row];
for(int i=0;i<=row;i++)
m[i]=new int[col];
for(i=0;i<=row;i++)
for(int j=0;j<=row;j++)
m[i][j]=m2.m[i][j];
}
matrix& matrix::operator=(matrix &m2)
{
cout<<"\nAssignment Operator Overloading\n";
row = m2.row;
col = m2.col;
m = new int*[row];
for(int i=0;i<=row;i++)
m[i]=new int[col];
for(i=0;i<=row;i++)
for(int j=0;j<=row;j++)
m[i][j]=m2.m[i][j];
return *this;
}
void matrix::getmatrix()
{
for(int i=0;i<row;i++)
for(int j=0; j<col; j++)
cin>>m[i][j];
}
void matrix::showmatrix()
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
cout<<"\t"<<m[i][j];
cout<<"\n";
}
}
void main()
{
int r,c;
clrscr();
cout<<"\nEnter rows and columns of the matrix:\n";
cin>>r>>c;
matrix m1(r,c);
cout<<"\nEnter the matrix elements one by one:\n";
m1.getmatrix();
cout<<"\nEntered matrix is:\n";
m1.showmatrix();
//invoking copy constructor
matrix m2=m1;
cout<<"\nResult of the copy constructor is:\n";
m2.showmatrix();
matrix m3;
m3=m1;
cout<<"\nResult of assignment operator overloading:\n";
m3.showmatrix();
getch();
}
OUTPUT 1:
Output 2:
Result:
Thus the program for constructor, destructor, copy constructor and assignment operator
overloading was executed.
OVERLOADING NEW AND DELETE OPERATOR
AIM:
To write a C++ program to implement the overloading of new and delete operators to
provide dynamic allocation of memory
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class op
{
public:
void *operator new(size_t size, char const *file,int line);
void operator delete(void *p);
};
void *op::operator new(size_t size, char const *file,int line)
{
void *p = malloc(size);
cout<<"\n New called the file:"<<file<<"\n line:"<<line<<"\n size:"<<size<<"\n p:"<<p<<endl;
return p;
}
void op::operator delete(void *p)
{
cout<<"\n Delete called p:"<<p<<endl;
free(p);
}
void main()
{
clrscr();
op *X = new(__FILE__,__LINE__)op;
delete X;
getch();
}
OUTPUT:
RESULT:
Thus the C++ program to implement the overloading of new and delete operators to
provide dynamic allocation of memory was executed.
CREATING LINKED LIST USING TEMPLATES
AIM:
To write a program top perform various operations in a linked list using templates.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<process.h>
template<class T>
class list
{
private:
int data;
list *next;
public:
list()
{
data = 0.0;
next = NULL;
}
list(int dat)
{
data =dat;
next = NULL;
}
void insert(list *node);
void display(list *);
};
template<class T>
void list<T>::insert(list<T> *node)
{
list *last = this;
while(last ->next)
last = last ->next;
last->next = node;
}
template<class T>
void list<T>::display(list<T> *first)
{
list *traverse;
for(traverse=first;traverse;traverse=traverse->next)
cout<<traverse->data;
cout<<endl;
}
void main()
{
int choice1,data;
list<int> *first = NULL;
list<int> *node;
while(1)
{
cout<<"\n Linked list using Templates";
cout<<"\n 1. Insert the element";
cout<<"\n 2. Display the elements:";
cout<<"\n 3. Quit";
cout<<"\n Enter your choice:";
cin>>choice1;
switch(choice1)
{
case 1:
cout<<"\n enter data:";
cin>>data;
node=new list<int>(data);
if(first==NULL)
first = node;
else
first -> insert(node);
break;
case 2:
first ->display(first);
break;
case 3:
exit(1);
}
}
}
OUTPUT:
enter data:12
enter data:23
enter data:10
RESULT:
Thus the program for linked list using template was executed using C++ .
IMPLEMENTATION OF BUBBLE SORT
AIM:
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
template <class t>
class bubble
{
t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void bubble <t>::get(int n)
{
int i;
cout<<"\nEnter the array elements:";
for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void bubble <t>::display(int n)
{
int i;
cout<<"\nThe sorted array is:\t";
for(i=0;i<n;i++)
cout<<a[i]<<setw(10);
}
template <class t>
void bubble <t>::sort(int n)
{
int i,j;
t temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void main()
{
int n,m;
bubble<int> b1;
bubble<float> b2;
clrscr();
cout<<"\n----Bubble Sort on Integer Values----";
cout<<"\nEnter the size of array:\n";
cin>>n;
b1.get(n);
b1.sort(n);
b1.display(n);
cout<<"\n\n----Bubble Sort on Float values----\n";
cout<<"\nEnter the size of array:\n";
cin>>m;
b2.get(m);
b2.sort(m);
b2.display(m);
getch();
}
OUTPUT:
RESULT:
Thus the program to implement Bubble Sort using templates was executed.
INSERTION SORT USING TEMPLATES
Aim:
To write a program to implement insertion sort using templates.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
template <class t>
class insertion
{
t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void insertion<t>::get(int n)
{
int i;
cout<<"\nEnter the array elements:";
for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void insertion <t>::display(int n)
{
int i;
cout<<"\nThe sorted array is: \t";
for(i=0;i<n;i++)
cout<<a[i]<<setw(10);
}
template <class t>
void insertion <t>::sort(int n)
{
int i,j;
t temp;
for(i=1;i<n;i++)
{
j=i;
while(j>=1)
{
if(a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
j--;
}
}
}
void main()
{
int n,m;
insertion<int> i1;
insertion<float> i2;
clrscr();
cout<<"\nInsertion Sort on Integer Values\n";
cout<<"\nEnter the size of array:\t";
cin>>n;
i1.get(n);
i1.sort(n);
i1.display(n);
cout<<"\n\nInsertion Sort on Float Values\n";
cout<<"\nEnter the size of array:\t";
cin>>m;
i2.get(m);
i2.sort(m);
i2.display(m);
getch();
}
OUTPUT:
RESULT:
Thus the program to implement insertion sort using templates was executed.
MERGE SORT USING TEMPLATES
AIM:
To write a program to implement merge sort using templates.
ALGORITHM:
Step 1: Start the process.
Step 2: Get the number of elements to be sorted.
Step 3: At every pass, one element is placed in the correct position.
Step 4: The initially sorted position is null and the complete list is unsorted with every pass, the
sorted portion grows by one element and the unsorted portion shrinks by one element.
Step 5: If the interchange has occurred then the current position of the data will be moved.
Step 6: The passes can be stopped if there is no interchange in the current pass. No interchange
indicates that the elements are sorted.
Step 7: Stop the process.
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
template<class t>
class sort
{
t a[10];
public:
void get(int);
void merge(int,int);
void mergesort(int,int,int);
void display(int);
};
template<class t>
void sort<t>::get(int n)
{
int i;
cout<<"\n\n Enter the Array Elements:";
for(i=1;i<=n;i++)
cin>>a[i];
}
template<class t>
void sort<t>::display(int n)
{
int i;
cout<<"\n The Sorted Array is\n";
for(i=1;i<=n;i++)
cout<<a[i]<<setw(5);
}
template<class t>
void sort<t>::merge(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge(low,mid);
merge(mid+1,high);
mergesort(low,mid,high);
}
}
template<class t>
void sort<t>::mergesort(int low,int mid,int high)
{
t b[10];
int h,i,j,k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h=h+1;
}
else
{
b[i]=a[j];
j=j+1;
}
i=i+1;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i=i+1;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i=i+1;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
void main()
{
int n;
clrscr();
cout<<"\n\t\t Merge Sort Using Templates";
cout<<"\n\t\t~~~~~~~~~~~~~~~~~~~~~";
sort<int>n1;
sort<float>n2;
cout<<"\n Enter the Array Size:";
cin>>n;
cout<<"\n----Integer values----\n";
n1.get(n);
n1.merge(1,n);
n1.display(n);
cout<<"\n\n----Float values----\n";
n2.get(n);
n2.merge(1,n);
n2.display(n);
getch();
}
OUTPUT:
----Float values----
Enter the Array Elements:12.4 34.6 67.8 13.9 33.2
RESULT:
Thus the program to implement Merge Sort using Templates was executed.
IMPLEMENTATION OF QUICK SORT
AIM:
To sort the elements using the quick sort.
ALGORITHM:
Step 1:Start the process.
Step 2:Get the values from the user.
Step 3:Position a pointer ‘low’ to the second element and a pointer ‘HIGH’ to the last element.
Step 4:Move ‘low’ forward till it reaches an element greater than k1.
Step 5:Move ‘high’ backward till it reaches an element less than k1.
Step 6:Interchange klow and khigh if low<high.
Step 7:Continue steps 2 to 4 till low<high.
Step 8:Swaps the elements at first and high indices.
PROGRAM:
#include <iostream.h>
#include <conio.h>
#include <process.h>
template <class T>
class QUICK_SORT
{
private:
T a[20];
int low, high, size;
public:
QUICK_SORT(int n)
{size=n;
}
void Get_Data();
void Quick(int low, int high);
int Partition(int low, int high);
void Display_Data();
};
template<class T>
void QUICK_SORT<T>::Get_Data()
{ cout<<"Enter the elements to be inserted" << endl;
for(int i=0; i<size; i++)
cin >> a[i];
}
template<class T>
void QUICK_SORT<T>::Quick(int low, int high)
{ int j;
if(low <= high)
{ j=Partition(low,high);
Quick(low, j-1);
Quick(j+1, high);
}} template<class T>
int QUICK_SORT<T>::Partition(int low, int high)
{ int i, j;
T key;
i = low + 1;
j = high;
key = a[low];
while(1)
{
while(i < high && key >= a[i]) i++;
while(key <a[j]) j--;
if(i < j)
{
T temp = a[i];
a[i] = a[j];
a[j] = temp;
} else
{
T temp = a[j];
a[j] = a[low];
a[low] = temp;
return j;
}
}
//end while
}//end QUICK_SORT<T>
template<class T>
void QUICK_SORT<T>::Display_Data()
{ int i;
cout << "The sorted list is:";
for(i=0; i<size; i++)
cout <<a[i]<<"\t";
cout << endl;
}
void main()
{ int n, ch;
clrscr();
cout<<"Enter number of data: ";
cin>>n; cout << endl;
QUICK_SORT<int>Q1(n);
QUICK_SORT<double>Q2(n);
cout << "1.To sort integer data " << endl;
cout << "2.To sort double data" << endl;
cout << "3.To quit" << endl;
cout << "Enter your choice" << endl;
cin >> ch;
switch(ch)
{ case 1:
Q1.Get_Data();
Q1.Quick(0,n-1);
Q1.Display_Data();
break;
case 2:
Q2.Get_Data();
Q2.Quick(0,n-1);
Q2.Display_Data();
break;
}
getch();
}//end main()
OUTPUT1:
Enter number of data: 4
OUTPUT2:
Enter number of data: 4
RESULT:
Thus the program for implementation of Quick sort using templates was executed.
IMPLEMENTATION OF STACK USING EXCEPTION HANDLING
AIM:
ALGORITHM:
Step 6: Inside the push function check the top of the stack for overflow. If the top is not equal to the size
(n-1) then push the elements onto the stack and increment the top pointer. If the top reaches the maximum
size of n then throw the elements on to the stack overflow.
Step 7: Inside the pop function check the stack underflow condition. If the stack is empty, top is equal to
zero then deletion cannot be performed, throws a stack underflow exception. Otherwise pop the elements
and decrement the pointer.
PROGRAM:
#include<iostream.h>
#include<iomanip.h>
class stack
private:
int *s; int max; int top;
public:
class full{};
class empty{};
stack(int);
void push(int);
};
stack::stack(int m)
s=new int[m];
top = -1;
max=m;
if(top<max-1)
s[++top]=item;
int stack::pop(void)
if(top>=0)
return s[top--];
else
throw empty();
}
void stack::display(void)
if(top>=0)
cout<<"\n \t |"<<setw(4)<<s[i]<<"|\n\t-----";
else
throw empty();
int main()
int item,size;
int ch = 1;
cin>>size;
stack s1(size);
cin>>ch;
do
switch(ch)
case 1:
try
s1.push(item);
catch(stack::full)
break;
case 2:
try
cout<<s1.pop();
catch(stack::empty)
break;
case 3:
try
s1.display();
}
catch(stack::empty)
break;
case 4:
exit(0);
cin>>ch;
}while(ch<5);
return 0;
OUTPUT:
MENU
1.PUSH
2.POP
3.SHOW THE STACK
4.EXIT
Stack Overflow
| 12|
-----
RESULT:
Thus the program to implement the stack using exception handling was executed.
AIM:
To implement a Queue using exception handling using C++.
ALGORITHM:
PROGRAM:
#include<iostream>
#include<iomanip>
class queue
private:
int *q;
int cnt;
public:
queue(int);
void insert(int);
int dele(void);
void display(void);
};
queue::queue(int m)
{
q=new int[m];
rear=0;
front=0;
cnt=0;
max=m;
if(cnt<max)
q[front++]=item;
cnt++;
else
int queue::dele(void)
if(cnt>0)
cnt--;
return q[rear++];
}
else
void queue::display(void)
if(cnt>0)
cout<<"|"<<q[j % max]<<"|";
else
throw EMPTY();
int main()
int ch=1;
cin>>size;
queue q(size);
cin>>ch;
do
switch(ch)
{
case 1:
cin>>item;
try
q.insert(item);
cout<<"\n***Queue Full***\n";
break;
case 2:
try
cout<<"\n***Queue Empty***\n";
break;
case 3:
try
{
q.display();
catch(queue::EMPTY)
cout<<"\n***Queue Empty***\n";
break;
case 4:
exit(0);
cin>>ch;
}while(ch<5);
return 0;
OUTPUT:
MENU
1.INSERT
2.DELETE
3.SHOW QUEUE
4.EXIT
***Queue Full***
|12||23|
***Queue Empty***
***Queue Empty***
RESULT:
Thus the program to implement the queue using exception handling was executed.
MINIMUM SPANNING TREE
AIM:
To find the minimum cost spanning tree in a graph using Prims algorithm.
ALGORITHM:
Step 3: Define a Graph class which represents the collection of Point and Arc objects.
Step 5: Enter the Number of nodes, source node, destination node, weight for the corresponding
edge.
Step6: Repeat step5 until all vertices, edges and weight are defined.
Step 7: The edge does not form a cycle in the graph, for Minimum Spanning Tree.
Step 8: Thus set of edges is connected and form a Minimum Spanning Tree.
Step 9: Display the adjacency matrix for the graph and the minimum total path of all the edges.
PROGRAM:
#include<iostream.h>
#include<conio.h>
#define MAX 50
#define TRUE 1
#define FALSE 0
#define MAXINT 250
class node
{
public:
int no;
node()
{}
node (int a)
{
no = a;
}
};
class arc
{
public:
int adj;
int weight;
arc()
{}
arc(int a)
{
adj = a;
}
};
class graph
{
public:
node nodes[MAX];
arc arcs[MAX][MAX];
graph(int n)
{
for(int i=1;i<=n;i++)
{
nodes[i].no = 0;
for(int j=1;j<=n;j++)
arcs[i][j].adj = FALSE;
}
}
void join(node n1, node n2, int w)
{
arcs[n1.no][n2.no].adj = w;
arcs[n2.no][n1.no].adj = w;
}
void displayadj(int n)
{
cout<<"\n The adjacency matrix....";
cout<<endl;
for(int i = 1; i<=n; i++)
{
for(int j = 1; j<=n;j++)
cout<<"\t"<<arcs[i][j].adj;
cout<<endl;
}
cout<<endl;
}
void shortpath(int n)
{
int lcost[20];
int clost[20],i,j,k,min;
for(i = 2; i<=n;i++)
{
lcost[i]=arcs[1][i].adj;
clost[i]=1;
}
cout<<"\n Minimum cost spanning tree edges are:\n";
for(i=2;i<=n;++i)
{
min=lcost[2];
k=2;
for(j=3;j<=n;++j)
if(lcost[j]<min)
{
min = lcost[j];
k=j;
}
cout<<"\n"<<k<<"<->"<<clost[k];
lcost[k]=MAXINT;
for(j=2;j<=n;++j)
if((arcs[k][j].adj<lcost[j])&&(lcost[j]<MAXINT))
{
lcost[j]=arcs[k][j].adj;
clost[j]=k;
}
}
}
};
int main()
{
int n;
clrscr();
cout<<"\n Enter total number of nodes...";
cin>>n;
graph g(n);
cout<<"\n Assigning number for each node...";
for(int i = 1;i<=n;i++)
g.nodes[i].no=i;
char ch ='y';
int w;
do
{
node a,b;
cout<<"\n Create path b/w the nodes";
cout<<"\n Enter the source node...";
cin>>a.no;
cout<<"\n Enter the destination node...";
cin >>b.no;
cout<<"\n Enter the weight:";
cin>>w;
g.join(a,b,w);
cout<<"\n Want to continue...[y]es or [n]:";
cin>>ch;
}while(ch=='y');
g.displayadj(n);
g.shortpath(n);
cin>>n;
getch();
return 0;
}
OUTPUT:
RESULT:
Thus the program to find the minimum cost spanning tree in a graph using Prims
algorithm was executed.
DYNAMIC POLYMORPHISM AND RTTI
AIM:
To write a C++ program to demonstrate a simple test application for dynamic
polymorphism.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
class Point
{
public:
int x; int y;
Point(){}
Point(int tempX, int tempY)
{
x = tempX;
y = tempY;
}
int GetX()
{
return x;
}
int GetY()
{
return y;
}
friend ostream & operator <<(ostream &tempout, Point &tempPoint)
{
tempout<<"("<<tempPoint.GetX()<<tempPoint.GetY()<<")";
return tempout;
}
};
class Shape
{
Point position;
public:
Shape(){}
virtual void draw()
{
cout<<"shape is drawm";
}
};
class Square:public Shape
{
Point leftbottom;
int length;
public:
Square(){}
Square(Point tleftbottom, int tlength)
{
leftbottom = tleftbottom;
length = tlength;
}
void draw()
{
cout<<"Square is drawn at"<<leftbottom<<"and with length as :"<<length<<"\n";
}
};
class Rectangles : public Shape
{
Point leftbottom, lefttop, rightbottom, righttop;
public:
Rectangles(){}
Rectangles(Point tleftbottom, Point tlefttop, Point trightbottom, Point trighttop)
{
leftbottom = tleftbottom;
lefttop = tlefttop;
rightbottom = trightbottom;
righttop = trighttop;
}
void draw()
{
cout<<"Rectangle is drawn at ("<<leftbottom<<",
"<<rightbottom<<")"<<"and"<<"("<<lefttop<<","<<righttop<<")\n";
}
};
class Triangle : public Shape
{
Point avertex, bvertex, cvertex;
public:
Triangle(){}
Triangle(Point tavertex, Point tbvertex, Point tcvertex)
{
avertex = tavertex;
bvertex = tbvertex;
cvertex = tcvertex;
}
void draw()
{
cout<<"Triangle is drawn at"<<avertex<<" "<<bvertex<<" "<<cvertex<<"\n";
}
};
class Circle: public Shape
{
Point center; int radius;
public:
Circle(){}
Circle(Point tcenter, int tradius)
{
center = tcenter;
radius = tradius;
}
void draw()
{
cout<<"Circle is drawn at"<<" " <<center<<" " <<"and the radius is: "<<radius<<"\n";
}
};
class Ellipses: public Shape
{
Point center;
int radius; int angle;
public:
Ellipses(){}
Ellipses(Point tcenter, int tradius, int tangle)
{
center = tcenter;
radius = tradius;
angle = tangle;
}
void draw()
{
cout<<"Ellipse is drawn at"<<center<<"and the radius is"<<radius<<"with an
angle"<<angle<<"\n";
}
};
void main()
{
clrscr();
cout<<"\n";
Point p1(10,20);
Point p2(3,2);
Square sq(p1,5);
sq.draw();
Rectangles rect(p1,p2,p1,p2);
rect.draw();
Circle c(p1,50);
c.draw();
Ellipses e(p2,34,23);
e.draw();
Triangle t(p1,p2,p1);
t.draw();
Shape *s;
s=&sq;
s->draw();
s=▭
s->draw();
s=&t;
s->draw();
getch();
}
OUTPUT:
RESULT:
Thus the C++ program to demonstrate a simple test application for dynamic
polymorphism was executed.
OPERATIONS ON COMPLEX NUMBERS USING FILES AS STORAGE
AIM:
To write a C++ program to perform addition of complex numbers using files.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<time.h>
class complex
{
public:
int real;
int imag;
complex(int r, int i)
{
real = r;
imag = i;
}
complex()
{
real = imag = 0;
}
void display(void);
};
void complex::display(void)
{
cout<<real<<((imag<0)?"-i":"+i")<<imag<<"\n";
}
void main()
{
clrscr();
ofstream ocom("complex1.txt");
float real,imag;
time_t ti;
srand((unsigned) time(&ti));
real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"+";
real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"\n";
ocom.close();
ifstream icom("complex1.txt");
char no,t,ch,op;
icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag;
icom>>no;
icom>>op;
complex a(real,imag);
icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag;
icom>>no;
icom>>op;
complex b(real,imag);
complex c;
switch(op)
{
case '+':
c.real = a.real+b.real;
c.imag = a.imag+b.imag;
break;
case '-':
c.real = a.real-b.real;
c.imag = a.imag-b.imag;
break;
case '*':
c.real = (a.real*b.real)-(a.imag*b.imag);
c.imag = (a.real*b.imag)+(a.imag*b.real);
break;
case '/':
float qt;
qt = b.real*b.real+b.imag*b.imag;
c.real = (a.real*b.real+a.imag*b.imag)/qt;
c.imag = (a.imag*b.real-a.real*b.imag)/qt;
break;
default:
cout<<"\n Invalid";
}
cout<<"\n complex 1:";
a.display();
cout<<"\n complex 2:";
b.display();
cout<<"\n Resultant complex:";
c.display();
ofstream out("result.txt");
out<<"("<<c.real<<((c.imag<0)?"-i":"+i")<<c.imag<<")";
out.close();
}
OUTPUT:
complex1.txt:
(0+i72)+(39+i71)
result.txt
(39+i143)
RESULT:
Thus the program for addition of complex numbers using files was executed.