CS-235 E-Manual
CS-235 E-Manual
LAB MANUAL
PREPARED BY
DR. NAVEEN CHAUDHARY
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
DISCLAIMER
The e-Manual on “OBJECT ORIENTED
PROGRAMMING WITH C++” is prepared as per the
syllabus offered to students of Computer Science &
Engineering, CTAE, MPUAT, Udaipur, enrolled for
undergraduate (B. Tech) degree programme.
This document is a compilation of materials
provided in text books, and e-contents freely available
on online sources. The author does not claim for
originality of work. This is meant purely for academic
purpose for students of Computer Science and
Engineering, CTAE, MPUAT as a reference Material
for understanding of course. Multiplication and use of
this e-manual for commercial activity is strictly
prohibited.
However, author shall in no event be liable for
any errors, omissions or damages arising out of use this
information and specially disclaim any warranties or
merchantability or fitness for any particular use.
fghfh
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiments
Write a Program to design a class having static member function named showcount() which
1.
has the property of displaying the number of objects created of the class.
Write a Program using class to process Shopping List for a Departmental Store. The list
2. include details such as the Code No and Price of each item and perform the operations like
Adding, Deleting Items to the list and Printing the Total value of an Order.
Write a Program which creates & uses array of object of a class. (for eg. implementing the
3.
list of Managers of a Company having details such as Name, Age, etc..).
Write a Program to find Maximum out of Two Numbers using friend function.
4. Note: Here one number is a member of one class and the other number is member of some
other class.
Write a Program to swap private data members of classes named as class_1, class_2 using
5.
friend function.
Write a Program to design a class complex to represent complex numbers. The complex
class should use an external function (use it as a friend function) to add two complex number
6.
the function should return an object of type complex representing the sum of two complex
no.
7. Write a Program using copy constructor to copy data of an object to another object.
Write a Program to allocate memory dynamically for an objects of a given class using class’s
8.
constructor.
Write a Program to design a class to represent a matrix. The class should have the
9.
functionality to insert and retrieve the elements of the matrix.
Write a program to design a class representing complex no. and having the functionality of
10.
performing addition & multiplication of two complex numbers using operator overloading.
Write a Program to overload operators like *, <<, >> using friend function. The following
11.
overloaded operators should work for a class vector.
Write a program for developing a matrix class which can handle integer matrices of different
12. dimensions. Also overload the operator for addition, multiplication & comparison of
matrices.
13. Write a program to overload new/delete operators in a class.
Write a program in C++ to highlight the difference between overloaded assignment operator
14.
and copy constructor.
Write a Program illustrating how the constructors are implemented and the order in which
15. they are called when the classes are inherited. Use three classes named alpha, beta, gamma
such that alpha, beta are base class and gamma is derived class inheriting alpha & beta
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Write a Program to design a student class representing student roll no. and a test class
(derived class of student) representing the scores of the student in various subjects and sports
16.
class representing the score in sports. The sports and test class should be inherited by a result
class having the functionality to add the scores and display the final result for a student.
Write a program to maintain the records of person with details (Name and Age) and find the
17.
eldest among them. The program must use this pointer to return the result.
18. Write a Program to illustrate the use of pointers to objects which are related by inheritance.
22. Write a program showing data conversion between objects of different classes.
Write a program showing data conversion between objects of different classes and
23.
conversion routine should reside in destination class.
24. Write a program implementing basic operation of class ios i.e. setf,unsetf,precision etc.
Write a program to implement I/O operations on characters. I/O operations includes input a
25.
string, length of string, store it in a file, fetching the stored characters from it, etc.
Write a program to perform read/write binary I/O operation on a file (i.e. write the object of a
27.
structure/class to file).
Write a Program for reading and writing data to and from the file using command line
29.
arguments.
Write a program showing implementation of stack class having the functionality of push, pop
30.
operations.
31. Write program to implement a queue class with required operations/ functions.
32. Write a program to implement circular queue class with required operations/ functions.
Write a program implanting linked list as a class. Also Perform some required operations like
33.
inserting, deleting nodes & display the contents of entire linked list.
34. Write a program implementing stack & its operations using dynamic memory allocation.
Write a program implementing Queue stack & its operations using dynamic memory
35.
allocation.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Write a program to implement Binary search tree using class and traverse the tree using any
36. traversal scheme. In addition to it the class must have capability to copy the contents from
one tree to another and compare the contents of two binary trees.
37. Write a program to implement the exception handling with multiple catch statements.
38. Write a program to implement the exception handling with rethrowing in exception.
Write a program to implement the exception handling with the functionality of testing the
39.
throw restrictions.
40. Write a program implementing stack and its operations using template class.
Write a program implementing linked list & some required operations on it using class
41.
template.
Note – All program in this manual are executed in DevC++
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
1. If you want run turbo c++ on full screen simply click on button "Run Turbo C++"
2. "OR" If you not want full screen mode uncheck the "Full screen mode" check box and click on
button "Start Turbo C++"
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
• Save the program using F2 (OR file > Save), remember the extension should be “.cpp”.
In the below screenshot I have given the name as b1pg1.cpp (batch 1 program1)
• Compile the program using Alt + F9,or Compile > Compile (as shown in the below
screenshot).
• Press Ctrl + F9 to Run , or select Run > Run in menu bar to run the C++ program.
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Write your program. Note- only write “iostream”, not iostream.h, also add “using
namespace std;”
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 1
Aim - Write a Program to design a class having static member function named showcount() which has the
property of displaying the number of objects created of the class.
Code -
#include<iostream>
using namespace std;
class test
{
int code;
static int count;
public:
void setcode(void)
{
code = ++count;
}
void showcode(void)
{
cout<<"object number:"<<code<<"\n";
}
static void showcount(void)
{
cout<<"count:"<<count<<"\n";
}
};
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode();
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
return 0;
}
Sampled Output–
count:2
count:3
object number:1
object number:2
object number:3
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No - 2
Aim - Write a Program using class to process Shopping List for a Departmental Store. The list include
details such as the Code No and Price of each item and perform the operations like Adding, Deleting
Items to the list and Printing the Total value of a Order.
Code -
#include<iostream>
using namespace std;
const m=50;
class ITEMS
{
int itemCode[m];
float itemPrice[m];
int count;
public:
void CNT(void){count=0;}
void getitem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};
void ITEMS :: getitem(void)
{
cout<<"Enter item code";
cin>>itemCode[count];
cout<<"Enter Item cost";
cin>>itemPrice[count];
count++;
}
void ITEMS :: displaySum(void)
{
float sum=0;
for(int i=0;i<count;i++)
sum=sum+itemPrice[i];
cout<<"\n Total Value:"<<sum<<"\n";
}
void ITEMS :: remove(void)
{
int a;
cout<<"Enter Item Code";
cin>>a;
for(int i=0;i<count;i++)
if(itemCode[i] == a)
itemPrice[i]=0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
for(int i=0;i<count;i++)
{
cout<<"\n"<<itemCode[i];
cout<<" "<<itemPrice[i];
}
cout<<"\n";
}
int main()
{
ITEMS order;
order.CNT();
int x;
do
{
cout<<"\n You can do the following;"
<<"Enter appropriate number\n";
cout<<"\n1 : Add an Item";
cout<<"\n2 : Display Total Value";
cout<<"\n3 : Delete an Item";
cout<<"\n4 : Display all items";
cout<<"\n5 : Quit";
cout<<"\n\n What is your option?";
cin>>x;
switch(x)
{
case 1 : order.getitem();
break;
case 2 : order.displaySum();
break;
case 3 : order.remove();
break;
case 4 : order.displayItems();
break;
default : cout<<"Error in input";
}
}while(x!=5);
return 0;
}
Sampled Output -
You can do the following;Enter appropriate number
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
1 : Add an Item
2 : Display Total Value
3 : Delete an Item
4 : Display all items
5 : Quit
1 : Add an Item
2 : Display Total Value
3 : Delete an Item
4 : Display all items
5 : Quit
1 : Add an Item
2 : Display Total Value
3 : Delete an Item
4 : Display all items
5 : Quit
Code Price
222 34.5
444 56.8
1 : Add an Item
2 : Display Total Value
3 : Delete an Item
4 : Display all items
5 : Quit
Experiment No - 3
Aim - Write a Program which creates & uses array of object of a class. ( for eg. implementing the list of
Managers of a Company having details such as Name, Age, etc..).
Code -
#include<iostream>
using namespace std;
class employee
{
char name [30];
float age;
public:
void getdata(void);
void putdata(void);
};
void employee :: getdata(void)
{
cout<<"Enter Name";
cin>>name;
cout<<"Enter Age";
cin>>age;
}
void employee :: putdata(void)
{
cout<<"Name:"<<name<<"\n";
cout<<"Age: "<<age<<"\n";
}
const int size=3;
int main()
{
employee manager[size];
for(int i=0; i<size; i++)
{
cout<<"\n Details of manager"<<i+1<<"\n";
manager[i].getdata();
}
cout<<"\n";
for(i=0; i<size; i++)
{
cout<<"\n Manager"<<i+1<<"\n";
manager[i].putdata();
}
return 0;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled Output –
Details of manager1
Enter Name-aaa
Enter Age-56
Details of manager2
Enter Name-bbb
Enter Age-45
Details of manager3
Enter Name-ccc
Enter Age-50
Manager1
Name:aaa
Age: 56
Manager2
Name:bbb
Age: 45
Manager3
Name:ccc
Age: 50
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No – 4
Aim - Write a Program to find Maximum out of Two Numbers using friend function. Note: Here one
number is a member of one class and the other number is member of some other class.
Code –
#include<iostream>
using namespace std;
class ABC;
class XYZ
{
int x;
public:
void setvalue(int i)
{
x=i;
}
friend void max(XYZ, ABC);
};
class ABC
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(XYZ, ABC);
};
void max (XYZ m, ABC n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}
int main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc);
return 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled Output –
20
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 5
Aim - Write a Program to swap private data members of classes named as class_1, class_2 using friend
function.
Code –
#include<iostream>
using namespace std;
class class_2;
class class_1
{
int value1;
public:
void indata(int a)
{
value1=a;
}
void display(void)
{
cout<<value1<<"\n";
}
friend void exchange(class_1 &, class_2 &);
};
class class_2
{
int value2;
public:
void indata(int a)
{
value2=a;
}
void display(void)
{
cout<<value2<<"\n";
}
friend void exchange(class_1 &, class_2 &);
};
void exchange(class_1 &x, class_2 &y)
{
int temp = x.value1;
x.value1 = y.value2;
y.value2 = temp;
}
int main()
{
class_1 C1;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
class_2 C2;
C1.indata(100);
C2.indata(200);
cout<<"Values before exchange"<<"\n";
C1.display();
C2.display();
exchange(C1, C2);
cout<<"Values after exchange"<<"\n";
C1.display();
C2.display();
return 0;
}
Sampled Output –
Experiment No. – 6
Aim- Write a Program to design a class complex to represent complex numbers. The complex class
should use an external function (use it as a friend function) to add two complex number the function
should return an object of type complex representing the sum of two complex no.
Code –
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public:
void input(float real, float img)
{
x=real;
y=img;
}
friend complex sum(complex, complex);
void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return (c3);
}
void complex :: show(complex c)
{
cout<<c.x<<"+j"<<c.y<<"\n";
}
int main()
{
complex A,B,C;
A.input(3.1, 5.65);
B.input(2.75, 1.2);
C=sum(A,B);
cout<<"A=";
A.show(A);
cout<<"B=";
B.show(B);
cout<<"C=";
C.show(C);
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
return 0;
}
Sampled output –
A=3.1+j5.65
B=2.75+j1.2
C=5.85+j6.85
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. - 7
Aim - Write a Program using copy constructor to copy data of an object to another object.
Code –
#include<iostream>
using namespace std;
class code
{
int id;
public:
code(){}
code(int a)
{
id = a;
}
code(code & x)
{
id = x.id;
}
void display(void)
{
cout<<id;
}
};
int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
cout<<"\n id of A:";
A.display();
cout<<"\n id of B:";
B.display();
cout<<"\n id of C:";
C.display();
cout<<"\n id of D:";
D.display();
return 0;
}
Sampled output -
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
id of A:100
id of B:100
id of C:100
id of D:100
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 8
Aim - Write a Program to allocate memory dynamically for an objects of a given class using class’s
constructor.
Code -
#include<iostream>
#include<string.h>
using namespace std;
class String
{
char *name;
int length;
public:
String()
{
length = 0;
name = new char[length +1];
}
String (const char *s)
{
length = strlen(s);
name= new char[length + 1];
strcpy(name, s);
}
void display(void)
{
cout<<name<<"\n";
}
void join(String &a, String &b);
};
strcpy(name,a.name);
strcat(name, b.name);
};
int main()
{
return 0;
}
Sampled Output -
Joseph
Louis
Lagrange
Joseph Louis
Joseph Louis Lagrange
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 9
Aim - Write a Program to design a class to represent a matrix. The class should have the functionality to
insert and retrieve the elements of the matrix.
Code–
#include<iostream>
using namespace std;
class matrix
{
int **p;
int d1,d2;
public:
matrix(int x, int y);
void get_element(int i, int j, int value)
{
p[i][j]=value;
}
int & put_element(int i, int j)
{
return p[i][j];
}
};
matrix ::matrix(int x, int y)
{
d1 = x;
d2 = y;
p = new int *[d1];
for(int i = 0; i < d1; i++)
p[i] = new int[d2];
}
int main()
{
int m, n;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>value;
A.get_element(i,j,value);
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
}
cout<<"\n";
cout<<A.put_element(1,2);
return 0;
}
Sampled Output-
6
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. - 10
Aim - Write a program to design a class representing complex no. and having the functionality of
performing addition & multiplication of two complex numbers using operator overloading.
Code–
#include <iostream>
using namespace std;
class complex
{
private:
float real,
imag;
public:
complex( )
{
}
complex( float r, float i )
{
real = r;
imag = i;
}
void getdata( )
{
float r, i;
cout << endl << "Enter real and imaginary part ";
cin >> r >> i;
real = r;
imag = i;
}
void setdata( )
{
real = r;
imag = i;
}
void displaydata( )
{
cout << endl << "real = " << real;
cout<<endl<<Imaginary = "<<imag;
}
complex t;
t.real = real + c.real;
t.imag = imag + c.imag;
}
int main( )
{
complex c1,
c2 ( 1.2, -2.5 ), c3, c4;
c1.setdata( 2.0, 2.0 );
c3 = c1 + c2;
c3.displaydata( );
c4.getdata( );
complex c7;
c7 = c1 + c2 * c3;
c7.displaydata( );
return 0;
}
Sampled output -
c3 = c1 + c2
real = 2
Imaginary = 2
real = 1.2
Imaginary = -2.5
real = 3.2
Imaginary = -0.5
c6 = c4 * c5
real = 10
Imaginary = 0.6
real = 2.5
Imaginary = 3
real = 23.2
Imaginary = 31.5
c7 = c1 + c2 *c3
real = 2
Imaginary = 2
real = 1.2
Imaginary = -2.5
real = 3.2
Imaginary = -0.5
real = 4.59
Imaginary = -6.6
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 11
Aim - Write a Program to overload operators like *, <<, >> using friend function. The following
overloaded operators should work for a class vector.
Code -
#include<iostream>
using namespace std;
const size = 3;
class vector
{
int v[size];
public:
vector();
vector(int *x);
friend vector operator *(int a, vector b);
friend vector operator *(vector b, int a);
friend istream & operator >>(istream &, vector &);
friend ostream & operator <<(ostream &, vector &);
};
vector ::vector()
{
for(int i=0;i<size;i++)
v[i]=0;
}
int main()
{
vector m;
vector n = x;
cout<<"\n";
cout<<"m="<<m<<"\n";
vector p,q;
p = 2 * m;
q = n * 2;
cout<<"\n";
cout<<"p="<<p<<"\n";
cout<<"q="<<q<<"\n";
return 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled output -
m=(1,2,3)
p=(2,4,6)
q=(4,8,12)
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. - 12
Aim - Write a program for developing a matrix class which can handle integer matrices of different
dimensions. Also overload the operator for addition, multiplication & comparison of matrices.
Code–
#include <iostream>
#include <iomanip>
Using namespace std;
class matrix
{
int maxrow, maxcol;
int * ptr;
public:
matrix( int r, int c )
{
maxrow = r;
maxcol = c;
ptr = new int [r * c];
}
void getmat( )
{
int i,j, mat_off,temp;
cout << endl << "enter elements matrix:" << endl;
for( i = 0; i < maxrow; i++ )
{
for( j = 0; j < maxcol; j++ )
{
mat_off = i * maxcol + j;
cin >> ptr[ mat_off ];
}
}
}
void printmat( )
{
int i, j, mat_off;
for( i = 0; i < maxrow; i++ )
{
cout << endl;
for( j = 0; j < maxcol; j++ )
{
mat_off = i * maxcol + j;
cout << setw( 3 ) << ptr[ mat_off ];
}
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
int delmat( )
{
matrix q ( maxrow - 1, maxcol - 1 );
int sign = 1, sum = 0, i, j,k,count;
int newsize,newpos,pos,order;
order = maxrow;
if( order == 1 )
{
return ( ptr[ 0 ] );
}
for( i = 0; i < order; i++, sign *= -1 )
{
for( j = 1; j < order; j++ )
{
for( k = 0, count = 0; k< order; k++ )
{
if( k == i )
continue;
pos = j * order + k;
newpos = ( j - 1 ) * ( order - 1 ) + count;
q.ptr[ newpos ] = ptr[ pos ];
count++;
}
}
sum = sum + ptr[ i ] * sign * q.delmat( );
}
return ( sum );
}
} ;
int main( )
{
int rowa, cola, rowb, colb;
cout << endl << "Enter dimensions of matrix A ";
cin >> rowa >> cola;
matrix a ( rowa, cola );
a.getmat( );
cout << endl << "Enter dimensions of matrix B";
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled output -
Experiment No. – 13
Aim - Write a program to overload new/delete operators in a class.
Code -
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <new.h>
using namespace std;
void memwarning( )
{
cout << endl << "Free store has now gone empty";
exit( 1 );
}
class employee
{
private:
char name[ 20 ];
int age;
float sal;
public:
void *operator new(size_t bytes);
void operator delete( void * q );
void setdata( char * n, int a, float s );
void showdata( );
~employee( );
};
struct pool
{
employee obj;
int status;
};
int flag = 0;
struct pool * p = NULL;
int i;
if( flag == 0 )
{
p = ( pool * )malloc( sz * MAX );
if( p == NULL )
memwarning( );
for( i = 0; i < MAX; i++ )
p[ i ].status = FREE;
flag = 1;
p[ 0 ].status = OCCUPIED;
return &p[ 0 ].obj;
}
else
{
for( i = 0; i < MAX; i++ )
{
if( p[ i ].status = FREE )
{
p[ i ].status = OCCUPIED;
return &p[ i ].obj;
}
}
memwarning( );
}
}
void employee::showdata( )
{
cout << endl << name << "\t" << age << "\t" << sal;
}
employee::~employee( )
{
cout << endl << "reached destructor";
free( p );
}
int main( )
{
void memwarning( );
set_new_handler( memwarning );
employee * e1,*e2,*e3,*e4,*e5,*e6;
e1 = new employee;
e1->setdata( "ajay", 23, 4500.50 );
e2 = new employee;
e2->setdata( "amol", 25, 5500.50 );
e3 = new employee;
e3->setdata( "anil", 26, 3500.50 );
e4 = new employee;
e4->setdata( "anuj", 30, 6500.50 );
e5 = new employee;
e5->setdata( "atul", 23, 4200.50 );
e1->showdata( );
e2->showdata( );
e3->showdata( );
e4->showdata( );
e5->showdata( );
delete e4;
delete e5;
e4->showdata( );
e5->showdata( );
e4 = new employee;
e5 = new employee;
e6 = new employee;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled Output –
ajay 23 4500.50
amol 25 5500.50
anil 26 3500.50
anuj 30 6500.50
atul 23 4200.50
0 0.0
0 0.0
Done!
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 14
Aim - Write a program in C++ to highlight the difference between overloaded assignment operator and
copy constructor.
Code -
#include <iostream>
using namespace std;
class circle
{
private:
int radius;
float x, y;
public:
circle( )
{
}
circle( int rr, float xx, float yy )
{
radius = rr;
x = xx;
y = yy;
cout<< endl<<"simple constructor invoked";
}
circle operator =( circle & c )
{
cout << endl << "Assignment operator invoked";
radiius = c.radius;
x = c.x;
y = c.y;
return circle( radius, x, y );
}
circle( circle & c )
{
cout << endl << "copy constructor invoked";
radius = c.radius;
x = c.x;
y = c.y;
}
void showdata( )
{
cout << endl << "Radius = " << radius;
cout << endl << "X-Coordinate=" << x;
cout << endl << "Y-Coordinate=" << y;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
} ;
int main( )
{
circle c1 ( 10, 2.5, 2.5 );
circle c2,c4;
c4 = c2 = c1;
circle c3 = c1;
c1.showdata( );
c2.showdata( );
c3.showdata( );
c4.showdata( );
return 0;
}
Sampled output –
Experiment No- 15
Aim - Write a Program illustrating how the constructors are implemented and the order in which they are
called when the classes are inherited. Use three classes named alpha, beta, gamma such that alpha,beta are
base class and gamma is derived class inheriting alpha & beta
Code –
#include<iostream>
using namespace std;
class alpha
{
int x;
public:
alpha(int i)
{
x = i;
cout<<"alpha initialized\n";
}
void show_x(void)
{
cout<<"x="<<x<<"\n";
}
};
class beta
{
float y;
public:
beta(float j)
{
y=j;
cout<<"beta initialized\n";
}
void show_y(void)
{
cout<<"y= "<<y<<"\n";
}
};
m = c; n = d;
cout<<"gamma initialized\n";
}
void show_mn(void){
cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";
}
};
int main()
{
gamma g(5, 10.75, 20, 30);
g.show_x();
g.show_y();
g.show_mn();
return 0;
}
Sampled output –
beta initialized
alpha initialized
gamma initialized
x=5
y= 10.75
m=20
n=30
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No – 16
Aim - Write a Program to design a student class representing student roll no. and a test class (derived
class of student) representing the scores of the student in various subjects and sports class representing the
score in sports. The sports and test class should be inherited by a result class having the functionality to
add the scores and display the final result for a student.
Code -
#include<iostream.h>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number = a;
}
void put_number(void)
{
cout<<"Roll No:"<<roll_number<<"\n";
}
};
public:
void get_marks(float x, float y)
{
part1 = x;
part2 = y;
}
void put_marks(void)
{
cout<<"Marks obtained"<<"\n"
<<"part1 ="<<part1<<"\n"
<<"part2 ="<<part2<<"\n";
}
};
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
class sports
{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}
void put_score(void)
{
cout<<"Sports wt:"<<score<<"\n\n";
}
};
put_number();
put_marks();
put_score();
cout<<"Total Score:"<<total<<"\n";
}
int main()
{
result student_1;
student_1.get_number (1234);
student_1.get_marks (27.5, 33.0);
student_1.get_score (6.0);
student_1.display ();
return 0;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled Output –
Roll No:1234
Marks obtained
part1 =27.5
part2 =33
Sports wt:6
Total Score:66.5
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 17
Aim - Write a program to maintain the records of person with details (Name and Age) and find the eldest
among them. The program must use this pointer to return the result.
Code –
#include<iostream>
#include<string.h>
Using namespace std;
class person
{
char name[20];
float age;
public:
person(const char *s, float a)
{
strcpy(name, s);
age = a;
}
void display(void)
{
cout<<"Name:"<<name<<"\n"
<<"Age: "<<age<<"\n";
}
};
int main()
{
person p1("John", 37.50),p2("Ahmed",29.0),p3("Hebber", 40.5);
p = p1.greater (p2);
cout<<"Elder Person is:\n";
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
p.display();
return 0;
}
Sampled output -
Experiment No. – 18
Aim - Write a Program to illustrate the use of pointers to objects which are related by inheritance.
Code –
#include<iostream>
using namespace std;
class BC
{
public:
int b;
void show()
{
cout<<"b="<<b<<"\n";
}
};
class DC : public BC
{
public:
int d;
void show()
{
cout<<"b="<<b<<"\n"
<<"d="<<d<<"\n";
}
};
int main()
{
BC *bptr;
BC base;
bptr = &base;
bptr->b = 100;
cout<<"bptr points to base object\n";
bptr->show ();
DC derived;
bptr = &derived;
bptr->b = 200;
DC *dptr;
dptr = &derived;
dptr->d = 300;
return 0;
}
Sampled output -
Experiment No. – 19
Code-
#include<iostream>
using namespace std;
class Base
{
public:
void display()
{
cout<<"\n Display Base";
}
void show()
{
cout<<"\n Show Derived";
}
};
int main()
{
Base B;
Derived D;
Base *bptr;
return 0;
}
Sampled Output –
Display Base
Show Base
Display Base
Show Derived
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 20
Aim - Write a program to design a class representing the information regarding digital library (books,
tape: book & tape should be separate classes having the base class as media). The class should have the
functionality for adding new item, issuing, deposit etc. the program should use the runtime
polymorphism.
Code -
#include<iostream>
#include<string.h>
using namespace std;
class media
{
protected:
char title[50];
float price;
public:
media(char *s, float a)
{
strcpy(title, s);
price = a;
}
virtual void display(){}
};
class book : public media
{
int pages;
public:
book(char *s, float a, int p) : media(s,a)
{
pages = p;
}
void display();
};
int main()
{
char * title = new char[30];
float price, time;
int pages;
media* list[2];
list[0] = &book1;
list[1] = &tape1;
cout<<"\n Media Details";
cout<<"\n..............Book.....";
list[0]->display ();
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
cout<<"\n..............Tape.....";
list[1]->display ();
return 0;
}
Sample output –
Title:aaa
Price:34.5
Pages:56
Price:67.8
Play Times(mins):45.5
Media Details
..............Book.....
Title:aaa
Pages:56
Price:34.5
..............Tape.....
Title:yyy
Play Time:45.5mins
Price:67.8
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 21
Aim - write a program to show conversion from string to int and vice-versa.
Code –
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
class string
{
private:
char str[ 20 ];
public:
string( )
{
str[ 0 ] = '\0';
}
string( char * s )
{
strcpy( str, s );
}
string( int a )
{
itoa( a, str, 10 );
}
operator int( )
{
int i = 0,
l,
ss = 0,
k = 1;
l = strlen( str ) - 1;
while( l >= 0 )
{
ss = ss + ( str[ l ] - 48 ) * k;
l--;
k *= 10;
}
return ( ss );
}
void displaydata( )
{
cout << str;
}
} ;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
int main( )
{
string s1 = 123;
cout << endl << "s1=";
s1.displaydata( );
s1 = 150;
cout << endl << "s1=";
s1.displaydata( );
string s2 ( "123" );
int i = int( s2 );
cout << endl << "i=" << i;
string s3 ( "456" );
i = s3;
cout << endl << "i=" << i;
return 0;
}
Sampled Output -
s1=123
s1=150
i=123
i=456
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No – 22
Aim - Write a program showing data conversion between objects of different classes.
Code -
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
class date
{
private:
char dt[ 9 ];
public:
date( )
{
dt[ 0 ] = '\0';
}
date( char * s )
{
strcpy( dt, s );
}
void displaydata( )
{
cout << dt;
}
};
class dmy
{
private:
dmy( )
{
day = mth = yr = 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
operator date( )
{
char temp[ 3 ], str[ 9 ];
itoa( day, str, 10 );
strcat( str, "/" );
itoa( mth, temp, 10 );
strcat( str, temp );
strcat( str, "/" );
itoa( yr, temp, 10 );
strcat( str, temp );
return ( date( str ) );
}
void displaydata( )
{
cout << day << "\t" << mth << "\t" << yr;
}
};
int main( )
{
date d1;
dmy d2 ( 17, 11, 94 );
d1 = d2;
cout<<endl<<"d1=";
d1.displaydata( );
Sampled output -
d1=17/11/94
d2=17 11 94
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 23
Aim - Write a program showing data conversion between objects of different classes and conversion
routine should reside in destination class.
Code –
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class dmy
{
int day,mth, yr;
public:
dmy( )
{
day = mth, yr = 0;
}
int getday( )
{
return ( day );
}
int getmth( )
{
return ( mth );
}
int getyr( )
{
return ( yr );
}
void displaydata( )
{
cout << day << "\t" << mth << "\t" << yr;
}
} ;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
class date
{
private:
char dt[ 9 ];
public:
date( )
{
dt[ 0 ] = '\0';
}
date( char * s )
{
strcpy( dt, s );
}
void displaydata( )
{
cout << dt;
}
date( dmy t )
{
int d = t.getday( );
int m = t.getmth( );
int y = t.getyr( );
char temp[ 3 ];
itoa( d, dt, 10 );
strcat( dt, "/" );
itoa( m, temp, 10 );
strcat( dt, temp );
strcat( dt, "/" );
itoa( y, temp, 10 );
strcat( dt, temp );
}
} ;
int main( )
{
date d1;
dmy d2 ( 17, 11, 94 );
d1 = d2;
cout << endl << "d1=";
d1.displaydata( );
cout << endl << "d2=";
d2.displaydata( );
return 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled output –
d1=17/11/94
d2=17 11 94
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No - 24
Aim - Write a program implementing basic operation of class ios i.e. setf,unsetf,precision etc.
Code –
#include <iostream>
using namespace std;
int main( )
{
int i = 52;
float a = 425.0;
float b = 123.500328;
cout.setf( ios::unitbuf );
cout.setf( ios::showpos );
cout.setf( ios::showbase );
cout.setf( ios::uppercase );
cout.setf( ios::hex, ios::basefield );
cout.fill( '0' );
cout << "Fill character " << cout.fill( ) << endl;
cout.width( 10 );
cout << i << endl;
cout.width( 10 );
cout << str << endl;
cout.width( 40 );
cout.setf( ios::left, ios::adjustfield );
cout << str << endl;
cout.precision( 6 );
cout << "Precision" << cout.precision( );
cout.setf( ios::showpoint );
cout.unsetf( ios::showpos );
cout << endl << a;
cout.unsetf( ios::showpoint );
cout << endl << a;
b = 5.375;
cout.precision( 14 );
cout.unsetf( ios::showpoint );
cout.unsetf( ios::unitbuf );
return 0;
}
Sampled Output -
+52
0X34
064
+52
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Fill character 0
0000000+52
+520000000
+000000052
Experiment No. – 25
Aim - Write a program to implement I/O operations on characters. I/O operations includes input a string,
length of string, store it in a file, fetching the stored characters from it, etc.
Code–
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char string[80];
cout<<"Enter a String \n";
cin>>string;
int len = strlen(string);
fstream file;
file.open("TEXT", ios::in | ios::out);
for(int i=0;i<len;i++)
file.put(string[i]);
file.seekg(0);
char ch;
while(file)
{
file.get(ch);
cout<<ch;
}
return 0;
}
Enter a String
qwerty
qwerty
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 26
Code–
#include<fstream>
#include<iostream>
Using namespace std;
Int main( )
{
char source[ 67 ], target[ 67 ]; char ch;
while(!infile.eof())
{
infile.get( ch );
outfile.put( ch );
}
Experiment No. – 27
Aim - Write a program to perform read/write binary I/O operation on a file (i.e. write the object of a
structure/class to file).
Code -
#include <fstream>
#include <iostream>
Using namespace std;
int main( )
{
struct employee
{
char name[ 20 ];
int age;
float basic;
float gross;
};
employee e;
char ch = 'Y';
ofstream outfile;
outfile.open( "EMPLOYEE.DAT", ios::out | ios::binary );
while( ch == 'Y' )
{
cout << endl << "Enter a record - name, age, basic salary, gross salary -";
cin >> e.name >> e.age >> e.basic >> e.gross;
outfile.close( );
ifstream infile;
infile.open( "EMPLOYEE.DAT", ios::in | ios::binary );
cout << endl << "Name" << "\t" << "Age" << "\t" << "Basic" << "\t" << "Gross";
while( infile.read( ( char * )&e, sizeof( e ) ) )
{
cout << endl << e.name << "\t" << e.age << "\t" << e.basic << "\t" << e.gross;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
}
return 0;
}
Sampled output -
Experiment No. – 28
Code–
#include <windows.h>
#include <fstream>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
using namespace std;
void gotoxy(short x, short y)//gotoxy is turbo c specific function so we have to write own definition
{
COORD pos={x,y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
class group
{
private:
struct person
{
char flag;
char empcode[ 5 ];
char name[ 40 ];
int age;
float sal;
} p;
fstream file;
public:
group( );
void addrec( );
void listrec( );
void modirec( );
void delrec( );
void recallrec( );
void packrec( );
void exit( );
};
int main( )
{
char choice;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
group g;
do
{
//clrscr();
system("cls");
gotoxy( 30, 10 );
cout << "1. Add records";
gotoxy( 30, 11 );
cout << "2. List records";
gotoxy( 30, 12 );
cout << "3. Modify records";
gotoxy( 30, 13 );
cout << "4. Delete records";
gotoxy( 30, 14 );
cout << "5. Recall records";
gotoxy( 30, 15 );
cout << "6. Pack records";
gotoxy( 30, 16 );
cout << "0. Exit";
gotoxy( 30, 18 );
cout << "Your Choice ? ";
cin >> choice;
//clrscr();
system("cls");
switch( choice )
{
case '1': g.addrec( ); break;
case '2': g.listrec( );break;
case '3': g.modirec( );break;
case '4': g.delrec( ); break;
case '5': g.recallrec( );break;
case '6': g.packrec( );break;
case '0': g.exit( ); break;
}
} while( choice !=’0’ );
return 0;
}
group::group( )
{
file.open( "emp.dat", ios::out|ios::binary|ios::in); // first out then binary then in, otherwise file won’t
open
if( !file )
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
{
cout << endl << "Unable to open file";
exit( );
}
}
void group::addrec( )
{
char ch;
file.seekp( 0L, ios::end );
do
{
cout << endl << "Enter emp code, name, age & salary" << endl;
cin >> p.empcode >> p.name >> p.age >> p.sal;
p.flag =' ';
file.write( ( char * )&p, sizeof( p ) );
cout << "Add another record? (Y/N)";
cin >> ch;
} while( ch == 'Y' || ch == 'Y' );
void group::listrec( )
{
int j = 0,a;
file.seekg( 0L, ios::beg );
file.clear( );
cout << endl << "Press any key......";
getch( );
}
}
void group::modirec( )
{
char code[ 5 ];
int count = 0;
long int pos;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
count++;
}
cout << endl << "No employee in file with code = " << code;
cout << endl << "Press any key .....";
getch( );
file.clear( );
}
void group::delrec( )
{
char code[ 5 ];
long int pos;
int count = 0;
cout << "Enter employee code : ";
cin >> code;
file.seekg( 0L, ios::beg );
cout << endl << "No employee in file with code = " << code;
cout<<endl<<"Press any key ....";
getch( );
file.clear( );
}
void group::recallrec()
{
char code[ 5 ];
long int pos;
int count = 0;
cout << "Enter employee code: ";
cin >> code;
file.seekg( 0L, ios::beg );
while( file.read( ( char * )&p, sizeof( p ) ) )
{
if( strcmp( p.empcode, code ) == 0 )
{
p.flag = ' ';
pos = count * sizeof( p );
file.seekp( pos, ios::beg );
file.write( ( char * )&p, sizeof( p ) );
return;
}
count++;
}
cout << endl << "No employee in file with code = " << code;
cout << endl << "Press any key ....";
file.clear( );
}
void group::packrec( )
{
ofstream outfile;
outfile.open( "TEMP", ios::out );
file.seekg( 0, ios::beg );
while( file.read( ( char * )&p, sizeof( p ) ) )
{
if( p.flag != '*' )
outfile.write((char *)&p,sizeof(p));
}
outfile.close( ); file.close( );
remove( "EMP.dat" );
rename( "TEMP", "TEMP.dat" );
file.open( "EMP.dat", ios::binary | ios::in | ios::out /*| ios::nocreate*/ );
}
void group::exit( )
{
file.close( );
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sampled Output –
1. Add records
2. List records
3. Modify records
4. Delete records
5. Recall records
6. Pack records
0. Exit
Your Choice ? 1
Experiment No- 29
Aim - Write a Program for reading and writing data to and from the file using command line arguments.
Code -
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
if(argc!=3)
{
cout<<"argc="<<argc<<"\n";
cout<<"Error in arguments\n";
exit(1);
}
fout1.open(argv[1]);
if(fout1.fail())
{
cout<<"Could not open the file:"
<<argv[1]<<"\n";
exit(1);
}
fout2.open(argv[2]);
if(fout2.fail())
{
cout<<"Could not open the file:"
<<argv[2]<<"\n";
exit(1);
}
fout1.close();
fout2.close();
ifstream fin;
char ch;
return 0;
}
Sampled Output –
Contents of text1.txt,
11 33 55 77 99
Contents of copy.txt
22 44 66 88
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 30
Aim - Write a program showing implementation of stack class having the functionality of push, pop
operations.
Code -
#include <iostream>
#define MAX 10
using namespace std;
class stack
{
private:
int arr[ MAX ], top;
public:
stack( )
{
top = -1;
}
void push( int item )
{
if( top == MAX - 1 )
{
cout << endl << "Stack is full";
return;
}
top++;
arr[ top ] = item;
}
int pop( )
{
if( top == -1 )
{
cout << endl << "Stack is empty";
return NULL;
}
int data = arr[ top ];
top--;
return data;
}
} ;
int main( )
{
stack s;
s.push( 11 );
s.push( 12 );
s.push( 13 );
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
s.push( 14 );
s.push( 15 );
s.push( 16 );
s.push( 17 );
s.push( 18 );
s.push( 19 );
s.push( 20 );
s.push( 21 );
int i = s.pop( ); cout << endl << "Item popped=" << i;
i = s.pop( ); cout << endl << "Item popped=" << i;
i = s.pop( ); cout << endl << "Item popped=" << i;
i = s.pop( ); cout << endl << "Item popped=" << i;
return 0;
}
Sampled output-
Stack is full
Item popped=20
Item popped=19
Item popped=18
Item popped=17
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 31
Aim - Write program to implement a queue class with required operations/ functions.
Code -
#include <iostream>
#define MAX 10
using namespace std;
class queue
{
private:
int arr[ MAX ];
int front,
rear;
public:
queue( )
{
front = -1;
rear = -1;
}
int delq( )
{
int data;
if( front == -1 )
{
cout << endl << "Queue is empty";
return NULL;
}
return data;
}
} ;
int main( )
{
queue a;
a.addq( 11 );
a.addq( 12 );
a.addq( 13 );
a.addq( 14 );
a.addq( 15 );
a.addq( 16 );
a.addq( 17 );
a.addq( 18 );
a.addq( 19 );
a.addq( 20 );
a.addq( 21 );
int i = a.delq( );
cout << endl << "Item deleted=" << i;
i = a.delq( );
cout << endl << "Item deleted=" << i;
i = a.delq( );
cout << endl << "Item deleted=" << i;
return 0;
}
Sampled output –
Queue is full
Item deleted=11
Item deleted=12
Item deleted=13
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 32
Aim - Write a program to implement circular queue class with required operations/ functions.
Code –
#include <iostream>
#define MAX 10
using namespace std;
class queue
{
private:
int arr[ MAX ];
int front,
rear;
public:
queue( )
{
front = -1;
rear = -1;
}
if( front == -1 )
front = 0;
}
int delq( )
{
int data;
if( front == -1 )
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
{
cout << endl << "Queue is empty";
return NULL;
}
else
{
data = arr[ front ];
if( front == rear )
{
front = -1;
rear = -1;
}
else
{
if( front == MAX - 1 )
front = 0;
else
front = front + 1;
}
return data;
}
}
} ;
int main( )
{
queue a;
a.addq( 11 );
a.addq( 12 );
a.addq( 13 );
a.addq( 14 );
a.addq( 15 );
a.addq( 16 );
a.addq( 17 );
a.addq( 18 );
a.addq( 19 );
a.addq( 20 );
a.addq( 21 );
int i = a.delq( );
cout << endl << "Item deleted=" << i;
i = a.delq( );
cout << endl << "Item deleted=" << i;
i = a.delq( );
cout << endl << "Item deleted=" << i;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
return 0;
}
Sampled output –
Queue is full
Item deleted=11
Item deleted=12
Item deleted=13
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 33
Aim - Write a program implanting linked list as a class. Also perform some required operations like
inserting, deleting nodes & display the contents of entire linked list.
Code -
#include <iostream>
using namespace std;
class linklist
{
struct node
{
int data;
node * link;
} * p;
public:
linklist( );
void append( int num );
void addatbeg( int num );
void addafter( int c, int num );
void del( int num );
void display( );
int count( );
~linklist( );
} ;
linklist::linklist( )
{
p = NULL;
}
t = new node;
t->data = num;
t->link = NULL;
q->link = t;
}
}
while( q != NULL )
{
if( q->data == num )
{
r->link = q->link;
delete q;
return;
}
r = q;
q = q->link;
}
cout << endl << "Element" << num << "not found";
}
void linklist::display( )
{
node * q;
cout << endl;
for( q = p; q->link != NULL; q = q->link )
{
cout << endl << q->data;
}
}
int linklist::count( )
{
node * q;
int c = 0;
for( q = p; q != NULL; q = q->link )
c++;
return ( c );
}
linklist::~linklist( )
{
node * q;
if( p == NULL )
return;
while( p != NULL )
{
q = p->link;
delete p;
p = q;
}
}
int main( )
{
linklist ll;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
cout << endl << "No. of elements in linked list= " << ll.count( );
ll.append( 11 );
ll.append( 22 );
ll.append( 33 );
ll.append( 44 );
ll.append( 55 );
ll.addatbeg( 100 );
ll.addatbeg( 200 );
ll.addatbeg( 300 );
ll.addafter( 3, 333 );
ll.addafter( 6, 444 );
ll.display( );
cout << endl << "No. of element in linked list =" << ll.count( );
ll.del( 300 );
ll.del( 66 );
ll.del( 0 );
ll.display( );
cout << endl << "No. of element in linked list =" << ll.count( );
return 0;
}
Sampled Output -
200
100
11
333
22
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
33
444
44
No. of element in linked list =9
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Code –
#include <iostream>
using namespace std;
struct node
{
int data;
node * link;
} ;
class stack
{
private:
node * top;
public:
stack( )
{
top = NULL;
}
int pop( )
{
if( top == NULL )
{
cout << endl << "Stack is empty";
return NULL;
}
node * temp;
int item;
temp = top;
item = temp->data;
top = top->link;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
delete temp;
return item;
}
~stack( )
{
if( top == NULL )
return;
node * temp;
while( top != NULL )
{
temp = top;
top = top->link;
delete temp;
}
}
} ;
int main( )
{
stack s;
s.push( 11 );
s.push( 12 );
s.push( 13 );
s.push( 14 );
s.push( 15 );
s.push( 16 );
int i = s.pop( );
cout << endl << "Item popped=" << i;
i = s.pop( );
cout << endl << "Item popped=" << i;
i = s.pop( );
cout << endl << "Item popped=" << i;
return 0;
}
Sample Output-
Item popped=16
Item popped=15
Item popped=14
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 35
Aim - Write a program implementing Queue stack & its operations using dynamic memory allocation.
Code -
#include <iostream>
using namespace std;
struct node
{
int data;
node * link;
} ;
class queue
{
private:
node * front,
* rear;
public:
queue( )
{
front = rear = NULL;
}
int delq( )
{
if( front == NULL )
{
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
~queue( )
{
if( front == NULL )
return;
node * temp;
while( front != NULL )
{
temp = front;
front = front->link;
delete temp;
}
}
} ;
int main( )
{
queue a;
a.addq( 11 );
a.addq( 12 );
a.addq( 13 );
a.addq( 14 );
a.addq( 15 );
a.addq( 16 );
a.addq( 17 );
int i = a.delq( );
cout << endl << "Item extracted=" << i;
i = a.delq( );
cout << endl << "Item extracted=" << i;
i = a.delq( );
cout << endl << "Item extracted=" << i;
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
return 0;
}
Sampled output –
Item extracted=11
Item extracted=12
Item extracted=13
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 36
Aim - Write a program to implement Binary search tree using class and traverse the tree using any
traversal scheme. In addition to it the class must have capability to copy the contents from one tree to
another and compare the contents of two binary trees.
Code –
#include <iostream>
#define TRUE 1
#define FALSE 0
using namespace std;
class tree
{
private:
struct node
{
node * l;
int data;
node * r;
} * p;
public:
tree( );
void search( int n, int & found, node *& parent );
void insert( int n );
void traverse( );
void in( node * q );
void pre( node * q );
void post( node * q );
int operator ==( tree t );
int compare( node * pp, node * qq );
void operator =( tree t );
node * copy( node * q );
} ;
tree::tree( )
{
p = NULL;
}
while( q != NULL )
{
if( q->data == n )
{
found = TRUE;
return;
}
if( q->data > n )
{
parent = q;
q = q->l;
}
else
{
parent = q;
q = q->r;
}
}
}
void tree::traverse( )
{
int choice;
cout << endl << "q.Inorder" << endl << "2. Preorder" << endl
<< "3. Postorder" << endl << "4. Your choice ";
cin >> choice;
switch( choice )
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
{
case 1:
in( p );
break;
case 2:
pre( p );
break;
case 3:
post( p );
break;
}
}
{
if( q != NULL )
{
t = new node;
t->data = q->data;
t->l = copy( q->l );
t->r = copy( q->r );
return ( t );
}
else
return ( NULL );
}
int main( )
{
tree tt, ss;
int i, num;
cout << endl << "Enter the data for the node to be inserted";
cin >> num;
tt.insert( num );
}
tt.traverse( );
ss = tt;
ss.traverse( );
if( ss == tt )
cout << endl << "Trees are equal";
else
cout << endl << "Trees are not equal";
return 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 37
Aim - Write a program to implement the exception handling with multiple catch statements.
Code –
#include<iostream>
using namespace std;
void test(int x)
{
try
{
if(x==1)
throw x;
else
if(x==0)
throw 'x';
else
if(x==-1)
throw 1.0;
cout<<"End of try-black\n";
}
catch(char c)
{
cout<<"Caught a Character\n";
}
catch(int c)
{
cout<<"Caught an Integer\n";
}
catch(double c)
{
cout<<"Caught a Double\n";
}
int main()
{
cout<<"Testing Multiple Catches\n";
cout<<"x==1\n";
test(1);
cout<<"x==0\n";
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
test(0);
cout<<"x==2\n";
test(2);
return 0;
}
Sample Output –
Testing Multiple Catches
x==1
Caught an Integer
End of try-catch system
x==0
Caught a Character
End of try-catch system
x==2
End of try-black
End of try-catch system
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No – 38
Aim - Write a program to implement the exception handling with rethrowing in exception.
Code -
#include<iostream>
using namespace std;
catch(double)
{
cout<<"Caught double inside function\n";
throw;
}
cout<<"End of Function\n";
}
int main()
{
cout<<"Inside Main\n";
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{
cout<<"Caught double inside main\n";
}
cout<<"End of Main\n";
return 0;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Sample Output –
Inside Main
Inside Function
Division =5.25
End of Function
Inside Function
Caught double inside function
Caught double inside main
End of Main
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 39
Aim - Write a program to implement the exception handling with the functionality of testing the throw
restrictions.
Code -
#include<iostream>
using namespace std;
int main()
{
try
{
cout<<"Testing Throw Restrictions\n";
cout<<"x == 0\n";
test(0);
cout<<"x == 1\n";
test(1);
cout<<"x == -1\n";
test(-1);
cout<<"x == 2\n";
test(2);
}
catch(char c)
{
cout<<"Caught a Character\n";
}
catch(int m)
{
cout<<"Caught an Integer\n";
}
catch(double d)
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
{
cout<<"Caught a Double\n";
}
Sampled Output –
Experiment No. – 40
Aim - Write a program implementing stack and its operations using template class.
Code –
#include <iostream>
using namespace std;
public:
stack( )
{
top = -1;
}
void push( T data )
{
if( top == MAX - 1 )
cout << endl << "Stack is full";
else
{
top++;
stk[ top ] = data;
}
}
T pop( )
{
if( top == -1 )
{
cout << endl << "Stack is empty";
return NULL;
}
else
{
T data = stk[ top ];
top--;
return data;
}
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
}
} ;
class complex
{
private:
float real, imag;
public:
complex( float r = 0.0, float i = 0.0 )
{
real = r;
imag = i;
}
friend ostream & operator <<( ostream & o, complex & c );
} ;
int main( )
{
stack< int > s1;
s1.push( 10 );
s1.push( 20 );
s1.push( 30 );
s2.push( 3.14 );
s2.push( 6.28 );
s2.push( 8.98 );
s3.push( c1 );
s3.push( c2 );
s3.push( c3 );
Sampled Output –
30
20
10
8.98
6.28
3.14
-1.5, -0.6
3.5, 4.5
1.5, 2.5
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
Experiment No. – 41
Aim - Write a program implementing linked list & some required operations on it using class template.
Code -
#include <string.h>
#include <iostream>
using namespace std;
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;
}
} ;
ostream operator <<( ostream & s, emp & e )
{
cout << e.name << "\t" << e.age << "\t" << e.sal;
return s;
}
public:
linklist( );
~linklist( );
void append( T );
void addatbeg( T );
void addafter( int, T );
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
q->link = p;
p = q;
}
t = new node;
t->data = num;
t->link = q->link;
q->link = t;
}
}
cout << endl << "Element" << n << "not found";
}
int main( )
{
linklist< 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( 4, 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 );
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
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( );
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( );
return 0;
}
Sampled output -
No. of elements in linked list= 0
200
100
11
333
444
22
33
44
No. of element in linked list =8
Element 66 not found
Department of Computer Science & Engineering, CTAE, MPUAT, Udaipur CPP Lab
200
100
11
444
22
33
44
No. of element in linked list =7
Sanjay 23 1100.00
Rahul 33 3500.00
Sanket 25 2500.00
Sandeep262600.00
No. of element in linked list =4
Sandeep262600.00
Sanjay 23 1100.00
Rahul 33 3500.00
Sanket 25 2500.00
Sandeep262600.00
Sandeep262600.00
Sanjay 23 1100.00
Rahul 33 3500.00
Sanjay 23 1100.00
Sanket 25 2500.00
Sandeep262600.00