Ex. No 1 Implementation of Static Data member, Default
Argument and Friend Function
Aim
To Write a C++ program for Students mark analysis using Static Data
member, Default Argument and Friend Function.
Algorithm
Step 1: Start the Process.
Step 2: Get the Students detail and calculate the Result analysis.
Step 3: Default value is assigned for pass in a function and the function is
assigned with default value when value for pass is not given in checking
for pass status.
Step 4: Declare the integer count as Static member each time when the student is
pass it will be incremented and finally specify pass count.
Step 5: The friend function display is used to access the private variables from
two classes and acting as the bridge between two classes.
Step 6: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
int cp(int,int,int,int=50);
void printline(char ch='*',int range= 70);
class per;
class acc
{i
nt rno,tot;
static int count;
int m1,m2,m3;
char name[20],grade;
float avg;
public:
void getdata()
{
cout<<"Enter id:";
cin>>rno;
cout<<"Enter name:";
cin>>name;
cout<<"Enter m1";
cin>>m1;
cout<<"Enter m2";
cin>>m2;
cout<<"Enter m3";
cin>>m3;
}friend void display(acc,per);
void cal()
{
tot=0;
if(cp(m1,m2,m3))
{
cout<<"Result=pass"<<endl;
tot=m1+m2+m3;
avg=tot/3;
count=count+1;
if(avg>=90)
grade='O';
if(avg>=70&&avg<90)
grade='A';
if(avg>=50&&avg<70)
grade='B';
}
else
{
cout<<"Result=Fail"<<endl;
}}
static void showcount(void)
{
cout<<endl;
cout<<"count:"<<count;}};
int acc::count;
class per
{
char add[25];
long tel;
public:
void getdata1()
{
cout<<"Enter address";
cin>>add;
cout<<"Enter phoneno:";
cin>>tel;
}
friend void display(acc a,per p)
{
cout<<endl;
cout<<"Name:"<<a.name<<endl;
cout<<"ID:"<<a.rno<<endl;
cout<<"Address:"<<p.add<<endl;
cout<<"Phone no.:"<<p.tel<<endl;
cout<<"M1:"<<a.m1<<endl;
cout<<"M2:"<<a.m2<<endl;
cout<<"M3:"<<a.m3<<endl;
if(cp(a.m1,a.m2,a.m3))
{
cout<<"Total:"<<a.tot<<endl;
cout<<"Average:"<<a.avg<<endl;
cout<<"Grade:"<<a.grade<<endl;
}}};
int cp(int m1,int m2,int m3,int pass1)
{
if(m1>=pass1&&m2>=pass1&&m3>=pass1)
return(1);
else
return(0);
}
void main()
{
int i,n;
clrscr();
per p1[20];
acc a1[20];
cout<<"Enter no of students:";
cin>>n;
for(i=0;i<n;i++)
{
a1[i].getdata();
p1[i].getdata1();
a1[i].cal();
}
for(i=0;i<n;i++)
{
printline('-');
display(a1[i],p1[i]);
printline();
}
acc::showcount();
getch();
}
void printline(char ch,int range)
{
int i;
cout<<endl;
for(i=0;i<range;i++)
cout<<ch;}
Output
Enter no of students:2
Enter id:2
Enter name:rahul
Enter m1:78
Enter m2:90
Enter m3:67
Enter address:coimbatore
Enter phoneno:230000
Result=pass
Enter id:5
Enter name:aravind
Enter m1:56
Enter m2:45
Enter m3:78
Enter address:madurai
Enter phoneno:456789
Result=Fail
-----------------------------------------------------------
Name:rahul
ID:2
Address:coimbatore
Phone no.:230000
M1:78
M2:90
M3:67
Total:235
Average:78
Grade:A
***********************************************************
-----------------------------------------------------------
Name:aravind
ID:5
Address:madurai
Phone no.:456789
M1:56
4
Yolearn
http://www.yolearn.net
the network of education
M2:45
M3:78
***********************************************************
count:1
Result
Thus the program to perform Students mark analysis using Static Data
member, Default Argument and Friend Function was implemented.
Ex. No 2 Implementation of complex number class with operator
overloading and type conversions
Aim
To write a C++ program to implement complex number class with
operator overloading and type conversions such as integer to complex, double to
complex, complex to double.
Algorithm
Step 1: Start the program.
Step 2: Create a class with necessary data members and member functions.
Step 3: Create a constructor to initialize the variables.
Step 4: Perform addition of two numbers overloading the necessary operators.
Step 5: Create an object for the Complex class and call the required functions to
perform the action.
Step 6: Perform the type conversion from double to complex, integer to complex
and complex to double.
Step 7: Display the result.
Step 8: Stop the program.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
class complex
{
float real,img,temp;
public:
complex()
{
real=img=0;
}
complex(int a)
{
real=a;
img=0;
}
complex(double a1)
{
real=a1;
img=0.0;
}
void outdata()
{i
f(img>=0.0)
{
cout<<real<<"+"<<img<<"i";
}
else
{
cout<<real<<img<<"i";
}}
complex operator+(complex c)
{
complex temp;
temp.real=real+c.real;
temp.img=img+c.img;
return(temp);
}
complex operator-(complex c)
{
complex temp1;
temp1.real=real-c.real;
temp1.img=img-c.img;
return(temp1);
}
complex operator*(complex c)
{
complex temp2;
temp2.real=real*c.real-img*c.img;
temp2.img=real*c.img+img*c.real;
return(temp2);
}
complex operator/(complex c)
{
complex temp3;
temp3.real=(((real*c.real)+(img*c.img))/((c.real*c.real)+(c.img*c.img)));
temp3.img=(((img*c.real)-(real*c.img))/((c.real*c.real)+(c.img*c.img)));
return(temp3);
}
operator double()
{
double magnitude;
magnitude=sqrt(pow(real,2)+pow(img,2));
return magnitude;
}}
;
void main()
{
clrscr();
complex c1,c2,c3,c4,c5,c6;
int real;
double real1;
cout<<"Enter the real number";
cin>>real;
c1=real;
cout<<"Integer to complex conversion"<<endl;
cout<<"Enter the real number";
cin>>real1;
c2=real1;
cout<<"Double to complex conversion"<<endl;
c3=c1+c2;
c4=c1-c2;
c5=c1*c2;
c6=c1/c2;
cout<<"\n\n";
cout<<"addtion result is:";
c3.outdata();
cout<<"\n\n";
cout<<"subraction result is:";
c4.outdata();
cout<<"\n\n";
cout<<"multiplication result is:";
c5.outdata();
cout<<"\n\n";
cout<<"division result is:";
c6.outdata();
cout<<"Conversion from complex to double"<<endl;
double mag=c3;
cout<<"Magnitude of a complex number"<<mag;
getch();
}
Output
Enter the real number:2
Integer to complex conversion
Enter the real number:2.0
Double to complex conversion
addtion result is:4+0i
subraction result is:0+0i
multiplication result is:4+0i
division result is:1+0i
Conversion from complex to double
Magnitude of a complex number:4
Result
Thus the program to implement complex number class with operator
overloading and type conversions such as integer to complex, double to complex,
complex to double is implemented.
Ex. No 3 Implement the Matrix Class using Constructor, Destructor,Copy
Constructor, Overloading assignment operator
Aim
To Write a C++ program to Implement Matrix Class using Constructor,
Destructor, Copy Constructor, Overloading assignment operator
Algorithm
Step 1: Start the Process.
Step 2: Create the class name as MATRIX.
Step 3: Declare the data member and member function.
Step 4: Declare constructor, destructor and copy constructor
Step 5: Display the result.
Step 6: Stop the process.
Program
#include<iostream.h>
#include<conio.h>
class matrix
{
private:
int row;
int col;
int **p;
public:
matrix() //Constructor
{
row=col=0;
p=NULL;
}
matrix(int r,int c);
~matrix(); //Destructor
void read();
void show();
void add(matrix &a,matrix &b);
void sub(matrix &a,matrix &b);
void operator =(matrix &m1)
{
row=m1.row;
col=m1.col;
p=new int *[m1.row]; //dynamic allocation
for(int i=0;i<m1.row;i++)
{
p[i]=new int[m1.col];//dynamic allocation
}}
matrix(matrix &m2)//copy construtor
{
row=m2.row;
col=m2.col;
p=new int *[m2.row]; //dynamic allocation
for(int i=0;i<m2.row;i++)
{
p[i]=new int[m2.col];//dynamic allocation
}
for(i=0;i<m2.row;i++)
for(int j=0;j<m2.col;j++)
{
p[i][j]=m2.p[i][j];
}}}
; matrix::matrix(int r,int c)
{
row=r;
col=c;
p=new int *[row]; //dynamic allocation
for(int i=0;i<row;i++)
p[i]=new int[col];//dynamic allocation
}
matrix::~matrix()
{
for(int i=0;i<row;i++)
delete p[i];
delete p;
}
void matrix::add(matrix &a,matrix &b)
{i
nt i,j;
row=a.row;
col=b.col;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[i][j]=a.p[i][j]+b.p[i][j];
}
void matrix::sub(matrix &a,matrix &b)
{i
nt i,j;
row=a.row;
col=b.col;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[i][j]=a.p[i][j]-b.p[i][j];
}
void matrix::read()
{int i,j;
10
Yolearn
http://www.yolearn.net
the network of education
for( i=0;i<row;i++)
for( j=0;j<col;j++)
{
cout<<"Matrix["<<i<<","<<j<<"]=";
cin>>p[i][j];
}}
void matrix::show()
{
int i,j;
for(i=0;i<row;i++)
{
cout<<endl;
for( j=0;j<col;j++)
{
cout<<p[i][j]<<"\t";
}
}
}
void main()
{i
nt m,n,p,g,q;
clrscr();
cout<<"Enter the A matrix"<<endl;
cout<<"How many rows?";
cin>>m;
cout<<"How many col?";
cin>>n;
matrix a(m,n);
a.read();
matrix b;
b=a;//overloading assignment operator
cout<<”Overloading assignment operator Invoked”<<endl;
cout<<”Enter the B matrix”;
b.read();
cout<<"Matrix A is ..";
a.show();
cout<<endl<<"Matrix B is..";
b.show();
matrix c(m,n);
c.add(a,b);
cout<<endl<<"c=a+b..";
c.show();
matrix d(m,n);
d.sub(a,b);
cout<<endl<<"d=a-b..";
d.show();
cout<<"\nCopy constructor invoked"<<endl;
matrix e(d);//Copy Constructor
e.show();
getch();
}
Output
Enter the A matrix
How many rows?2
How many col?2
Matrix[0,0]=2
Matrix[0,1]=2
Matrix[1,0]=2
Matrix[1,1]=2
Overloading assignment operator Invoked
Enter the B matrix
Matrix[0,0]=1
Matrix[0,1]=1
Matrix[1,0]=1
Matrix[1,1]=1
Matrix A is ..
2 2
2 2
Matrix B is..
1 1
1 1
c=a+b..
3 3
3 3
d=a-b..
1 1
1 1
Copy constructor invoked
1 1
1 1
Result
Thus the C++ program to Implement Matrix Class using Constructor,
Destructor, Copy Constructor, Overloading assignment operator is implemented.
Ex. No 4 Overloading of new and delete operators for addition of
vector elements
Aim
To write a C++ program to Overload the new and delete operators for
addition of vector elements to provide custom dynamic allocation of memory.
Algorithm
Step 1: Start the program.
Step 2: Declare the necessary function prototype.
Step 3: Define void *operator new (), void operator delete () functions to allocate
storage and to delete the memory with the help of malloc and free
functions respectively.
Step 4: read () and sum () functions to get and calculate the vector addition.
Step 5: Stop the program.
Program
#include<iostream.h>
const int asize=10;
class vector
{i
nt *a;
public:
void * operator new(size_t )
{
vector *v;
v=::new vector;
v->a=new int[asize];
return v;
}
void operator delete(void *vec)
{
vector *v;
v=(vector *)vec;
delete(int*) v->a;
::delete vec;
}
void read()
{f
or(int i=0;i<asize;i++)
{
cin>>a[i];
}}i
nt sum()
{i
nt sum=0;
for(int i=0;i<asize;i++)
{
sum+=a[i];
}
return sum;
}}
;
void main()
{
vector *v=new vector;
cout<<”Enter the vector elements”;
v->read();
cout<<”the sum of vector elements”<<v->sum();
delete v;
}
Output
Enter the vector elements 10
10
10
10
10
10
10
10
10
10
The sum of vector elements: 100
Result
Thus the program to Overload the new and delete operators for
addition of vector elements to provide custom dynamic allocation of memory is
implemented.
Ex. No 5 Implementation of Template for Linked List Class
with necessary methods
Aim
To write a C++ program to implement the template of linked list class.
Algorithm
Step1: Start the program.
Step2: Create an emp and linked list class, declare necessary data members.
Also create a node structure with template based variables and link field.
Include necessary constructor, member function and destructor.
Step3: Define constructor linklist() to initialize the variable. Define
member function such as., void append(T),void addatbeg(T),void
addafter(int,T),void del(int),void display(),int count() to perform various
operation in the linked list.
Step4: Use destructor ~linklist() to destroy the allocated memory.
Step5: Create required objects to call the necessary function to perform all the
operations.
Step6: Display the result.
Step7: Stop the program.
Program
#include<iostream.h>
#include<string.h>
#include<iostream.h>
class emp
{
private:
char name[20];
int age;
float sal;
public:
emp(char *n="",int a=0,float s=0.0)
{
strcpy(name,n);
age=a;
sal=s;
}f
riend ostream&operator<<(ostream &s,emp &e);
};
ostream&operator<<(ostream &s,emp &e)
{
cout<<e.name<<'\t'<<e.age<<'\t'<<e.sal;
return s;
}t
emplate<class T>
class linklist
{
private:
struct node
{
T data;
node *link;
}*p;
public:
linklist();
void append(T);
void addatbeg(T);
void addafter(int,T);
void del(int);
void display();
int count();
~linklist();
};
template<class T>
linklist<T>::linklist()
{
p=NULL;
}
//Adds a new node at the end of the linked list
template<class T>
void linklist<T>::append(T num)
{
node *q,*t;
//if the list is empty
if(p==NULL)
{
//create first node
p=new node;
p->data=num;
p->link=NULL;
}
else
{
//go to the last node
q=p;
while(q->link!=NULL)
q=q->link;
//add node at the end
t=new node;
t->data=num;
t->link=NULL;
q->link=t;
}}
//adds a new node at the beginning of the linked list
template<class T>
void linklist<T>::addatbeg(T num)
{
node *q;
//add new node
q=new node;
q->data=num;
q->link=p;
p=q;
}
//adds a new node after the specified number of nodes
template<class T>
void linklist<T>::addafter(int c,T num)
{
node *q,*t;
int i;
//skip to the desired portion
17
Yolearn
http://www.yolearn.net
the network of education
for(i=0;q=p,i<=c;i++)
{
q=q->link;
//if end of linked list is encountered
if(q==NULL)
{
cout<<endl<<"There are less than"<<c<<"elements.";
return;
}}
//insert new node
t=new node;
t->data=num;
t->link=q->link;
q->link=t;
}
//deletes the specified node from the linked list
template<class T>
void linklist<T>::del(int n)
{
node *q,*r;
int i=1;
q=p;
//if node to be deleted is first node
if(n==1)
{
p=q->link;
delete q;
return;
}
//traverse list till the last but one node is reached
r=q;
while(q!=NULL)
{i
f(i==n)
{
r->link=q->link;
//free the memory occupied by the node
delete q;
return;
}
r=q;
q=q->link;
i++;
}
cout<<endl<<"Element"<<n<<"not found";
}//displays the contents of the linked list
template<class T>
void linklist<T>::display()
{
node *q;
cout<<endl;
//traverse the entire linked list
for(q=p;q!=NULL;q=q->link)
cout<<q->data<<endl;
}//counts number of nodes present in the linked list
template<class T>
int linklist<T>::count()
{
node *q;
int c=0;
//traverse the entire linked list
for(q=p;q!=NULL;q=q->link)
c++;
return(c);
}//destroys the linked list object
template<class T>
linklist<T>::~linklist()
{
node *t;
while(p!=NULL)
{t
=p;
p=p->link;
delete t;
}}
void main()
{l
inklist<int>l1;
cout<<endl<<"No.of elements in Linked list="<<l1.count();
l1.append(11);
l1.append(22);
l1.append(33);
l1.append(44);
l1.append(55);
l1.append(66);
l1.addatbeg(100);
l1.addatbeg(200);
l1.addafter(3,333);
l1.addafter(6,444);
l1.display();
cout<<endl<<"No.of elements in linked list="<<l1.count();
l1.del(200);
l1.del(66);
l1.del(0);
l1.del(333);
l1.display();
cout<<endl<<"No.of elements in linked list="<<l1.count();
linklist<emp>l2 ;
cout<<endl<<"No.OF elements in linked list="<<l2.count();
emp e1("Sanjay",23,1100.00);
emp e2("Sachin",33,3500.00);
emp e3("Sourav",24,2400.00);
emp e4("Sanket",25,2500.00);
emp e5("Sandeep",26,2600.00);
l2.append(e1);
l2.append(e2);
l2.append(e3);
l2.append(e4);
l2.append(e5);
l2.display();
l2.del(3);
l2.display();
cout<<endl<<"No.of elements in linked list="<<l2.count();
l2.addatbeg(e5);
l2.display();
l2.addafter(3,e1);
l2.display();
cout<<endl<<"No.of elements in linked list="<<l2.count();
}
Output
No.of elements in linked list =0
200
444
100
333
11
22
33
44
55
66
No.of elements in linked list=10
Element200not found
Element66not found
Element0not found
Element333not found
200
444
333
100
11
22
33
44
55
66
No.of elements in linked list=10
No.OF elements in linked list=0
Sanjay 23 1100
Sachin 33 3500
Sourav 24 2400
Sanket 25 2500
Sandeep 26 2600
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
No.of elements in linked list=4
Sandeep 26 2600
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
Sandeep 26 2600
Sanjay 23 1100
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
No.of elements in linked list=6
Result
Thus the program to implement the template of linked list class is
implemented.
Ex. No 6 Generating Templates for standard sorting
algorithms
Aim
To write a C++ program to implement the Templates of standard sorting
algorithms such as bubble sort, insertion sort, merge sort, and quick sort
Algorithm
Step 1: Start the Process.
Step 2: Create the template to handle bubble sort, insertion sort, and
quick sort, merge sort.
Step 3: Get the element using for loop.
Step 4: Call the template function for sorting.
Step 5: Display the result.
Step 6: Stop the process.
Program
#include<iostream.h>
#include<conio.h>
int a[20];
enum Boolean{false,true};
void merge(int,int,int);
//Bubble Sort
template<class T>
void swap(T &x,T&y)
{
T t;
t=x;
x=y;
y=t;
}t
emplate<class T>
void bubb(T &s,int size)
{
Boolean swapped=true;
for(int i=0;(i<size-1)&&swapped;i++)
{
swapped=false;
for(int j=0;j<(size-1)-i;j++)
if(s[j]>s[j+1])
{
swapped=true;
swap(s[j],s[j+1]);
}}}
//Merge Sort
Template<class T>
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
//Insertion Sort
template<class T>
void insertionsort(T numbers[], int array_size)
{
T i, j, index;
for (i=1; i < array_size; i++)
{
index = numbers[i];
j = i;
while ((j > 0) && (numbers[j-1] > index))
{
numbers[j] = numbers[j-1];
j = j - 1;
}
numbers[j] = index;
}
}
//Quick Sort
template<class T>
int Partition(int low,int high,T arr[])
{ T pivot,high_vac,low_vac;
pivot=arr[low];
while(high>low)
{
high_vac=arr[high];
while(pivot<high_vac)
{
if(high<=low) break;
high--;
high_vac=arr[high];
24
Yolearn
http://www.yolearn.net
the network of education
}
arr[low]=high_vac;
low_vac=arr[low];
while(pivot>low_vac)
{
if(high<=low)
break;
low++;
low_vac=arr[low];
}
arr[high]=low_vac;
}
arr[low]=pivot;
return low;
}t
emplate<class T>
void Quick_sort(int low,int high,T arr[])
{
int Piv_index;
if(low<high)
{
Piv_index=Partition(low,high,arr);
Quick_sort(low,Piv_index-1,arr);
Quick_sort(Piv_index+1,high,arr);
}
}
void main()
{i
nt num[25],temp[25];
float floatnum[25];
int i,size,ch;
clrscr();
cout<<"Program to sort.."<<endl;
cout<<"enter the size of interger and float:";
cin>>size;
cout<<"Enter the integer element"<<endl;
for(i=0;i<size;i++)
cin>>num[i];
cout<<"Enter the float element"<<endl;
for( i=0;i<size;i++)
cin>>floatnum[i];
do
{
cout<<"Sorting"<<endl;
cout<<"1.Merge Sort\n2.Quick sort\n3.Insertion sort\n4.Bubble
sort\n5.Float bubble sort\n6.Float insertion sort\n7.Float quick
sort\n8.Exit"<<endl;
cout<<"Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
merge_sort(0,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 2:
Quick_sort(0,size-1,num);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 3:
insertionsort(num,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 4:
bubb(num,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 5:
bubb(floatnum,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 6:
insertionsort(floatnum,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 7:
Quick_sort(0,size-1,floatnum);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 8:
break;
}}
while(ch<8);
getch();
}
Output
Program to sort..
enter the size of interger and float:5
Enter the integer element
31240
Enter the float element
3.4
1.2
5.6
2.1
4.5
Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:2
sorted vector:
01234 Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:7
1.2
2.1
3.4
4.5
5.6
Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:8
Result
Thus the program to implement the Templates of standard sorting
algorithms such as bubble sort, insertion sort, merge sort, and quick sort is
implemented.
Ex. No 7a Design of Stack classes with necessary
Exception handling
Aim
To write a C++ program to implement the stack class with necessary
exception handling.
Algorithm
Step 1: Start the Process
Step 2: Create the class for stack.
Step 3: Declare the member function for push and pop operation.
Step 4: Push operation to insert the element.
Step 5: Pop operation to delete the element.
Step 6: Stop the Process.
Program
#include<iostream.h>
#define MAX 5
class stack
{
protected:
int arr[MAX];
public:
int item;
int top;
stack()
{t
op=0;
}
class overflowException{};
void push(int a)
{
cout<<top;
if(top<MAX)
{t
op++;
arr[top]=a;
}
else
{throw overflowException();
}}
class underflowException{};
int pop()
{if(top==0)
{throw underflowException();
}
else
{i
nt data=arr[top];
top--;
return data;
}
}}
;
int main()
{
char ch;
int choice;
stack a;
do
{
cout<<”1.Push\n2.Pop<<end1;
cout<<"Enter the choice";
cin>>choice;
switch(choice)
{
case 1:
try
{
cout<<"enter the item";
cin>>a.item;
a.push(a.item);
cout<<”Item pushed”;
}
catch(stack::overflowException )
{
cout<<"Stack overflow";
}
break;
case 2:
try
{
cout<<”Item Popped:”<<a.pop();
}
catch(stack::underflowException)
{
cout<<"Stack is empty";
}
break;
}
cout<<"do u want to continue";
cin>>ch;
}
while(ch=='y');
30
Yolearn
http://www.yolearn.net
the network of education
return 0;
}
Output
1.Push
2.Pop
Enter the choice:1
enter the item:2
Item pushed
do u want to continue Y
1.Push
2.Pop
Enter the choice:1
enter the item:3
Item pushed
do u want to continue Y
1.Push
2.Pop
Enter the choice:2
Item Popped:3
do u want to continue n
Result
Thus the program to implement the stack class with necessary exception
handling is implemented.
Ex. No 7b Designing of Queue classes with necessary
Exception handling
Aim
To write a C++ program to implement the Queue class with necessary
exception handling.
Algorithm
Step 1: Start the Process
Step 2: Create a class for queue.
Step 3: Declare the member function for front and rear operation.
Step 4: Provide necessary exception handling for stack and queue.
Step 5: Display the result.
Step 6: Stop the Process
Program
#include<iostream.h>
class que
{i
nt size;
int arr[5];
int rear,front;
int data;
public:
que()
{
size=5;
rear=-1;
front=-1;
}
class quefullException{};
void enque(int data)
{i
f(rear+1>=size)
{
throw quefullException();
}
else
{
if(rear==-1&&front==-1)
{
front++;
}
rear++;
cout<<"rear"<<rear;
arr[rear]=data;
cout<<arr[rear];
}}
class queEmptyException{};
int deque()
{i
f(front>rear)
{
throw queEmptyException();
}
return(arr[front++]);
}}
;
int main()
{
que q;
char choice;
do
{
Cout<<”1.Insert\n2.Delete”<<endl;
cout<<"enter the choice:";
int ch;
cin>>ch;
switch(ch)
{
case 1:
try
{
cout<<"enter the element to insert";
int item;
cin>>item;
q.enque(item);
cout<<“Item inserted”;
}
catch(que::quefullException)
{
cout<<"Queue is full";
}
break;
case 2:
try
{
cout<<"the deleted item from queue"<<q.deque();
}
catch(que::queEmptyException)
{
cout<<"queue is empty";
}
break;
}
cout<<"continue(y/n)";
cin>>choice;
}while(choice=='y');
}
Output
1.Insert
2.Delete
Enter the choice:1
enter the element to insert :2
Item inserted
continue (y/n)y
1.Insert
2.Delete
Enter the choice:1
enter the element to insert :3
Item inserted
continue (y/n)y
1.Insert
2.Delete
Enter the choice:2
the deleted item from queue:2
continue (y/n)n
Result
Thus the program to implement the Queue class with necessary exception
handling is implemented.
Ex. No 8 Implementation of Graph for calculating Minimum
Spanning Tree
Aim
To Write a C++ Program to implement the graph and to obtain a minimum
cost spanning tree.
Algorithm
Step 1: Start the Process.
Step 2:.Create a class to get the edges and cost of the graph.
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: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
class kruskal
{
private:
int n; //no of nodes
int noe; //no edges in the graph
int graph_edge[100][4];
int tree[10][10];
int sets[100][10];
int top[100];
public:
void read_graph();
void initialize_span_t();
void sort_edges();
void algorithm();
int find_node(int );
void print_min_span_t(); };
void kruskal::read_graph()
{
cout<<”*************************************************\n”
<<”This program implements the kruskal algorithm\n”
<<”*************************************************\n”;
cout<<”Enter the no. of nodes in the undirected weighted graph ::”;
cin>>n;
noe=0;
cout<<”Enter the weights for the following edges ::\n”;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cout<<” < “<<i<<” , “<<j<<” > ::”;
int w;
cin>>w;
if(w!=0)
{
noe++;
graph_edge[noe][1]=i;
graph_edge[noe][2]=j;
graph_edge[noe][3]=w; } } }
// print the graph edges
cout<<”\n\nThe edges in the given graph are::\n”;
for(i=1;i<=noe;i++)
cout<<” < “<<graph_edge[i][1]
<<” , “<<graph_edge[i][2]
<<” > ::”<<graph_edge[i][3]<<endl;
}
void kruskal::sort_edges()
{
/**** Sort the edges using bubble sort in increasing order**************/
for(int i=1;i<=noe-1;i++)
{
for(int j=1;j<=noe-i;j++)
{
if(graph_edge[j][3]>graph_edge[j+1][3])
{
int t=graph_edge[j][1];
graph_edge[j][1]=graph_edge[j+1][1];
graph_edge[j+1][1]=t;
t=graph_edge[j][2];
graph_edge[j][2]=graph_edge[j+1][2];
graph_edge[j+1][2]=t;
t=graph_edge[j][3];
graph_edge[j][3]=graph_edge[j+1][3];
graph_edge[j+1][3]=t; } } }
// print the graph edges
cout<<”\n\nAfter sorting the edges in the given graph are::\n”;
for(i=1;i<=noe;i++)
cout<<” < “<<graph_edge[i][1]
<<” , “<<graph_edge[i][2]
<<” > ::”<<graph_edge[i][3]<<endl; }
void kruskal::algorithm()
{
// ->make a set for each node
for(int i=1;i<=n;i++)
{
sets[i][1]=i;
top[i]=1; }
cout<<”\nThe algorithm starts ::\n\n”;
for(i=1;i<=noe;i++)
{
int p1=find_node(graph_edge[i][1]);
int p2=find_node(graph_edge[i][2]);
if(p1!=p2)
{
cout<<”The edge included in the tree is ::”
<<” < “<<graph_edge[i][1]<<” , “
<<graph_edge[i][2]<<” > “<<endl<<endl;
tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3];
tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3];
// Mix the two sets
for(int j=1;j<=top[p2];j++)
{
top[p1]++;
sets[p1][top[p1]]=sets[p2][j]; }
top[p2]=0; }
else
{
cout<<”Inclusion of the edge “
<<” < “<<graph_edge[i][1]<<” , “
<<graph_edge[i][2]<<” > “<<”forms a cycle so it is removed\n\n”; } } }
int kruskal::find_node(int n)
{
for(int i=1;i<=noe;i++)
{
for(int j=1;j<=top[i];j++)
{
if(n==sets[i][j])
return i; } }
return -1; }
int main()
{
clrscr();
kruskal obj;
obj.read_graph();
obj.sort_edges();
obj.algorithm();
return 0;
getch(); }
Output
*************************************************
This program implements the kruskal algorithm
*************************************************
Enter the no. of nodes in the undirected weighted graph ::3
Enter the weights for the following edges ::
< 1 , 2> ::3
< 1 , 3> ::1
< 2 , 3> ::4
The edges in the given graph are::
< 1 , 2 > ::3
< 1 , 3 > ::1
< 2 , 3 > ::4
After sorting the edges in the given graph are::
< 1, 3 > ::1
< 1, 2 > ::3
< 2, 3 > ::4
The algorithm starts ::
The edge included in the tree is :: < 1 , 3 >
The edge included in the tree is :: < 1 , 2 >
Inclusion of the edge < 2 , 3 > forms a cycle so it is removed
Result
Thus the Program to implement the graph and to obtain a minimum cost
spanning tree is implemented.
Ex. No 9 Implementation of dynamic polymorphism & RTTI
Aim
To write a C++ program to implement Hierarchy classes with Dynamic
polymorphism and Use Virtual concept along with RTTI
Algorithm
Step 1: Start the Process.
Step 2: Create a class SHAPE with data member and one member function as
Virtual.
Step 3: Create a derived class square,rectangle,polygon,circle and triangle with
SHAPE as base class.
Step 4: Create a Object in the main function.
Step 5: Invoke the appropriate function using object.
Step 6: Finally display the result.
Step 7: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
class shape
{
public:
int x,y;
public:
void getdata(int a,int b=0)
{
x=a;
y=b;
}
virtual void area()
{
cout<<"shape ";
}}
;
class square:public shape
{
public:
void area()
{
cout<<"area of square:"<<x*x<<endl;
}}
;
class rectangle:public shape
{
public:
void area()
{
cout<<"area of rectangle:"<<x*y<<endl;
}}
;
class circle:public shape
{
public:
void area()
{
cout<<"area of circle:"<<(3.14)*x*x<<endl;
}};
class triangle:public shape
{
public:
int area1;
void area()
{
cout<<"area of triangle:";
area1=(0.5)*x*y;
cout<<area1<<endl;
}}
;
class polygon:public triangle
{
public:
void area()
{
cout<<"area of polygon:"<<6*area1<<endl;
}}
;
void main()
{
clrscr();
shape *s;
triangle t;
square sq;
rectangle rt;
polygon p;
circle c;
s=&t;
s->getdata(3,2);
s->area();
s=&sq;
s->getdata(4);
s->area();
s=&c;
s->getdata(3);
s->area();
s=&rt;
s->getdata(2,4);
s->area();
s=&p;
s->area();
getch();
}
Output
area of triangle:3
area of square:16
area of circle:28.26
area of rectangle:8
area of polygon:23772
Result
Thus the program to implement Hierarchy classes with Dynamic
polymorphism and Use of Virtual concept along with RTTI is implemented.
Ex. No 10 File operations with randomly generated complex
Number
Aim
the network of education
To a C++ program to implement the randomly generates complex
numbers and write them two per line in a file along with an operator. 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.
Algorithm
Step 1: Start the Process.
Step 2: Create two files.
Step 3: One file is to read and another file to write.
Step 4: Do the operations in one file and write the result in another file.
Step 5: Display the result.
Step 6: Stop the Process.
Program
//Complex Class defined in a.cpp program
#include<iostream.h>
class complex
{f
loat real,imag;
public:
void get()
{
cin>>real>>imag;
}f
loat put1()
{
return real;
}f
loat put2()
{
return imag;
}}
;
//Program for writing a complex numbers in a file along with operators
#include "a.cpp"
#include<fstream.h>
#include<conio.h>
void main()
{clrscr();
fstream f("a.txt",ios::out);
complex c,c1;
char ch;
do
{
cout<<"enter the complex number1";
c1.get();
cout<<"enter the complex number2";
c.get();
char op;
cout<<"enter the operation to perform";
cin>>op;
f<<c1.put1()<<",i";
f<<c1.put2()<<"\t"<<op<<"\t";
f<<c.put1()<<",i";
f<<c.put2()<<endl;
cout<<"do u want to write one more";
cin>>ch;
}while(ch=='y');
f.close();
}
//Program for reading from file one line at a time and doing corresponding
operation and write the result in another file
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
clrscr();
fstream f1("a.txt",ios::in);
float r1,r2,r3,im1,im2,im3;
char *opertor,*c1,*c2,buffer[100];
while(!f1.eof())
{f
1.getline(buffer,100);
cout<<buffer<<endl;
for(int j=0;j<100;j++)
{if(buffer[j]=='+'||buffer[j]=='-'||buffer[j]=='*'||buffer[j]=='/')
{
char o=buffer[j];
opertor=&o;
c1=strtok(buffer,opertor);
cout<<"c1"<<c1<<endl;
c2=strtok(NULL,opertor);
cout<<"c2"<<c2<<endl;
}i
f(*opertor=='+')
{
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"1st"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img of c1:"<<r1<<r2<<im1<<im2<<endl;
r3=r1+r2;
im3=im1+im2;
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<"i"<<im3<<endl;
}
else
{
if(*opertor=='-')
{ char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"2nd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img of c2:"<<r1<<r2<<im1<<im2<<endl;
r3=r1-r2;
im3=im1-im2;
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<im3<<"i"<<endl;
f2.close();
}
else
{
if(*opertor=='*')
{
cout<<"entered";
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"3rd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img"<<r1<<r2<<im1<<im2;
r3=(r1*r2)-(im1*im2);
im3=(im1*r2)+(im2*r1);
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<","<<im3<<"i"<<endl;
f2.close();
}
else
{
if(*opertor=='/')
{
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"3rd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img"<<r1<<r2<<im1<<im2;
r3=((r1*r2)+(im1*im2))/((im1*im1)+(im2*im2));
im3=((im1*r2)-(im2*r1))/((im1*im1)+(im2*im2));
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<im3<<"i"<<endl;
f2.close();
}}
}}
}}}
Output:
Writing in a file:
enter the complex number11
1e
nter the complex number21
1e
nter the operation to perform+
do u want to write one more y
enter the complex number1 2
2e
nter the complex number2 1
1e
nter the operation to performdo
u want to write one more y
enter the complex number1 1
1e
nter the complex number2 1
1e
nter the operation to perform*
do u want to write one more y
enter the complex number12
1e
nter the complex number2 2
2e
nter the operation to perform/
do u want to write one more n
Text file a.txt:
1,i1 + 1,i1
2,i2 - 1,i1
1,i1 * 1,i1
2,i1 / 2,i2
Out.txt
2 i2
1 1i
0 2i
1.2 -0.4i
Result
Thus the program to implement the randomly generates complex
numbers and write them two per line in a file along with an operator. 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 is implemented.
For more lab manuals , question banks , syllabus . please log on to http://
www.yolearn.net
49
Argument and Friend Function
Aim
To Write a C++ program for Students mark analysis using Static Data
member, Default Argument and Friend Function.
Algorithm
Step 1: Start the Process.
Step 2: Get the Students detail and calculate the Result analysis.
Step 3: Default value is assigned for pass in a function and the function is
assigned with default value when value for pass is not given in checking
for pass status.
Step 4: Declare the integer count as Static member each time when the student is
pass it will be incremented and finally specify pass count.
Step 5: The friend function display is used to access the private variables from
two classes and acting as the bridge between two classes.
Step 6: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
int cp(int,int,int,int=50);
void printline(char ch='*',int range= 70);
class per;
class acc
{i
nt rno,tot;
static int count;
int m1,m2,m3;
char name[20],grade;
float avg;
public:
void getdata()
{
cout<<"Enter id:";
cin>>rno;
cout<<"Enter name:";
cin>>name;
cout<<"Enter m1";
cin>>m1;
cout<<"Enter m2";
cin>>m2;
cout<<"Enter m3";
cin>>m3;
}friend void display(acc,per);
void cal()
{
tot=0;
if(cp(m1,m2,m3))
{
cout<<"Result=pass"<<endl;
tot=m1+m2+m3;
avg=tot/3;
count=count+1;
if(avg>=90)
grade='O';
if(avg>=70&&avg<90)
grade='A';
if(avg>=50&&avg<70)
grade='B';
}
else
{
cout<<"Result=Fail"<<endl;
}}
static void showcount(void)
{
cout<<endl;
cout<<"count:"<<count;}};
int acc::count;
class per
{
char add[25];
long tel;
public:
void getdata1()
{
cout<<"Enter address";
cin>>add;
cout<<"Enter phoneno:";
cin>>tel;
}
friend void display(acc a,per p)
{
cout<<endl;
cout<<"Name:"<<a.name<<endl;
cout<<"ID:"<<a.rno<<endl;
cout<<"Address:"<<p.add<<endl;
cout<<"Phone no.:"<<p.tel<<endl;
cout<<"M1:"<<a.m1<<endl;
cout<<"M2:"<<a.m2<<endl;
cout<<"M3:"<<a.m3<<endl;
if(cp(a.m1,a.m2,a.m3))
{
cout<<"Total:"<<a.tot<<endl;
cout<<"Average:"<<a.avg<<endl;
cout<<"Grade:"<<a.grade<<endl;
}}};
int cp(int m1,int m2,int m3,int pass1)
{
if(m1>=pass1&&m2>=pass1&&m3>=pass1)
return(1);
else
return(0);
}
void main()
{
int i,n;
clrscr();
per p1[20];
acc a1[20];
cout<<"Enter no of students:";
cin>>n;
for(i=0;i<n;i++)
{
a1[i].getdata();
p1[i].getdata1();
a1[i].cal();
}
for(i=0;i<n;i++)
{
printline('-');
display(a1[i],p1[i]);
printline();
}
acc::showcount();
getch();
}
void printline(char ch,int range)
{
int i;
cout<<endl;
for(i=0;i<range;i++)
cout<<ch;}
Output
Enter no of students:2
Enter id:2
Enter name:rahul
Enter m1:78
Enter m2:90
Enter m3:67
Enter address:coimbatore
Enter phoneno:230000
Result=pass
Enter id:5
Enter name:aravind
Enter m1:56
Enter m2:45
Enter m3:78
Enter address:madurai
Enter phoneno:456789
Result=Fail
-----------------------------------------------------------
Name:rahul
ID:2
Address:coimbatore
Phone no.:230000
M1:78
M2:90
M3:67
Total:235
Average:78
Grade:A
***********************************************************
-----------------------------------------------------------
Name:aravind
ID:5
Address:madurai
Phone no.:456789
M1:56
4
Yolearn
http://www.yolearn.net
the network of education
M2:45
M3:78
***********************************************************
count:1
Result
Thus the program to perform Students mark analysis using Static Data
member, Default Argument and Friend Function was implemented.
Ex. No 2 Implementation of complex number class with operator
overloading and type conversions
Aim
To write a C++ program to implement complex number class with
operator overloading and type conversions such as integer to complex, double to
complex, complex to double.
Algorithm
Step 1: Start the program.
Step 2: Create a class with necessary data members and member functions.
Step 3: Create a constructor to initialize the variables.
Step 4: Perform addition of two numbers overloading the necessary operators.
Step 5: Create an object for the Complex class and call the required functions to
perform the action.
Step 6: Perform the type conversion from double to complex, integer to complex
and complex to double.
Step 7: Display the result.
Step 8: Stop the program.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
class complex
{
float real,img,temp;
public:
complex()
{
real=img=0;
}
complex(int a)
{
real=a;
img=0;
}
complex(double a1)
{
real=a1;
img=0.0;
}
void outdata()
{i
f(img>=0.0)
{
cout<<real<<"+"<<img<<"i";
}
else
{
cout<<real<<img<<"i";
}}
complex operator+(complex c)
{
complex temp;
temp.real=real+c.real;
temp.img=img+c.img;
return(temp);
}
complex operator-(complex c)
{
complex temp1;
temp1.real=real-c.real;
temp1.img=img-c.img;
return(temp1);
}
complex operator*(complex c)
{
complex temp2;
temp2.real=real*c.real-img*c.img;
temp2.img=real*c.img+img*c.real;
return(temp2);
}
complex operator/(complex c)
{
complex temp3;
temp3.real=(((real*c.real)+(img*c.img))/((c.real*c.real)+(c.img*c.img)));
temp3.img=(((img*c.real)-(real*c.img))/((c.real*c.real)+(c.img*c.img)));
return(temp3);
}
operator double()
{
double magnitude;
magnitude=sqrt(pow(real,2)+pow(img,2));
return magnitude;
}}
;
void main()
{
clrscr();
complex c1,c2,c3,c4,c5,c6;
int real;
double real1;
cout<<"Enter the real number";
cin>>real;
c1=real;
cout<<"Integer to complex conversion"<<endl;
cout<<"Enter the real number";
cin>>real1;
c2=real1;
cout<<"Double to complex conversion"<<endl;
c3=c1+c2;
c4=c1-c2;
c5=c1*c2;
c6=c1/c2;
cout<<"\n\n";
cout<<"addtion result is:";
c3.outdata();
cout<<"\n\n";
cout<<"subraction result is:";
c4.outdata();
cout<<"\n\n";
cout<<"multiplication result is:";
c5.outdata();
cout<<"\n\n";
cout<<"division result is:";
c6.outdata();
cout<<"Conversion from complex to double"<<endl;
double mag=c3;
cout<<"Magnitude of a complex number"<<mag;
getch();
}
Output
Enter the real number:2
Integer to complex conversion
Enter the real number:2.0
Double to complex conversion
addtion result is:4+0i
subraction result is:0+0i
multiplication result is:4+0i
division result is:1+0i
Conversion from complex to double
Magnitude of a complex number:4
Result
Thus the program to implement complex number class with operator
overloading and type conversions such as integer to complex, double to complex,
complex to double is implemented.
Ex. No 3 Implement the Matrix Class using Constructor, Destructor,Copy
Constructor, Overloading assignment operator
Aim
To Write a C++ program to Implement Matrix Class using Constructor,
Destructor, Copy Constructor, Overloading assignment operator
Algorithm
Step 1: Start the Process.
Step 2: Create the class name as MATRIX.
Step 3: Declare the data member and member function.
Step 4: Declare constructor, destructor and copy constructor
Step 5: Display the result.
Step 6: Stop the process.
Program
#include<iostream.h>
#include<conio.h>
class matrix
{
private:
int row;
int col;
int **p;
public:
matrix() //Constructor
{
row=col=0;
p=NULL;
}
matrix(int r,int c);
~matrix(); //Destructor
void read();
void show();
void add(matrix &a,matrix &b);
void sub(matrix &a,matrix &b);
void operator =(matrix &m1)
{
row=m1.row;
col=m1.col;
p=new int *[m1.row]; //dynamic allocation
for(int i=0;i<m1.row;i++)
{
p[i]=new int[m1.col];//dynamic allocation
}}
matrix(matrix &m2)//copy construtor
{
row=m2.row;
col=m2.col;
p=new int *[m2.row]; //dynamic allocation
for(int i=0;i<m2.row;i++)
{
p[i]=new int[m2.col];//dynamic allocation
}
for(i=0;i<m2.row;i++)
for(int j=0;j<m2.col;j++)
{
p[i][j]=m2.p[i][j];
}}}
; matrix::matrix(int r,int c)
{
row=r;
col=c;
p=new int *[row]; //dynamic allocation
for(int i=0;i<row;i++)
p[i]=new int[col];//dynamic allocation
}
matrix::~matrix()
{
for(int i=0;i<row;i++)
delete p[i];
delete p;
}
void matrix::add(matrix &a,matrix &b)
{i
nt i,j;
row=a.row;
col=b.col;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[i][j]=a.p[i][j]+b.p[i][j];
}
void matrix::sub(matrix &a,matrix &b)
{i
nt i,j;
row=a.row;
col=b.col;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[i][j]=a.p[i][j]-b.p[i][j];
}
void matrix::read()
{int i,j;
10
Yolearn
http://www.yolearn.net
the network of education
for( i=0;i<row;i++)
for( j=0;j<col;j++)
{
cout<<"Matrix["<<i<<","<<j<<"]=";
cin>>p[i][j];
}}
void matrix::show()
{
int i,j;
for(i=0;i<row;i++)
{
cout<<endl;
for( j=0;j<col;j++)
{
cout<<p[i][j]<<"\t";
}
}
}
void main()
{i
nt m,n,p,g,q;
clrscr();
cout<<"Enter the A matrix"<<endl;
cout<<"How many rows?";
cin>>m;
cout<<"How many col?";
cin>>n;
matrix a(m,n);
a.read();
matrix b;
b=a;//overloading assignment operator
cout<<”Overloading assignment operator Invoked”<<endl;
cout<<”Enter the B matrix”;
b.read();
cout<<"Matrix A is ..";
a.show();
cout<<endl<<"Matrix B is..";
b.show();
matrix c(m,n);
c.add(a,b);
cout<<endl<<"c=a+b..";
c.show();
matrix d(m,n);
d.sub(a,b);
cout<<endl<<"d=a-b..";
d.show();
cout<<"\nCopy constructor invoked"<<endl;
matrix e(d);//Copy Constructor
e.show();
getch();
}
Output
Enter the A matrix
How many rows?2
How many col?2
Matrix[0,0]=2
Matrix[0,1]=2
Matrix[1,0]=2
Matrix[1,1]=2
Overloading assignment operator Invoked
Enter the B matrix
Matrix[0,0]=1
Matrix[0,1]=1
Matrix[1,0]=1
Matrix[1,1]=1
Matrix A is ..
2 2
2 2
Matrix B is..
1 1
1 1
c=a+b..
3 3
3 3
d=a-b..
1 1
1 1
Copy constructor invoked
1 1
1 1
Result
Thus the C++ program to Implement Matrix Class using Constructor,
Destructor, Copy Constructor, Overloading assignment operator is implemented.
Ex. No 4 Overloading of new and delete operators for addition of
vector elements
Aim
To write a C++ program to Overload the new and delete operators for
addition of vector elements to provide custom dynamic allocation of memory.
Algorithm
Step 1: Start the program.
Step 2: Declare the necessary function prototype.
Step 3: Define void *operator new (), void operator delete () functions to allocate
storage and to delete the memory with the help of malloc and free
functions respectively.
Step 4: read () and sum () functions to get and calculate the vector addition.
Step 5: Stop the program.
Program
#include<iostream.h>
const int asize=10;
class vector
{i
nt *a;
public:
void * operator new(size_t )
{
vector *v;
v=::new vector;
v->a=new int[asize];
return v;
}
void operator delete(void *vec)
{
vector *v;
v=(vector *)vec;
delete(int*) v->a;
::delete vec;
}
void read()
{f
or(int i=0;i<asize;i++)
{
cin>>a[i];
}}i
nt sum()
{i
nt sum=0;
for(int i=0;i<asize;i++)
{
sum+=a[i];
}
return sum;
}}
;
void main()
{
vector *v=new vector;
cout<<”Enter the vector elements”;
v->read();
cout<<”the sum of vector elements”<<v->sum();
delete v;
}
Output
Enter the vector elements 10
10
10
10
10
10
10
10
10
10
The sum of vector elements: 100
Result
Thus the program to Overload the new and delete operators for
addition of vector elements to provide custom dynamic allocation of memory is
implemented.
Ex. No 5 Implementation of Template for Linked List Class
with necessary methods
Aim
To write a C++ program to implement the template of linked list class.
Algorithm
Step1: Start the program.
Step2: Create an emp and linked list class, declare necessary data members.
Also create a node structure with template based variables and link field.
Include necessary constructor, member function and destructor.
Step3: Define constructor linklist() to initialize the variable. Define
member function such as., void append(T),void addatbeg(T),void
addafter(int,T),void del(int),void display(),int count() to perform various
operation in the linked list.
Step4: Use destructor ~linklist() to destroy the allocated memory.
Step5: Create required objects to call the necessary function to perform all the
operations.
Step6: Display the result.
Step7: Stop the program.
Program
#include<iostream.h>
#include<string.h>
#include<iostream.h>
class emp
{
private:
char name[20];
int age;
float sal;
public:
emp(char *n="",int a=0,float s=0.0)
{
strcpy(name,n);
age=a;
sal=s;
}f
riend ostream&operator<<(ostream &s,emp &e);
};
ostream&operator<<(ostream &s,emp &e)
{
cout<<e.name<<'\t'<<e.age<<'\t'<<e.sal;
return s;
}t
emplate<class T>
class linklist
{
private:
struct node
{
T data;
node *link;
}*p;
public:
linklist();
void append(T);
void addatbeg(T);
void addafter(int,T);
void del(int);
void display();
int count();
~linklist();
};
template<class T>
linklist<T>::linklist()
{
p=NULL;
}
//Adds a new node at the end of the linked list
template<class T>
void linklist<T>::append(T num)
{
node *q,*t;
//if the list is empty
if(p==NULL)
{
//create first node
p=new node;
p->data=num;
p->link=NULL;
}
else
{
//go to the last node
q=p;
while(q->link!=NULL)
q=q->link;
//add node at the end
t=new node;
t->data=num;
t->link=NULL;
q->link=t;
}}
//adds a new node at the beginning of the linked list
template<class T>
void linklist<T>::addatbeg(T num)
{
node *q;
//add new node
q=new node;
q->data=num;
q->link=p;
p=q;
}
//adds a new node after the specified number of nodes
template<class T>
void linklist<T>::addafter(int c,T num)
{
node *q,*t;
int i;
//skip to the desired portion
17
Yolearn
http://www.yolearn.net
the network of education
for(i=0;q=p,i<=c;i++)
{
q=q->link;
//if end of linked list is encountered
if(q==NULL)
{
cout<<endl<<"There are less than"<<c<<"elements.";
return;
}}
//insert new node
t=new node;
t->data=num;
t->link=q->link;
q->link=t;
}
//deletes the specified node from the linked list
template<class T>
void linklist<T>::del(int n)
{
node *q,*r;
int i=1;
q=p;
//if node to be deleted is first node
if(n==1)
{
p=q->link;
delete q;
return;
}
//traverse list till the last but one node is reached
r=q;
while(q!=NULL)
{i
f(i==n)
{
r->link=q->link;
//free the memory occupied by the node
delete q;
return;
}
r=q;
q=q->link;
i++;
}
cout<<endl<<"Element"<<n<<"not found";
}//displays the contents of the linked list
template<class T>
void linklist<T>::display()
{
node *q;
cout<<endl;
//traverse the entire linked list
for(q=p;q!=NULL;q=q->link)
cout<<q->data<<endl;
}//counts number of nodes present in the linked list
template<class T>
int linklist<T>::count()
{
node *q;
int c=0;
//traverse the entire linked list
for(q=p;q!=NULL;q=q->link)
c++;
return(c);
}//destroys the linked list object
template<class T>
linklist<T>::~linklist()
{
node *t;
while(p!=NULL)
{t
=p;
p=p->link;
delete t;
}}
void main()
{l
inklist<int>l1;
cout<<endl<<"No.of elements in Linked list="<<l1.count();
l1.append(11);
l1.append(22);
l1.append(33);
l1.append(44);
l1.append(55);
l1.append(66);
l1.addatbeg(100);
l1.addatbeg(200);
l1.addafter(3,333);
l1.addafter(6,444);
l1.display();
cout<<endl<<"No.of elements in linked list="<<l1.count();
l1.del(200);
l1.del(66);
l1.del(0);
l1.del(333);
l1.display();
cout<<endl<<"No.of elements in linked list="<<l1.count();
linklist<emp>l2 ;
cout<<endl<<"No.OF elements in linked list="<<l2.count();
emp e1("Sanjay",23,1100.00);
emp e2("Sachin",33,3500.00);
emp e3("Sourav",24,2400.00);
emp e4("Sanket",25,2500.00);
emp e5("Sandeep",26,2600.00);
l2.append(e1);
l2.append(e2);
l2.append(e3);
l2.append(e4);
l2.append(e5);
l2.display();
l2.del(3);
l2.display();
cout<<endl<<"No.of elements in linked list="<<l2.count();
l2.addatbeg(e5);
l2.display();
l2.addafter(3,e1);
l2.display();
cout<<endl<<"No.of elements in linked list="<<l2.count();
}
Output
No.of elements in linked list =0
200
444
100
333
11
22
33
44
55
66
No.of elements in linked list=10
Element200not found
Element66not found
Element0not found
Element333not found
200
444
333
100
11
22
33
44
55
66
No.of elements in linked list=10
No.OF elements in linked list=0
Sanjay 23 1100
Sachin 33 3500
Sourav 24 2400
Sanket 25 2500
Sandeep 26 2600
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
No.of elements in linked list=4
Sandeep 26 2600
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
Sandeep 26 2600
Sanjay 23 1100
Sanjay 23 1100
Sachin 33 3500
Sanket 25 2500
Sandeep 26 2600
No.of elements in linked list=6
Result
Thus the program to implement the template of linked list class is
implemented.
Ex. No 6 Generating Templates for standard sorting
algorithms
Aim
To write a C++ program to implement the Templates of standard sorting
algorithms such as bubble sort, insertion sort, merge sort, and quick sort
Algorithm
Step 1: Start the Process.
Step 2: Create the template to handle bubble sort, insertion sort, and
quick sort, merge sort.
Step 3: Get the element using for loop.
Step 4: Call the template function for sorting.
Step 5: Display the result.
Step 6: Stop the process.
Program
#include<iostream.h>
#include<conio.h>
int a[20];
enum Boolean{false,true};
void merge(int,int,int);
//Bubble Sort
template<class T>
void swap(T &x,T&y)
{
T t;
t=x;
x=y;
y=t;
}t
emplate<class T>
void bubb(T &s,int size)
{
Boolean swapped=true;
for(int i=0;(i<size-1)&&swapped;i++)
{
swapped=false;
for(int j=0;j<(size-1)-i;j++)
if(s[j]>s[j+1])
{
swapped=true;
swap(s[j],s[j+1]);
}}}
//Merge Sort
Template<class T>
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
//Insertion Sort
template<class T>
void insertionsort(T numbers[], int array_size)
{
T i, j, index;
for (i=1; i < array_size; i++)
{
index = numbers[i];
j = i;
while ((j > 0) && (numbers[j-1] > index))
{
numbers[j] = numbers[j-1];
j = j - 1;
}
numbers[j] = index;
}
}
//Quick Sort
template<class T>
int Partition(int low,int high,T arr[])
{ T pivot,high_vac,low_vac;
pivot=arr[low];
while(high>low)
{
high_vac=arr[high];
while(pivot<high_vac)
{
if(high<=low) break;
high--;
high_vac=arr[high];
24
Yolearn
http://www.yolearn.net
the network of education
}
arr[low]=high_vac;
low_vac=arr[low];
while(pivot>low_vac)
{
if(high<=low)
break;
low++;
low_vac=arr[low];
}
arr[high]=low_vac;
}
arr[low]=pivot;
return low;
}t
emplate<class T>
void Quick_sort(int low,int high,T arr[])
{
int Piv_index;
if(low<high)
{
Piv_index=Partition(low,high,arr);
Quick_sort(low,Piv_index-1,arr);
Quick_sort(Piv_index+1,high,arr);
}
}
void main()
{i
nt num[25],temp[25];
float floatnum[25];
int i,size,ch;
clrscr();
cout<<"Program to sort.."<<endl;
cout<<"enter the size of interger and float:";
cin>>size;
cout<<"Enter the integer element"<<endl;
for(i=0;i<size;i++)
cin>>num[i];
cout<<"Enter the float element"<<endl;
for( i=0;i<size;i++)
cin>>floatnum[i];
do
{
cout<<"Sorting"<<endl;
cout<<"1.Merge Sort\n2.Quick sort\n3.Insertion sort\n4.Bubble
sort\n5.Float bubble sort\n6.Float insertion sort\n7.Float quick
sort\n8.Exit"<<endl;
cout<<"Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
merge_sort(0,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 2:
Quick_sort(0,size-1,num);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 3:
insertionsort(num,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 4:
bubb(num,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<num[i]<<"\n";
break;
case 5:
bubb(floatnum,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 6:
insertionsort(floatnum,size);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 7:
Quick_sort(0,size-1,floatnum);
cout<<"sorted vector:"<<endl;
for(i=0;i<size;i++)
cout<<floatnum[i]<<"\n";
break;
case 8:
break;
}}
while(ch<8);
getch();
}
Output
Program to sort..
enter the size of interger and float:5
Enter the integer element
31240
Enter the float element
3.4
1.2
5.6
2.1
4.5
Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:2
sorted vector:
01234 Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:7
1.2
2.1
3.4
4.5
5.6
Sorting
1.Merge Sort
2.Quick sort
3.Insertion sort
4.Bubble sort
5.Float bubble sort
6.Float insertion sort
7.Float quick sort
8.Exit
Enter your choice:8
Result
Thus the program to implement the Templates of standard sorting
algorithms such as bubble sort, insertion sort, merge sort, and quick sort is
implemented.
Ex. No 7a Design of Stack classes with necessary
Exception handling
Aim
To write a C++ program to implement the stack class with necessary
exception handling.
Algorithm
Step 1: Start the Process
Step 2: Create the class for stack.
Step 3: Declare the member function for push and pop operation.
Step 4: Push operation to insert the element.
Step 5: Pop operation to delete the element.
Step 6: Stop the Process.
Program
#include<iostream.h>
#define MAX 5
class stack
{
protected:
int arr[MAX];
public:
int item;
int top;
stack()
{t
op=0;
}
class overflowException{};
void push(int a)
{
cout<<top;
if(top<MAX)
{t
op++;
arr[top]=a;
}
else
{throw overflowException();
}}
class underflowException{};
int pop()
{if(top==0)
{throw underflowException();
}
else
{i
nt data=arr[top];
top--;
return data;
}
}}
;
int main()
{
char ch;
int choice;
stack a;
do
{
cout<<”1.Push\n2.Pop<<end1;
cout<<"Enter the choice";
cin>>choice;
switch(choice)
{
case 1:
try
{
cout<<"enter the item";
cin>>a.item;
a.push(a.item);
cout<<”Item pushed”;
}
catch(stack::overflowException )
{
cout<<"Stack overflow";
}
break;
case 2:
try
{
cout<<”Item Popped:”<<a.pop();
}
catch(stack::underflowException)
{
cout<<"Stack is empty";
}
break;
}
cout<<"do u want to continue";
cin>>ch;
}
while(ch=='y');
30
Yolearn
http://www.yolearn.net
the network of education
return 0;
}
Output
1.Push
2.Pop
Enter the choice:1
enter the item:2
Item pushed
do u want to continue Y
1.Push
2.Pop
Enter the choice:1
enter the item:3
Item pushed
do u want to continue Y
1.Push
2.Pop
Enter the choice:2
Item Popped:3
do u want to continue n
Result
Thus the program to implement the stack class with necessary exception
handling is implemented.
Ex. No 7b Designing of Queue classes with necessary
Exception handling
Aim
To write a C++ program to implement the Queue class with necessary
exception handling.
Algorithm
Step 1: Start the Process
Step 2: Create a class for queue.
Step 3: Declare the member function for front and rear operation.
Step 4: Provide necessary exception handling for stack and queue.
Step 5: Display the result.
Step 6: Stop the Process
Program
#include<iostream.h>
class que
{i
nt size;
int arr[5];
int rear,front;
int data;
public:
que()
{
size=5;
rear=-1;
front=-1;
}
class quefullException{};
void enque(int data)
{i
f(rear+1>=size)
{
throw quefullException();
}
else
{
if(rear==-1&&front==-1)
{
front++;
}
rear++;
cout<<"rear"<<rear;
arr[rear]=data;
cout<<arr[rear];
}}
class queEmptyException{};
int deque()
{i
f(front>rear)
{
throw queEmptyException();
}
return(arr[front++]);
}}
;
int main()
{
que q;
char choice;
do
{
Cout<<”1.Insert\n2.Delete”<<endl;
cout<<"enter the choice:";
int ch;
cin>>ch;
switch(ch)
{
case 1:
try
{
cout<<"enter the element to insert";
int item;
cin>>item;
q.enque(item);
cout<<“Item inserted”;
}
catch(que::quefullException)
{
cout<<"Queue is full";
}
break;
case 2:
try
{
cout<<"the deleted item from queue"<<q.deque();
}
catch(que::queEmptyException)
{
cout<<"queue is empty";
}
break;
}
cout<<"continue(y/n)";
cin>>choice;
}while(choice=='y');
}
Output
1.Insert
2.Delete
Enter the choice:1
enter the element to insert :2
Item inserted
continue (y/n)y
1.Insert
2.Delete
Enter the choice:1
enter the element to insert :3
Item inserted
continue (y/n)y
1.Insert
2.Delete
Enter the choice:2
the deleted item from queue:2
continue (y/n)n
Result
Thus the program to implement the Queue class with necessary exception
handling is implemented.
Ex. No 8 Implementation of Graph for calculating Minimum
Spanning Tree
Aim
To Write a C++ Program to implement the graph and to obtain a minimum
cost spanning tree.
Algorithm
Step 1: Start the Process.
Step 2:.Create a class to get the edges and cost of the graph.
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: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
class kruskal
{
private:
int n; //no of nodes
int noe; //no edges in the graph
int graph_edge[100][4];
int tree[10][10];
int sets[100][10];
int top[100];
public:
void read_graph();
void initialize_span_t();
void sort_edges();
void algorithm();
int find_node(int );
void print_min_span_t(); };
void kruskal::read_graph()
{
cout<<”*************************************************\n”
<<”This program implements the kruskal algorithm\n”
<<”*************************************************\n”;
cout<<”Enter the no. of nodes in the undirected weighted graph ::”;
cin>>n;
noe=0;
cout<<”Enter the weights for the following edges ::\n”;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cout<<” < “<<i<<” , “<<j<<” > ::”;
int w;
cin>>w;
if(w!=0)
{
noe++;
graph_edge[noe][1]=i;
graph_edge[noe][2]=j;
graph_edge[noe][3]=w; } } }
// print the graph edges
cout<<”\n\nThe edges in the given graph are::\n”;
for(i=1;i<=noe;i++)
cout<<” < “<<graph_edge[i][1]
<<” , “<<graph_edge[i][2]
<<” > ::”<<graph_edge[i][3]<<endl;
}
void kruskal::sort_edges()
{
/**** Sort the edges using bubble sort in increasing order**************/
for(int i=1;i<=noe-1;i++)
{
for(int j=1;j<=noe-i;j++)
{
if(graph_edge[j][3]>graph_edge[j+1][3])
{
int t=graph_edge[j][1];
graph_edge[j][1]=graph_edge[j+1][1];
graph_edge[j+1][1]=t;
t=graph_edge[j][2];
graph_edge[j][2]=graph_edge[j+1][2];
graph_edge[j+1][2]=t;
t=graph_edge[j][3];
graph_edge[j][3]=graph_edge[j+1][3];
graph_edge[j+1][3]=t; } } }
// print the graph edges
cout<<”\n\nAfter sorting the edges in the given graph are::\n”;
for(i=1;i<=noe;i++)
cout<<” < “<<graph_edge[i][1]
<<” , “<<graph_edge[i][2]
<<” > ::”<<graph_edge[i][3]<<endl; }
void kruskal::algorithm()
{
// ->make a set for each node
for(int i=1;i<=n;i++)
{
sets[i][1]=i;
top[i]=1; }
cout<<”\nThe algorithm starts ::\n\n”;
for(i=1;i<=noe;i++)
{
int p1=find_node(graph_edge[i][1]);
int p2=find_node(graph_edge[i][2]);
if(p1!=p2)
{
cout<<”The edge included in the tree is ::”
<<” < “<<graph_edge[i][1]<<” , “
<<graph_edge[i][2]<<” > “<<endl<<endl;
tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3];
tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3];
// Mix the two sets
for(int j=1;j<=top[p2];j++)
{
top[p1]++;
sets[p1][top[p1]]=sets[p2][j]; }
top[p2]=0; }
else
{
cout<<”Inclusion of the edge “
<<” < “<<graph_edge[i][1]<<” , “
<<graph_edge[i][2]<<” > “<<”forms a cycle so it is removed\n\n”; } } }
int kruskal::find_node(int n)
{
for(int i=1;i<=noe;i++)
{
for(int j=1;j<=top[i];j++)
{
if(n==sets[i][j])
return i; } }
return -1; }
int main()
{
clrscr();
kruskal obj;
obj.read_graph();
obj.sort_edges();
obj.algorithm();
return 0;
getch(); }
Output
*************************************************
This program implements the kruskal algorithm
*************************************************
Enter the no. of nodes in the undirected weighted graph ::3
Enter the weights for the following edges ::
< 1 , 2> ::3
< 1 , 3> ::1
< 2 , 3> ::4
The edges in the given graph are::
< 1 , 2 > ::3
< 1 , 3 > ::1
< 2 , 3 > ::4
After sorting the edges in the given graph are::
< 1, 3 > ::1
< 1, 2 > ::3
< 2, 3 > ::4
The algorithm starts ::
The edge included in the tree is :: < 1 , 3 >
The edge included in the tree is :: < 1 , 2 >
Inclusion of the edge < 2 , 3 > forms a cycle so it is removed
Result
Thus the Program to implement the graph and to obtain a minimum cost
spanning tree is implemented.
Ex. No 9 Implementation of dynamic polymorphism & RTTI
Aim
To write a C++ program to implement Hierarchy classes with Dynamic
polymorphism and Use Virtual concept along with RTTI
Algorithm
Step 1: Start the Process.
Step 2: Create a class SHAPE with data member and one member function as
Virtual.
Step 3: Create a derived class square,rectangle,polygon,circle and triangle with
SHAPE as base class.
Step 4: Create a Object in the main function.
Step 5: Invoke the appropriate function using object.
Step 6: Finally display the result.
Step 7: Stop the Process.
Program
#include<iostream.h>
#include<conio.h>
class shape
{
public:
int x,y;
public:
void getdata(int a,int b=0)
{
x=a;
y=b;
}
virtual void area()
{
cout<<"shape ";
}}
;
class square:public shape
{
public:
void area()
{
cout<<"area of square:"<<x*x<<endl;
}}
;
class rectangle:public shape
{
public:
void area()
{
cout<<"area of rectangle:"<<x*y<<endl;
}}
;
class circle:public shape
{
public:
void area()
{
cout<<"area of circle:"<<(3.14)*x*x<<endl;
}};
class triangle:public shape
{
public:
int area1;
void area()
{
cout<<"area of triangle:";
area1=(0.5)*x*y;
cout<<area1<<endl;
}}
;
class polygon:public triangle
{
public:
void area()
{
cout<<"area of polygon:"<<6*area1<<endl;
}}
;
void main()
{
clrscr();
shape *s;
triangle t;
square sq;
rectangle rt;
polygon p;
circle c;
s=&t;
s->getdata(3,2);
s->area();
s=&sq;
s->getdata(4);
s->area();
s=&c;
s->getdata(3);
s->area();
s=&rt;
s->getdata(2,4);
s->area();
s=&p;
s->area();
getch();
}
Output
area of triangle:3
area of square:16
area of circle:28.26
area of rectangle:8
area of polygon:23772
Result
Thus the program to implement Hierarchy classes with Dynamic
polymorphism and Use of Virtual concept along with RTTI is implemented.
Ex. No 10 File operations with randomly generated complex
Number
Aim
the network of education
To a C++ program to implement the randomly generates complex
numbers and write them two per line in a file along with an operator. 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.
Algorithm
Step 1: Start the Process.
Step 2: Create two files.
Step 3: One file is to read and another file to write.
Step 4: Do the operations in one file and write the result in another file.
Step 5: Display the result.
Step 6: Stop the Process.
Program
//Complex Class defined in a.cpp program
#include<iostream.h>
class complex
{f
loat real,imag;
public:
void get()
{
cin>>real>>imag;
}f
loat put1()
{
return real;
}f
loat put2()
{
return imag;
}}
;
//Program for writing a complex numbers in a file along with operators
#include "a.cpp"
#include<fstream.h>
#include<conio.h>
void main()
{clrscr();
fstream f("a.txt",ios::out);
complex c,c1;
char ch;
do
{
cout<<"enter the complex number1";
c1.get();
cout<<"enter the complex number2";
c.get();
char op;
cout<<"enter the operation to perform";
cin>>op;
f<<c1.put1()<<",i";
f<<c1.put2()<<"\t"<<op<<"\t";
f<<c.put1()<<",i";
f<<c.put2()<<endl;
cout<<"do u want to write one more";
cin>>ch;
}while(ch=='y');
f.close();
}
//Program for reading from file one line at a time and doing corresponding
operation and write the result in another file
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
clrscr();
fstream f1("a.txt",ios::in);
float r1,r2,r3,im1,im2,im3;
char *opertor,*c1,*c2,buffer[100];
while(!f1.eof())
{f
1.getline(buffer,100);
cout<<buffer<<endl;
for(int j=0;j<100;j++)
{if(buffer[j]=='+'||buffer[j]=='-'||buffer[j]=='*'||buffer[j]=='/')
{
char o=buffer[j];
opertor=&o;
c1=strtok(buffer,opertor);
cout<<"c1"<<c1<<endl;
c2=strtok(NULL,opertor);
cout<<"c2"<<c2<<endl;
}i
f(*opertor=='+')
{
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"1st"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img of c1:"<<r1<<r2<<im1<<im2<<endl;
r3=r1+r2;
im3=im1+im2;
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<"i"<<im3<<endl;
}
else
{
if(*opertor=='-')
{ char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"2nd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img of c2:"<<r1<<r2<<im1<<im2<<endl;
r3=r1-r2;
im3=im1-im2;
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<im3<<"i"<<endl;
f2.close();
}
else
{
if(*opertor=='*')
{
cout<<"entered";
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"3rd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img"<<r1<<r2<<im1<<im2;
r3=(r1*r2)-(im1*im2);
im3=(im1*r2)+(im2*r1);
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<","<<im3<<"i"<<endl;
f2.close();
}
else
{
if(*opertor=='/')
{
char *s=strtok(c1,",");
char *s1=strtok(NULL,",i");
cout<<s<<s1<<"3rd"<<endl;
r1=atof(s);
im1=atof(s1);
r2=atof(strtok(c2,","));
char *s2=strtok(NULL,",i");
im2=atof(s2);
cout<<"real,img"<<r1<<r2<<im1<<im2;
r3=((r1*r2)+(im1*im2))/((im1*im1)+(im2*im2));
im3=((im1*r2)-(im2*r1))/((im1*im1)+(im2*im2));
cout<<r3<<im3;
fstream f2("out.txt",ios::out|ios::app);
f2<<r3<<im3<<"i"<<endl;
f2.close();
}}
}}
}}}
Output:
Writing in a file:
enter the complex number11
1e
nter the complex number21
1e
nter the operation to perform+
do u want to write one more y
enter the complex number1 2
2e
nter the complex number2 1
1e
nter the operation to performdo
u want to write one more y
enter the complex number1 1
1e
nter the complex number2 1
1e
nter the operation to perform*
do u want to write one more y
enter the complex number12
1e
nter the complex number2 2
2e
nter the operation to perform/
do u want to write one more n
Text file a.txt:
1,i1 + 1,i1
2,i2 - 1,i1
1,i1 * 1,i1
2,i1 / 2,i2
Out.txt
2 i2
1 1i
0 2i
1.2 -0.4i
Result
Thus the program to implement the randomly generates complex
numbers and write them two per line in a file along with an operator. 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 is implemented.
For more lab manuals , question banks , syllabus . please log on to http://
www.yolearn.net
49
Anna University coe1.annauniv.edu
ReplyDeleteAnna University coe1.annauniv.edu