You are on page 1of 62

VELAMMAL INSTITUTE OF TECHNOLOGY

Velammal Gardens, Panchetti - 601204

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

III SEMESTER

CS2209 - OBJECT ORIENTED PROGRAMMING LAB MANUAL

[As per Anna University, Chennai – Regulations 2008]

[ COMMON TO CSE & IT]

Prepared by:
E. Manosri
N.K Rejin Paul
S. Selvakanmani
SYLLABUS

CS 2209 OBJECT ORIENTED PROGRAMMING LAB 0 0 3 2


(Common to CSE & IT)

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

(Common to Information Technology & Computer Science Engineering)

List of Equipments and software for a batch of 30 students

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

1. Implementation of Static Members


2. Calculation of Simple Interest using Default Arguments
3. Matrix Multiplication using friend functions
4. Implementation of Complex Numbers using Operator Overloading
5. Implementation of Complex Numbers using Operator Overloading and Type
Conversion
6. Matrix Class with Constructor, Destructor, Copy constructor and Assignment
operator overloading
7. Overloading New and Delete Operator
8. Creating Linked List using Templates
9. Implementation of Bubble sort using Templates
10. Implementation of Insertion sort using Templates
11. Implementation of Merge sort using Templates
12. Implementation of Quick sort using Templates
13. Implementation of Stack using Exception Handling
14. Implementation of Queue using Exception Handling
15. Minimum Spanning Tree
16. Dynamic Polymorphism & RTTI
17. Operations on complex numbers using files as Storage
IMPLEMENTATION OF STATIC MEMBERS

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

Static count value:2


Static cnt value:102

Object Number:2

Static count value:3


Static cnt value:103

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:

Step 1: Start the program.


Step 2: Create a class Matrix with two matrix array as data member and a function as their
member function.
Step 3: Declare a function multiply as a friend function for the class matrix.get the value of the
given two matrix using a member function.
Step 4: Calculate the matrix multiplication using friend function. The friend function is called in
the main function without the help of the object and object as its arguments.
Step 5: Display the resultant matrix.
Step 6: Stop the program.

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 the dimension (n*m) of the first matrix: 2 2

Enter 4 element:1 2 3 4

The value of the first matrix:


1 2
3 4
Enter the dimension (n*m) for the second matrix: 2 2

Enter 4 element:4 5 6 7

The value of the second matrix:


4 5
6 7
Resultant Matrix:
16 19
36 43
Do you want to multiply one more matrix: n

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:

Step 1: Start the process


Step 2: Create a class complex with real and imaginary data members.
Step 3: A parameterized constructor is used here for initializing real and
imaginary data members during object creation.
Step 4: The operators such as +, -,* and / are overloaded.
Step 5: In the main function the complex number operations are done with the
help of overloaded operators.
Step 6: The result is displayed.
Step 7: Stop the process.
PROGRAM:

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

Enter complex number 1:


Real Part:2
Imag Part:4

Enter complex number 2:


Real Part:3
Imag Part:5

Enter complex numbers are:


Complex 1: 2+4i
Complex 2: 3+5i
Result of addition is:5+9i
Result of subtraction is:-1-1i
Result of multiplication is:-14+22i
Result of division is:0.764706+0.058824i
Integer->complex:4+9i
Double->complex:3.23004+4.666305i
Converted to double7.896345

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:

Enter rows and columns of the matrix:


3
2

Enter the matrix elements one by one:


2
3
1
4
5
7

Entered matrix is:


2 3
1 4
5 7

Copy constructor invoked

Result of the copy constructor is:


2 3
1 4
5 7

Assignment Operator Overloading

Result of assignment operator overloading:


2 3
1 4
5 7

Output 2:

Enter rows and columns of the matrix:


33

Enter the matrix elements one by one:


12 23 34 45 56 67 78 89 90

Entered matrix is:


12 23 34
45 56 67
78 89 90

Copy constructor invoked

Result of the copy constructor is:


12 23 34
45 56 67
78 89 90

Assignment Operator Overloading

Result of assignment operator overloading:


12 23 34
45 56 67
78 89 90

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:

Step 1: Start the program.


Step 2: Create a class ‘op’;
Step 3: Declare the overloaded member functions new & delete.
Step 4: Invoke the base class constructor and passing arguments for the new function.
Step 5: The inbuilt identifiers __FILE__ and __LINE__ will get the current file which under
processing and the line which currently executing the __LINE__ will be passed.
Step 6: Using malloc the memory will be allocated for the current processing file.
Step 7: Invoke the overloaded operated function delete and pass the pointer variable free the
memory which is already allocated.
Step 8: Stop the program.

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:

New called the file:NEWDEL1.CPP


line:24
size:1
p:0x8fba0df6
Delete called p:0x8fba0df6

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:

Step1: Start the process.


Step2: Declare template class T and include the necessary header files.
Step3: Create a class for linked list node.
Step4: Declare the necessary member function, insert, display ,quit.
Step5: Initialize the head node to NULL.
Step6: Adding values to the tail or end of the list.
a. check the head node for NULL. If it is null then new node will be assigned to head
node .And the given input is given to the head node.
b. If it is not null, a new node will be created, while the new link node is not equal to null then
new value will be appeared to the new node.
Step7: Display the list.
a. print the nodes if the node is not null.
Step 9: Inside main, call and invoke the function and pass the different data types.
Step 10:Display the results.
Step 11:Stop the process.

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:

Linked list using Templates


1. Insert the element
2. Display the elements:
3. Quit
Enter your choice:1

enter data:12

Linked list using Templates


1. Insert the element
2. Display the elements:
3. Quit
Enter your choice:1

enter data:23

Linked list using Templates


1. Insert the element
2. Display the elements:
3. Quit
Enter your choice:1

enter data:10

Linked list using Templates


1. Insert the element
2. Display the elements:
3. Quit
Enter your choice:2
12 23 10

Linked list using Templates


1. Insert the element
2. Display the elements:
3. Quit
Enter your choice:3

RESULT:
Thus the program for linked list using template was executed using C++ .
IMPLEMENTATION OF BUBBLE SORT

AIM:

To write a program to implement bubble sort using templates

ALGORITHM:

Step 1:Start the process.


Step 2:Get the number of elements to be sorted.
Step 3:Get the elements from the user.
Step 4:For iteration=1 to n,
a. Assign the first element to the variable “i” and the second element to the variable “j”.
b.Compare the two elements.
c.If the first element is greater than the second element then swap the two values. Else
break.
Step 5:Continue the steps 4 until there is no interchange in the current iteration.
Step 6;No interchange indicates the elements are sorted.
Step 7: Stop the process.

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:

----Bubble Sort on Integer Values----


Enter the size of array: 5

Enter the array elements: 3 6 1 2 9

The sorted array is: 1 2 3 6 9

----Bubble Sort on Float values----

Enter the size of array: 5

Enter the array elements: 1.2 5.7 3.6 2.0 4.6

The sorted array is: 1.2 2 3.6 4.6 5.7

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:

Step 1: Start the process.


Step 2: Get the number of elements to be inserted
Step 3: Store the elements in an array
Step 4: Fix the index position to the first element.
Step 5: Write a routine for comparing the least element in the array
Step 6: Compare the first element with the next element. If the second element is lesser than the
first element, then the first element will be swapped. Likewise, all the elements will be compared
in many passes.
Step 7: Once the element have be sorted then the sorting routine will get stop.
Step 8: Stop the process.

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:

Insertion Sort on Integer Values


Enter the size of array: 5
Enter the array elements:23
67
12
78
34

The sorted array is: 12 23 34 67 78

Insertion Sort on Float Values


Enter the size of array: 3
Enter the array elements:13.3
29.0
12.7

The sorted array is: 12.7 13.3 29

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:

Merge Sort Using Templates


~~~~~~~~~~~~~~~~~~~~~
Enter the Array Size:5
----Integer values----
Enter the Array Elements:12 45 23 10 78

The Sorted Array is 10 12 23 45 78

----Float values----
Enter the Array Elements:12.4 34.6 67.8 13.9 33.2

The Sorted Array is 12.4 13.9 33.2 34.59 67.8

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

1.To sort integer data


2.To sort double data
3.To quit
Enter your choice
2
Enter the elements to be inserted
1.7 2.6 1.9 4.7
The sorted list is:1.7 1.9 2.6 4.7

OUTPUT2:
Enter number of data: 4

1.To sort integer data


2.To sort double data
3.To quit
Enter your choice
1
Enter the elements to be inserted
12 56 89 23
The sorted list is:12 23 56 89

RESULT:
Thus the program for implementation of Quick sort using templates was executed.
IMPLEMENTATION OF STACK USING EXCEPTION HANDLING

AIM:

To implement a Stack using exception handling using C++.

ALGORITHM:

Step 1: Start the process.

Step 2: Create a Class Stack.

Step 3: Initialize the top pointer of the stack.

Step 4: Create class full and empty.

Step 5: Create the members push, pop and display.

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.

Step 8: Display the stack elements.

Step 9: Stop the process.

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

int pop(void);void display(void);

};

stack::stack(int m)

s=new int[m];

top = -1;

max=m;

void stack::push(int item)

if(top<max-1)

s[++top]=item;

else throw full();

int stack::pop(void)

if(top>=0)

return s[top--];

else

throw empty();
}

void stack::display(void)

if(top>=0)

for(int i = top; i>=0;i--)

cout<<"\n \t |"<<setw(4)<<s[i]<<"|\n\t-----";

else

throw empty();

int main()

int item,size;

int ch = 1;

cout<<"\n Enter the size of the Stack:";

cin>>size;

stack s1(size);

cout<<"\n Stack with exception handling";

cout<<"\n \n MENU \n 1.PUSH \n 2.POP \n3.SHOW THE STACK \n4.EXIT";

cout<<"\n Enter your choice:";

cin>>ch;

do

switch(ch)

case 1:

cout<<"\n Enter the item to push:";


cin>>item;

try

s1.push(item);

catch(stack::full)

cout<<"\n Stack Overflow";

break;

case 2:

try

cout<<"The Popped element is:";

cout<<s1.pop();

catch(stack::empty)

cout<<"\n Stack is empty";

break;

case 3:

cout<<"The stack is....";

try

s1.display();
}

catch(stack::empty)

cout<<"\n Stack empty";

break;

case 4:

exit(0);

cout<<"\n Enter your choice:\t";

cin>>ch;

}while(ch<5);

return 0;

OUTPUT:

[ex@localhost ~]$ vi stack.cpp

[ex@localhost ~]$ g++ stack.cpp

[ex@localhost ~]$ ./a.out

Enter the size of the Stack:2

Stack with exception handling

MENU

1.PUSH

2.POP
3.SHOW THE STACK

4.EXIT

Enter your choice:1

Enter the item to push:12

Enter your choice: 1

Enter the item to push:34

Enter your choice: 1

Enter the item to push:23

Stack Overflow

Enter your choice: 2

The Popped element is:34

Enter your choice: 3

The stack is....

| 12|

-----

Enter your choice: 4

RESULT:

Thus the program to implement the stack using exception handling was executed.

IMPLEMENTATION OF QUEUE USING EXCEPTION HANDLING

AIM:
To implement a Queue using exception handling using C++.

ALGORITHM:

Step 1: Start the process.


Step 2: Create a class queue.
Step 3: Initialize the front and rear pointers of the queue.
Step 4: Create the members full, empty, insert, dele and display.
Step 5: Inside the insert function check if rear = max. If rear is not equal to max then add the element to
the queue. If rear reaches the max then throw the message “Queue Overflow”.
Step 6: Inside the dele function, check if front = rear. If front is not equal to rear then deletion is possible.
If front is equal to the rear, throw the message “Queue Underflow”.
Step 7: Display the queue.
Step 8: Stop the process.

PROGRAM:

#include<iostream>

#include<iomanip>

using namespace std;

class queue

private:

int *q;

int max, front, rear;

int cnt;

public:

class FULL{}; //for exception handling

class EMPTY{}; //for exception handling

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;

void queue::insert(int item)

if(cnt<max)

front = front % max;

q[front++]=item;

cnt++;

else

throw FULL(); //FULL object is thrown

int queue::dele(void)

if(cnt>0)

cnt--;

rear = rear % max;

return q[rear++];

}
else

throw EMPTY(); //EMPTY object is thrown

void queue::display(void)

if(cnt>0)

for(int i=0,j=front; i<cnt; i++,j++)

cout<<"|"<<q[j % max]<<"|";

else

throw EMPTY();

int main()

int item, size;

int ch=1;

cout<<"\nEnter the size of the queue…";

cin>>size;

queue q(size);

cout<<"\nQueue Operations using Exception Handling";

cout<<"\n\n\tMENU\n1.INSERT\n2.DELETE\n 3.SHOW QUEUE\n4.EXIT";

cout<<"\nEnter your choice…";

cin>>ch;

do

switch(ch)

{
case 1:

cout<<"\nEnter the item to insert in to the queue…";

cin>>item;

try

q.insert(item);

catch(queue::FULL) //FULL object is caught

cout<<"\n***Queue Full***\n";

break;

case 2:

try

cout<<"\nRemoved Item from the Qis…"<<q.dele();

catch(queue::EMPTY) //EMPTY object is caught

cout<<"\n***Queue Empty***\n";

break;

case 3:

cout<<"\nThe Queue is…\n";

try

{
q.display();

catch(queue::EMPTY)

cout<<"\n***Queue Empty***\n";

break;

case 4:

exit(0);

cout<<"\nEnter your choice…";

cin>>ch;

}while(ch<5);

return 0;

OUTPUT:

[ex@localhost ~]$ g++ q2.cpp

[ex@localhost ~]$ ./a.out

Enter the size of the queue…2

Queue Operations using Exception Handling

MENU

1.INSERT

2.DELETE
3.SHOW QUEUE

4.EXIT

Enter your choice…1

Enter the item to insert in to the queue…12

Enter your choice…1

Enter the item to insert in to the queue…23

Enter your choice…1

Enter the item to insert in to the queue…34

***Queue Full***

Enter your choice…3

The Queue is…

|12||23|

Enter your choice…2

Removed Item from the Qis…12

Enter your choice…2

Removed Item from the Qis…23

Enter your choice…2

***Queue Empty***

Enter your choice…3

The Queue is…

***Queue Empty***

Enter your choice…4

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 1 : Start the process.

Step 2: Create two classes as POINT and ARC.

Step 3: Define a Graph class which represents the collection of Point and Arc objects.

Step 4: Write a method to find a minimum cost spanning tree in a graph.

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.

Step 10: Stop the process.

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:

Enter total number of nodes...4


Assigning number for each node...
Create path b/w the nodes
Enter the source node...1
Enter the destination node...2
Enter the weight:1
Want to continue...[y]es or [n]:y
Create path b/w the nodes
Enter the source node...1
Enter the destination node...4
Enter the weight:2
Want to continue...[y]es or [n]:y
Create path b/w the nodes
Enter the source node...1
Enter the destination node...3
Enter the weight:2
Want to continue...[y]es or [n]:y
Create path b/w the nodes
Enter the source node...2
Enter the destination node...4
Enter the weight:4
Want to continue...[y]es or [n]:y
Create path b/w the nodes
Enter the source node...2
Enter the destination node...3
Enter the weight:5
Want to continue...[y]es or [n]:y
Create path b/w the nodes
Enter the source node...3
Enter the destination node...4
Enter the weight:3
Want to continue...[y]es or [n]:n
The adjacency matrix....
0 1 2 2
1 0 5 4
2 5 0 3
2 4 3 0
Minimum cost spanning tree edges are:
2<->1
3<->1
4<->1

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:

Step 1: Start the program.


Step 2: Create a class called Point in order to locate the position of the shapes.
Step 3: Create a class called Shape and use virtual function to draw the corresponding shape.
Step 4: Create classes for shapes like Square, Rectangle, Triangle, Circle, Ellipses.
Step 5: Call all the shapes using objects, in main function.
Step 6: Shapes will be drawn with the given values.
Step 7: Shapes can also be drawn by using their address and display their location.
Step 8: Stop the program.

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=&rect;
s->draw();
s=&t;
s->draw();
getch();
}

OUTPUT:

Square is drawn at(1020)and with length as :5


Rectangle is drawn at ((1020), (1020))and((32),(32))
Circle is drawn at (1020) and the radius is: 50
Ellipse is drawn at(32)and the radius is34with an angle23
Triangle is drawn at(1020) (32) (1020)
Square is drawn at(1020)and with length as :5
Rectangle is drawn at ((1020), (1020))and((32),(32))
Triangle is drawn at(1020) (32) (1020)

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:

Step 1: Start the program.


Step 2: Create a class called COMPLEX and create its members: real and imaginary.
Step 3: Generate the random numbers by using rand() function.
Step 4: Write the randomly generated numbers in a file called “complex1.txt”.
Step 5: Add the two complex numbers.
Step 6: Store the Resultant complex number in another file called “result.txt”
Step 7: Display the resultant value.
Step 8: Stop the program.

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.

You might also like