Você está na página 1de 39

Siddaganga Institute of Technology, SIT Tumkur-03

Department of Computer Science and Engineering


2015-2016
Object Oriented Programming with C++ Lab Manual

Table of Contents

Sl.No Topic Name Page


No.
1. Circle Program to implement using friend functions and constructors 2
2. Time Program to add 2 time duration using constructors and
3
Other methods
3. Rain Gauge program to demonstrate use of array of objects and
5
friend functions.
4. Queue operations using exception handling and constructors 7
5. Conversion from Infix to Postfix Expression program using type
10
conversions
6. Addition of two distance objects using function overloading and
12
returning objects
7. Bank Transaction operation using constructors and array of objects 14
8. Addition of two fractions and checking their equality using operator
15
overloading
9. Addition of two matrices using operator overloading 18
10. Multiplication of two matrices using operator overloading 20
11. Calculate the average age of student semester wise using inheritance
23
concept.
12. Calculating the account transactions of a customer using inheritance
26
concept.
13. File operations to store details of items in inventory 29
14. String operations using string library functions 31
15. Template functions to demonstrate Insertion Sort and Selection Sort 33
16. Stack operations using templates and exception handling. 35

Dept. of CSE, SIT Tumkur Page 1


Object Oriented Programming with C++ Lab Manual

1. Write a C++ program to create a class to represent entities of type Circle,


specified by its attributes radius and coordinates of its centre. Include
appropriate Constructors and display methods. Also write a friend function that
determines whether two circles intersect one another or they touch each other or
they are disjoint.

#include <iostream>
#include <cmath>
using namespace std;
class CircleType
{
private:
int iRadius;
int iXc, iYc;
public:
CircleType();
CircleType(int, int, int);
void fnSetRadius(int);
void fnShowDetails();
friend void fnCheckCircles(CircleType, CircleType);
};
CircleType :: CircleType() //point circle
{
iRadius = iXc = iYc = 0;
}
CircleType :: CircleType(int r, int x, int y)
{
iRadius = r;
iXc = x;
iYc = y;
}
void CircleType :: fnShowDetails()
{
cout << "\nRadius : " << iRadius;
cout << "\nXcenter : " << iXc;
cout << "\nYcenter : " << iYc;
}
void fnCheckCircles(CircleType c1, CircleType c2)
{
double dDist;
dDist = sqrt(((c2.iXc - c1.iXc)*(c2.iXc - c1.iXc) + (c2.iYc - c1.iYc)*(c2.iY
if (dDist == c1.iRadius + c2.iRadius)
cout << "\nTwo circles touch each other" << endl;
else if (dDist < c1.iRadius + c2.iRadius)
cout << "\nTwo circles intersect one another" << endl;
Dept. of CSE, SIT Tumkur Page 2
Object Oriented Programming with C++ Lab Manual

else
cout << "\nTwo circles are disjoint" << endl;
}
int main(void)
{
CircleType c1(5,10,0), c2(5,0,0), c3(5,12,0);
fnCheckCircles(c1,c2); //touch
fnCheckCircles(c1,c3); //intersect
fnCheckCircles(c2,c3); //disjoint

return 0;
}

2. Write a C++ program that stores the time duration in hh:mm:ss format in a
class called Duaration having the members hh, mm and ss.
Include the following constructors:
a) zero parameter constructor that sets all data members to zero.
b) three parameter constructor that sets values of hh, mm and ss respectively if
the values are valid.
c)Implement the following methods
1. getDuration method that reads and validates a time duration
2. showDuration method that displays the time duration
3. addDuration method that adds two durations
Illustrate the addition of two time durations.

#include <iostream>
using namespace std;

class DurationType
{
int iHr, iMn, iSc;
public:
DurationType();
DurationType(int, int, int);
void fnSetDuration();
void fnShowDuration();
DurationType fnAddDuration(DurationType);
};

DurationType :: DurationType()
{
iHr = iMn = iSc = 0;
}

DurationType :: DurationType(int h, int m, int s)


{
iHr = h;

Dept. of CSE, SIT Tumkur Page 3


Object Oriented Programming with C++ Lab Manual

iMn = m;
iSc = s;
}

void DurationType :: fnSetDuration()


{
int h,m,s;
cout << "\nEnter the duration : ";
cin >> h >> m >> s;
if(m<60 && s<60)
{
iHr = h;
iMn = m;
iSc = s;
}
else
cout << "\nInvalid Input\n";
}

void DurationType :: fnShowDuration()


{
cout << iHr << ":"<< iMn << ":"<< iSc << endl;
}

DurationType DurationType :: fnAddDuration(DurationType d2)


{
DurationType d3;
int hh, mm, ss;
ss = iSc + d2.iSc;
mm = iMn + d2.iMn + (ss/60);
hh = iHr + d2.iHr + (mm/60);

d3.iSc = ss % 60;
d3.iMn = mm % 60;
d3.iHr = hh;
return d3;
}

int main()
{
DurationType d1, d2, d3;

d1.fnSetDuration();
d2.fnSetDuration();
d3 = d1.fnAddDuration(d2); // d3 = fnAddDuration(d1,d2);

cout << "\nDuration 1";

Dept. of CSE, SIT Tumkur Page 4


Object Oriented Programming with C++ Lab Manual

d1.fnShowDuration();
cout << "\nDuration 2"
d2.fnShowDuration();
cout << "\nTotal Duration ";
d3.fnShowDuration();

return 0;
}

3. Create a RainGauge class that store rainfallincm information and city name.
Include a zero parameter constructor. Write methods for the following
a. fnReadMeasurement that generates a random decimal value in the range of 0
20cms and reads the name of the city
b. fnDispReading that display city name and rainfall received.
c. Write a friend function that takes an array of RainGauge objects and the
number of cities as parameters and calculates the average rainfall received.
d. Create an array of RainGauge objects in main and display the results.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;

class RainGauge
{
double dRainInCm;
char cLocation[20];

public:
RainGauge();
void fnReadMeasurement();
void fnDispReading();
friend double fnCalcAvg(RainGauge [], int);
};

RainGauge :: RainGauge()
{
dRainInCm = 0.0;
strcpy(cLocation, "\0");
}
void RainGauge :: fnReadMeasurement()
{
cout << "\nEnter Location of the RainGauge\n";
cin >> cLocation;

Dept. of CSE, SIT Tumkur Page 5


Object Oriented Programming with C++ Lab Manual

srand(time(NULL));

dRainInCm = ((rand()%20+1000)/1000.0);

void RainGauge :: fnDispReading()


{
cout << cLocation << " : " << dRainInCm << " cms\n";
}

double fnCalcAvg(RainGauge r[], int iNum)


{
int i;
double dAvgRain = 0.0;
for(i=0; i<iNum;i++)
{
dAvgRain += r[i].dRainInCm;
}
dAvgRain /= iNum;
return dAvgRain;
}

int main()
{
RainGauge rainSensorArray[10];
double dAvgRainFall;
int i, iNum;

cout << "\nEnter the number of cities\n";


cin >> iNum;

for(i=0;i<iNum;i++)
{
rainSensorArray[i].fnReadMeasurement();
}

cout << "\nRainfall Information\n";


cout << "========================\n";
for(i=0;i<iNum;i++)
{
rainSensorArray[i].fnDispReading();
}

dAvgRainFall = fnCalcAvg(rainSensorArray, iNum);

Dept. of CSE, SIT Tumkur Page 6


Object Oriented Programming with C++ Lab Manual

cout << "\nAverage RainFall recieved is " << dAvgRainFall << " cms\n";

return 0;
}

4. Write a C++ program to create a class called QUEUE with appropriate data
members. Demonstrate the followings concepts by implementing suitable
behaviors:
a. Constructors and destructors.
b. Exception handling to take care of queue empty and queue full conditions.
c. Member functions to add an element and to delete an element from the
queue.
d. Write a menu based program to illustrate operations on a Queue.

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
template<class T>

Class queue
{
int f;
int r;
int max;
T *q;
public: queue(int size)
{
f=-1;
r=-1;
max=size;
q=new T[size];
}
~queue()
{
delete q;
}
void insert_front(T x);
void delete_rear(void);
void display(void);
};

template<class T>
void queue<T>::insert_front(T item)
{
if(r==max-1)
throw ('o');

Dept. of CSE, SIT Tumkur Page 7


Object Oriented Programming with C++ Lab Manual

q[++r]=item;
if(f==-1)
f=0;
}

template<class T>
void queue<T>::delete_rear(void)
{
if(f==-1)
throw ('u');
else
{
T e=q[f];
if(f==r)
f=r=-1;
else
++;
cout<<"item delted= "<<e<<endl;
}
}
template<class T>
void queue<T>::display()
{
if(f==-1)
{
cout<<"queue empty"<<endl;
return;
}
cout<<"front"<<" ";
for(int i=f;i<=r;i++)
{
cout<<q[i]<<" ";
}
cout<<"rear";
}

int main()
{
int count;
cout<<"Enter max size for queue"<<endl;
cin>>count;
queue<int> qi(count);
queue<char> qc(count);
int ch,item,datatype;
char itemc;
cout<<"\nEnter choice 1:for integer 2:for character\n";
cin>>datatype;

Dept. of CSE, SIT Tumkur Page 8


Object Oriented Programming with C++ Lab Manual

cout<<"\n1-Add an element 2-Delete an element 3-Display 4-Exit\n";


while(1)
{
cout<<"\nEnter the choice"<<endl;
cin>>ch;
switch(ch)
{
case 1 :cout<<"\nEnter the item to be inserted"<<endl;
if(datatype==1)
{
try
{
cin>>item;
qi.insert_front(item);
}
catch(char c)
{
cout<<"queue overflow"<<endl;
}
}
else if(datatype==2)
{
try
{
cin>>itemc;
qc.insert_front(itemc);
}
catch(char c)
{
cout<<"queue overflow"<<endl;
}
}
break;
case 2 :if(datatype==1)
{
try
{
qi.delete_rear();
}
catch(char c)
{
cout<<"queue underflow"<<endl;
}
}
else if(datatype==2)
{
try

Dept. of CSE, SIT Tumkur Page 9


Object Oriented Programming with C++ Lab Manual

{
qc.delete_rear();
}
catch(char c)
{
cout<<"queue underflow"<<endl;
}
}
break;
case 3 :if(datatype==1)
qi.display();
else if(datatype==2)
qc.display();
break;
case 4 :exit(0);
}
}
return 0;
}

5. Write a C++ program to create a class called EXPRESSION. Accept an


arithmetic expression (assumed to be valid INFIX form) and assign to
EXPRESSION object. Convert the expression in the object to POSTFIX form by
writing appropriate member functions. Display the results.

#include<iostream>
#include<cctype>
#include<cstring>
#include<cstdlib>
using namespace std;

class EXPRESSION
{
private:
char infix[50],postfix[50];
char s[50];
int top;
public:
EXPRESSION(char *str);
void push(char ch);
int precedence(char ch);
char pop();
void convert();
void display();
};

Dept. of CSE, SIT Tumkur Page 10


Object Oriented Programming with C++ Lab Manual

EXPRESSION::EXPRESSION(char *str)
{
strcpy(infix,str);
top=0;
}
void EXPRESSION::push(char ch)
{
s[++top]=ch;
}
char EXPRESSION::pop(void)
{
return(s[top--]);
}

int EXPRESSION::precedence(char ch)


{
if(ch== '(' || ch== '#') return(1);
if(ch== '+' || ch== '-') return(2);
if(ch== '*' || ch== '/') return(3);
if(ch == '^') return(4);
return 0;
}
void EXPRESSION::convert()
{
int i,j=0;
push('#');
for(i=0;infix[i]!='\0';i++)
{
if(isalnum(infix[i]))
postfix[j++]=infix[i];
else
if(infix[i]=='(')
push(infix[i]);
else
if(infix[i]== ')')
{
while(s[top]!='(')
postfix[j++]=pop();
pop();
}
else
{
while(precedence(s[top])>=precedence(infix[i]))
postfix[j++]=pop();
push(infix[i]);
}
} //end of for

Dept. of CSE, SIT Tumkur Page 11


Object Oriented Programming with C++ Lab Manual

while(s[top]!='#') //copy the remaining elements into suffix


postfix[j++]=pop();
postfix[j]='\0';
}
void EXPRESSION::display()
{
cout << postfix << endl;
}

/*---------------------MAIN FUNCTION-------------------------*/

int main()
{
char infix[50];
cout << "Enter the valid Infix Expression :";
cin >> infix;
EXPRESSION Exp(infix); //Create a object and call the constructor with
// argument as infix expression
Exp.convert();
cout << "\nThe Corresponding Suffix expression is:";
Exp.display();
return 0;
}

6. Create two classes DB & DM which store the value of distances. DM stores
distances in metres & centimeters and DB in feet & inches. Write a program that
can read values for the class objects and add one object of DM with another
object of DB. Use friend function to carry out the addition. The object that stores
the result should be a DB object.

#include<iostream>
using namespace std;
class DB;
class DM
{
float metres;
float centimetres;
public:
DM()
{
metres=0;
centimetres=0;
}
DM(float a,float b)
{
metres=a;
centimetres=b;

Dept. of CSE, SIT Tumkur Page 12


Object Oriented Programming with C++ Lab Manual

}
friend void add(DM,DB);
};
class DB
{
float feet;
float inches;
public:
DB()
{
feet=0;
inches=0;
}
DB(float a,float b)
{
feet=a;
inches=b;
}
friend void add(DM,DB);
};
void add(DM d1,DB d2)
{
// 1metre= 39 inches
float f,i;
i=(d1.metres+(d1.centimetres/100))*39;
f=int(i)/12;
i=int(i)%12;
f=f+d2.feet;
i=i+d2.inches;
if(i>72)
{
f=f+int(i)/12;
i=int(i)%12;
}
cout<<"feet="<<f<<endl;
cout<<"inches="<<i<<endl;
}
int main()
{
float x,y;
cout<<"enterthe distance in metres and cms"<<endl;
cin>>x>>y;
DM d1(x,y);
cout<<"enter the distance in feet and inches"<<endl;
cin>>x>>y;
DB d2(x,y);
add(d1,d2);

Dept. of CSE, SIT Tumkur Page 13


Object Oriented Programming with C++ Lab Manual

7. Write a C++ program to create class called bank account. Include the following
data member and member functions.
Data Members Member functions
1.Name of depositor 1. Parameterized Constructor
2.Account holder 2. To deposit an amount
3.Type of account 3. To withdraw amount after Checking the balance
4.Balance amount in the account 4. To display name balance.

#include<iostream>
#include<string.h>
using namespace std;
class bankaccount
{
char name[20];
char acc_no[20];
char acc_type[20];
float amount;
public:bankaccount(char a[20],char b[20],char c[20] ,float d)
{
strcpy(name,a);
amount=d;
}
void deposit(float deposit)
{
amount=amount+deposit;
}
void withdrawl(void)
{
float money;
cout<<"enter the amount to be withdrawn:\n";
cin>>money;
if(money>amount)
{
cout<<"money cannot be withdrawn\n";
}
else
{
cout<<"current balance is:"<<amount;
amount=amount-money;
cout<<"\namount after withdrawl is:"<<amount;
}
}
void display(void)
{
Dept. of CSE, SIT Tumkur Page 14
Object Oriented Programming with C++ Lab Manual

cout<<"\nname of the depositer is:"<<name;


cout<<"\nbalance is:\n"<<amount;
}
};
int main()
{
char a[20],b[20],c[20];
float d;
cout<<"\nenter the name,acc no,acc type,amt:\n";
cin>>a>>b>>c>>d;
bankaccount b1(a,b,c,d);
float amt;
cout<<"\nenter the amount to be deposited:";
cin>>amt;
b1.deposit(amt);
cout<<"\ncheck my balance\n";
b1.display();
cout<<"\nto with draw the money\n";
b1.withdrawl();
}

8. Write a class to represent entities of type Fraction with appropriate data


members. Include a method simplify that simpfies a given fraction ( for eg: 6/8 to
3/4).
Overload the following operators
a. >> to read a fraction object
b. << to display a fraction object
c. == to check if two fractions are the same
d. + to add two fractions
Illustrate these operations in main function.

#include<iostream>
using namespace std;
//Creating a Class fraction
class fraction
{
private:
int* num;
int* deno;

public:
fraction();
fraction operator-(fraction);
fraction operator+(fraction);

friend istream & operator>>(istream &input,fraction &f)


{

Dept. of CSE, SIT Tumkur Page 15


Object Oriented Programming with C++ Lab Manual

cout<<"Enter the value for numerator and denominator\n";


input>>f.num>>f.deno;
return input;
}
//Used to display a fraction
friend ostream & operator<<(ostream &output,fraction &f)
{
cout<<*(fraction::num)<<"/"<<*(fraction::deno);
}
//Default constructor
inline fraction::fraction()
{
this->num=new int(0);
this->deno=new int(0);
}
//Parameterized constructor, used to initialize a fraction
//This function is used to swap two variables
void swap(int &x,int &y)
{
int tmp=x;
x=y;
y=tmp;
}
//This function is used to find L.C.M of two numbers
int lcm(int l,int s)
{
if(l<s)
swap(l,s);
int m=2,result=l;
while(result%s)
{
result=l*m;
m++;
}
return result;
}
//This function is used to find G.C.D of two numbers
int gcd(int a,int b)
{
if(a<b)
swap(a,b);
while(1)
{
int c=a%b;
if(c==0)
return b;
a=b;

Dept. of CSE, SIT Tumkur Page 16


Object Oriented Programming with C++ Lab Manual

b=c;
}
}
};
//Used to subtract two fractions
fraction fraction::operator-(fraction f2)
{
int slcm=lcm(*(this->deno),*(f2.deno));
int num2=*(f2.num)*(slcm / *(f2.deno));
int num1=*(this->num)*(slcm / *(this->deno));
int num=num1-num2;
int t=num;
num=num/gcd(num,slcm);
slcm=slcm/gcd(t,slcm);
fraction f(num,slcm);
return f;
}
fraction fraction::operator+(fraction f1)
{
int slcm=lcm(*(f1.deno),*(this->deno));
int num1=*(f1.num)*(slcm/ *(f1.deno));
int num2=*(this->num)*(slcm/ *(this->deno));
int num=num1+num2;
int t=num;
num=num/gcd(num,slcm);
slcm=slcm/gcd(t,slcm);
fraction f(num,slcm);
return f;
}
int main()
{
int c;
char ch;
fraction f1,f2;
while(true)
{
cout<<"\nEnter numerator and denominator of 1st fraction:";
cin>>f1;
cout<<"\nEnter numerator and denominator of 2nd fraction:";
cin>>f2;
cout<<"Fraction 1:\n ";
cout<<f1;
cout<<"\nFraction 2:\n ";
cout<<f2;
cout<<"\n";
do
{

Dept. of CSE, SIT Tumkur Page 17


Object Oriented Programming with C++ Lab Manual

cout<<"\n Menu\n"<<"----------------\n"<<"1.Addition\n2.Compare 2
fractions\n";
cout<<"\nEnter which operation you want to perform:";
cin>>c;
switch(c)
{
case 1:fraction res=f1+f2;
cout<<"\nResult of addition:";
res.printfrac();
break;

case 2:fraction res=f1-f2;


cout<<"\nResult of subtraction:";
res.printfrac();
break;

default:cout<<"\nInvalid choice!!!";
}
cout<<"\nDo you want to exit from program(Y/N):";
cin>>ch;
if(ch=='Y'||ch=='y')
return 0;
}

9. Write a C++ program to create class called MATRIX using a two dimensional
array of integers. Implement the following operations by overloading the
operator‘==’ which checks the compatibility of two matrices m1 and m2 to be
added and subtracted. Perform the addition and subtraction by overloading the
operator + and – respectively. Display the results (sum matrix m3 and difference
matrix m4) by overloading the operator <<.

#include<iostream>
using namespace std;
class matrix
{
int m,n;
int a[10][10];
public:matrix()
{
m=0;
n=0;
}
matrix(int i,int j)
{
m=i;
n=j;
}

Dept. of CSE, SIT Tumkur Page 18


Object Oriented Programming with C++ Lab Manual

void setdata();
friend matrix operator +(matrix &,matrix &);
friend matrix operator -(matrix &,matrix &);
friend int operator ==(matrix &,matrix &);
friend ostream & operator<<(ostream &dout,matrix &x);
};

void matrix::setdata()
{
cout<<"enter elements"<<endl;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cin>>a[i][j];
}
}
matrix operator +(matrix &m1,matrix &m2)
{
matrix temp(m1.m,m1.n);
for(int i=0;i<m1.m;i++)
{
for(int j=0;j<m1.n;j++)
temp.a[i][j]=m1.a[i][j]+m2.a[i][j];
}
return temp;
}
matrix operator -(matrix &m1,matrix &m2)
{
matrix temp(m1.m,m1.n);
for(int i=0;i<m1.m;i++)
{
for(int j=0;j<m1.n;j++)
temp.a[i][j]=m1.a[i][j]-m2.a[i][j];
}
return temp;
}
int operator==(matrix &m1,matrix &m2)
{
if((m1.m==m2.n)&&(m1.n==m2.n))
return 1;
else
return 0;
}
ostream & operator<<(ostream &dout,matrix &x)
{
for(int i=0;i<x.m;i++)
{

Dept. of CSE, SIT Tumkur Page 19


Object Oriented Programming with C++ Lab Manual

for(int j=0;j<x.n;j++)
dout<<x.a[i][j]<<" ";
dout<<endl;
}
return dout;
}
int main()
{
int row1,row2,col1,col2;
cout<<"enter the order of matrix1"<<endl;
cin>>row1>>col1;
matrix m1(row1,col1);
cout<<"enter the order of matrix2"<<endl;
cin>>row2>>col2;
matrix m2(row2,col2);
if(m1==m2)
{
m1.setdata();
m2.setdata();
cout<<"matrix 1\n";
cout<<m1;
cout<<"matrix 2\n";
cout<<m2;
matrix m3=m1+m2;
matrix m4=m1-m2;
cout<<"addition of matrices"<<endl;
cout<<m3;
cout<<"subtraction of matrices"<<endl;
cout<<m4;
}
else
cout<<"order of matrices are not equal"<<endl;
return 0;
}

10. Write a C++ program to create class called MATRIX. Overload the operator
‘==’which checks the compatibility of two matrices m1 and m2 to be multiplied.
Perform the multiplication of matrices by overloading the operator *. Display
the results (product matrix m3) by overloading the operator <<.

#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;
class matrix
{
int r,c;

Dept. of CSE, SIT Tumkur Page 20


Object Oriented Programming with C++ Lab Manual

int a[10][10];
public:matrix()
{}
matrix(int m,int n)
{
r=m;
c=n;
}
void read()
{
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>a[i][j];
}
friend ostream & operator <<(ostream &dout,matrix &m);
friend int operator == (matrix &m1,matrix &m2);
friend matrix operator * (matrix &m1, matrix &m2);
};
ostream & operator << (ostream & dout,matrix &m)
{
for(int i=0;i<m.r;i++)
{
for(int j=0;j<m.c;j++)
{
dout<<m.a[i][j];
dout<<setw(6);
}
dout<<"\n";
}
return dout;
}
int operator == (matrix &m1,matrix &m2)
{
int flag;
try
{
flag=1;
if(m1.c==m2.r)
{
if((m1.r==m2.r)&&(m1.c==m2.c))
{
for(int i=0;i<m1.r;i++)
for(int j=0;j<m1.c;j++)
if(m1.a[i][j]!=m2.a[i][j])
flag=0;
}
cout<<"2 matricies are equal\n";

Dept. of CSE, SIT Tumkur Page 21


Object Oriented Programming with C++ Lab Manual

}
else
throw(m1.r);
}
catch(...)
{
cout<<"multiplication not possivli\n";
exit(0);
}
if(flag)
return 1;
else
return 0;
}
matrix operator * (matrix &m1,matrix &m2)
{
matrix m3(m1.r,m1.c);
for(int i=0;i<m1.r;i++)
{
for(int j=0;j<m2.c;j++)
{ m3.a[i][j]=0;
for(int k=0;k<m1.c;k++)
m3.a[i][j]=m3.a[i][j]+m1.a[i][k]*m2.a[k][j];
}
}
return m3;
}
int main()
{
int r1,r2,c1,c2;
cout<<"enter the num of rows n col of 1st matrix\n";
cin>>r1>>c1;
matrix m1(r1,c1);
cout<<"enter the num of rows n col of 2nd matrix\n";
cin>>r2>>c2;
matrix m2(r2,c2);
cout<<"enter the "<<r1*c1<<"elments of matrix1\n";
m1.read();
cout<<"enter the "<<r2*c2<<"elements of matrix2\n";
m2.read();
matrix m3;
cout<<"1st matrix:\n";
cout<<m1;
cout<<"2nd matrix:\n";
cout<<m2;
int f=m1==m2;
if(f==0)

Dept. of CSE, SIT Tumkur Page 22


Object Oriented Programming with C++ Lab Manual

{
cout<<"matr are not equal\n";
}
else
{
cout<<"mat are equal\n";
}
m3=m1*m2;
cout<<"resultant matrix:\n";
cout<<m3;
return 0;
}

11. Write a C++ program to create a class called STUDENT with data members
USN, Name and Age. Using Inheritance create the classes UGSTUDENT and
PGSTUDENT having fields as Semester, Fees and Stipend. Enter the data for at
least 5 students. Find the Semesterwise average age for all UG and PG students
separately.

#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>

class student
{
protected:
char usn[20];
char name[20];
int age;

public:
void readinfo();
};

class ugstudent:public student


{
int sem;
float stipend;
float fees;

public:
void ugreadinfo();
friend void average_age(ugstudent *a,int n);

};

Dept. of CSE, SIT Tumkur Page 23


Object Oriented Programming with C++ Lab Manual

class pgstudent:public student


{
int sem;
float stipend;
float fees;

public:
void pgreadinfo();
friend void average_age(pgstudent *a,int n);
};
void student::readinfo()
{
cout<<"Name:"; cin>>name; cout<<"USN"; cin>>usn; cout<<"AGE:";
cin>>age;
}
void ugstudent::ugreadinfo()
{
cout<<"Semester:"; cin>>sem; cout<<"Stipend"; cin>>stipend;
cout<<"Fees:"; cin>>fees;
}
void pgstudent::pgreadinfo()
{
cout<<"Semester:"; cin>>sem; cout<<"Stipend"; cin>>stipend;
cout<<"Fees:"; cin>>fees;
}
void average_age(ugstudent *a,int n)
{
int count[10],sum[10];
for(int i=0;i<10;i++)
count[i]=sum[i]=0;
for(i=0;i<n;i++)
{
sum[a[i].sem]+=a[i].age; count[a[i].sem]++;
}
for(i=0;i<8;i++)
{
if(count[i]!=0)
{
cout<<"Average age of sem"<<i<<"student"; cout<<sum[i]/count[i]<<endl;

void average_age(pgstudent *a,int n)


{
int count[10],sum[10];
for(int i=0;i<10;i++)
count[i]=sum[i]=0;

Dept. of CSE, SIT Tumkur Page 24


Object Oriented Programming with C++ Lab Manual

for(i=0;i<n;i++)
{
sum[a[i].sem]+=a[i].age; count[a[i].sem]++;
}
for(i=0;i<8;i++)
{
if(count[i]!=0)
{
cout<<"Average age of sem"<<i<<"student is \n";
cout<<sum[i]/count[i]<<endl;
}
}
};

int main()
{

ugstudent ug[10]; pgstudent pg[10]; int n,i;

while(1)
{

cout<<"1.UGSTUDENT 2.PGSTUDENT 3.EXIT\n";


int choice;
cout<<"Enter the choice\n";
cin>>choice;
switch(choice)
{
case 1:cout<<"Enter the no of students\n"; cin>>n;
for(i=0;i<n;i++)
{
ug[i].readinfo();
ug[i].ugreadinfo();

}
average_age(ug,n);
break;

case 2:cout<<"Enter the number of students\n";


cin>>n;
for(i=0;i<n;i++)
{

pg[i].readinfo();
pg[i].pgreadinfo();

Dept. of CSE, SIT Tumkur Page 25


Object Oriented Programming with C++ Lab Manual

average_age(pg,n);
break;

default:exit(0);
}
}
return 0 ;
}

12. Create class called ACCOUNT that stores customer name, account number and
type of the account. From this derive the classes CUR_ACCT and SAV_ACCT.
Include necessary member functions in order to achieve the following tasks
i. Accept deposit from a customer and update the balance.
ii. Compute the deposit interest.
iii. Permit withdrawal and update the balance.
iv. Check for the minimum balance, impose penalty and update the balance.

#include<iostream>
using namespace std;
class acc
{
protected:char name[20];
int accno;
char type[20];

public:void virtual getdata()=0;


void virtual deposit()=0;
void virtual interest()=0;
void virtual withdrawl()=0;
void virtual check()=0;
void virtual display()=0;
};
class sav_acc:public acc
{
float bal;
public:void getdata()
{
cout<<"enter the name accno type and balance"<<endl;
cin>>name>>accno>>type>>bal;
}
void deposit()
{
int dep;
cout<<"enter the deposit"<<endl;
cin>>dep;
bal=bal+dep;

Dept. of CSE, SIT Tumkur Page 26


Object Oriented Programming with C++ Lab Manual

}
void interest()
{
int r=5;
float interest=(bal*r)/100.0;
bal=bal+interest;
}
void withdrawl()
{
int amt;
cout<<"enter the withdrawl amount"<<endl;
cin>>amt;
bal=bal-amt;
}
void check()
{
if(bal<500)
{
cout<<"penalty imposed"<<endl;
bal=bal-100;
}

}
else
cout<<"no penalty"<<endl;
}
void display()
{
cout<<"name= "<<name<<endl;
cout<<"accno= "<<accno<<endl;
cout<<"type= "<<type<<endl;
cout<<"balance= "<<bal<<endl;
}
};
class cur_acc:public acc
{
float bal;
public:void getdata()
{
cout<<"enter the name accno type and balance"<<endl;
cin>>name>>accno>>type>>bal;
}
void deposit()
{
int dep;
cout<<"enter the deposit"<<endl;
cin>>dep;

Dept. of CSE, SIT Tumkur Page 27


Object Oriented Programming with C++ Lab Manual

bal=bal+dep;
}
void interest()
{
int r=10;
float interest=(bal*r)/100.0;
bal=bal+interest;
}
void withdrawl()
{
int amt;
cout<<"enter the withdrawl amount"<<endl;
cin>>amt;
bal=bal-amt;
}
void check()
{
if(bal<1000)
{
cout<<"penalty imposed"<<endl;
bal=bal-200;
}
else
cout<<"no penalty"<<endl;
}

void display()
{
cout<<"name= "<<name<<endl;
cout<<"accno= "<<accno<<endl;
cout<<"type= "<<type<<endl;
cout<<"balance= "<<bal<<endl;
}
};
int main()
{
acc *ptr[100];
int usn=0;
char ch,op;
do
{
cout<<"enter s.saving c.current"<<endl;
cin>>ch;
if(ch=='s')
ptr[usn]=new sav_acc;
else
ptr[usn]=new cur_acc;

Dept. of CSE, SIT Tumkur Page 28


Object Oriented Programming with C++ Lab Manual

cout<<"enter the account information"<<endl;


ptr[usn]->getdata();
usn++;
cout<<"enter y-continue n-stop"<<endl;
cin>>op;
}while(op=='y');
while(1)
{
int a;
int ch1;
cout<<"enter object num to operate"<<endl;
cin>>a;
cout<<"\n enter option\n 1.deposit\t 2.interest\t 3.withdrawl\t
4.penalty\t
5.display\t 6.exit"<<endl;
cin>>ch1;
switch(ch1)
{
case 1:ptr[a-1]->deposit();
break;
case 2:ptr[a-1]->interest();
break;
case 3:ptr[a-1]->withdrawl();
break;
case 4:ptr[a-1]->check();
break;
case 5:ptr[a-1]->display();
break;
case 6:return 0;
}
}
}

13. Define a ITEM class with item_name, item_code, item_prize, number_of_items


(item_count) as data members. Demonstrate the followings concepts by suitable
behaviors:Working with Files: demonstrate the following file operations:
a. Writing an object at the end of file
b. Reading all objects from a file and display on console.
c. Update a given object information on the file.

#include<iostream>
#include<cstdlib>
#include<fstream>
using namespace std;
class item
{
char name[20];

Dept. of CSE, SIT Tumkur Page 29


Object Oriented Programming with C++ Lab Manual

int code;
int price;
int no_of_objects;
public:
void getdata()
{
cout<<"\nenter name,code,price,no of objects\n";
cin>>name>>code>>price>>no_of_objects;
}
void display()
{
cout<<endl;
cout<<"name:"<<name<<" code:"<<code<<" price:"<<price<<" no of
items:"<<no_of_objects<<endl;
}
};
Int main()
{
int n;
cout<<"enter the no of objects: ";
cin>>n;
fstream file;
item it;
file.open("item",ios::out);
file.close();
file.open("item",ios::app|ios::in);
if(file)
{
cout<<"file opened successfully\n";
for(int i=0;i<n;i++)
{
cout<<"\nenter the details of the item "<<i+1;
it.getdata();
file.write((char*)&it,sizeof(it));
}
file.seekg(0);
for(int i=0;i<n;i++)
{
cout<<"item"<<i+1;
file.read((char*)&it,sizeof(it));
it.display();
}
cout<<"\nenter another object to add\n";
it.getdata();
file.write((char*)&it,sizeof(it));
file.seekg(0);
cout<<"\nafter adding an item";

Dept. of CSE, SIT Tumkur Page 30


Object Oriented Programming with C++ Lab Manual

for(int i=0;i<=n;i++)
{
file.read((char*)&it,sizeof(it));
it.display();
}
cout<<"\nenter the object no to be modified :";
int n1;
cin>>n1;
int loc=(n1-1)*sizeof(it);
file.seekp(loc);
cout<<"\nenter the new values for the item ";
it.getdata();
file.write((char*)&it,sizeof(it));
cout<<"\nfile after modification";
file.seekg(0);
for(int i=0;i<=n;i++)
{
file.read((char*)&it,sizeof(it));
it.display();
}
file.close();
}
else
{
cout<<"error in opening the file";
}
}

14. Write a C++ program to perform the following operations on STRING using
string library
i. Parameterized and copy constructor
ii. Compare two string objects
iii. Find substring in a main string
iv. Return the position of the first occurrence a given substring in the string.
v. Return the position of the last occurrence a given substring in the string
vi. Insert a given substring at the end of main string
vii. Swap content of two given strings

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string s1("abc");
string s2("def");
string s3(s2);

Dept. of CSE, SIT Tumkur Page 31


Object Oriented Programming with C++ Lab Manual

string s4,s5;
cout<<s1<<endl<<s2<<endl<<s3<<endl;
cout<<"enter first string"<<endl;
cin>>s4;
cout<<"enter second string"<<endl;
cin>>s5;

while(1)
{
int ch,x1,x2,x3,x4,x5;
string str1,sbst;
char c1,c2;
cout<<"1:compare 2:substring 3:position of 1st occurence
4:position
of last occurence 5:insert a substring at end 6:swapping
7:concatenate 8:exit"<<endl;
cout<<"enter the choice"<<endl;
cin>>ch;
switch(ch)
{
case 1 :cout<<"compare two string"<<endl;
x1=s4.compare(s5);
if(x1==0)
cout<<s4<<" = "<<s5<<endl;
else if(x1>0)
cout<<s4<<" > "<<s5<<endl;
else
cout<<s4<<" < "<<s5<<endl;
break;
case 2 :cout<<"enter the substring to be found"<<endl;
cin>>str1;
x2=s4.find(str1);
cout<<"substring"<<" "<<str1<<" is found at :
"<<x2<<"th position"<<endl;
break;
case 3: cout<<"enter the char to be found first"<<endl;
cin>>c1;
x3=s4.find_first_of(c1);
cout<<c1<<"is found first at: "<<x3<<endl;
break;
case 4:cout<<"enter the char to be found last"<<endl;
cin>>c2;
x4=s4.find_last_of(c2);
cout<<c2<<"is found last at: "<<x4<<endl;
break;
case 5:cout<<"enter the substring to be inserted"<<endl;
cin>>sbst;

Dept. of CSE, SIT Tumkur Page 32


Object Oriented Programming with C++ Lab Manual

x5=s4.length();
s4.insert(x5,sbst);
cout<<"modified s4: "<<s4<<endl;
break;
case 6:s4.swap(s5);
cout<<"after swapping"<<endl;
cout<<s4<<endl<<s5<<endl;
break;
case 7:s4=s4+" "+s5;
cout<<"concatenated string is "<<s4<<endl;
break;
case 8:
}
}
}

15. Write a C++ program to create a template functions for Insertion sort and
Selection Sort. Demonstrate sorting of integers and double data types for both
sorting algorithms.
#include<iostream>
#include<conio.h>
using namespace std;
template <class T>
void s_sort(T a[],int n)
{
int i,j,t;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i]) //for descending order use if(a[j]>a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}

template<class T>
void isort(T a[],int n)
{
int i;
for(i=1;i<n;i++)
{
T t=a[i];

Dept. of CSE, SIT Tumkur Page 33


Object Oriented Programming with C++ Lab Manual

int j;
for(j=i-1;j>=0&&t<a[j];j--)
{
a[j+1]=a[j];
}
a[j+1]=t;
}
}
int main()
{
int a[100],i,n;
double s;
int choice;
while(1)
{
cout<<"Select\n 1.Selection Sort\n 2.Insertion Sort\n";
cout<<"Enter choice";
cin>>choice;
switch(choice)
{
case 1: cout<<"Enter The number of Element:\n";
cin>>n;
cout<<"\nEnter Elements:\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
s_sort(a,n);
cout<<"\nSorting using Selection Sort\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
break;
case 2:cout<<"Enter The number of Element:\n";
cin>>s;
cout<<"\nEnter Elements:\n";
for(i=0;i<s;i++)
{
cin>>a[i];
}
s_sort(a,s);
cout<<"\nSorting using Insertion Sort\n";
for(i=0;i<s;i++)
{
cout<<a[i]<<"\t";
}

Dept. of CSE, SIT Tumkur Page 34


Object Oriented Programming with C++ Lab Manual

break;
}
}
return 0;
}
16. Write a C++ program to create a template class STACK, with push and pop and
display member functions. Write a menu based program to illustrate the
working for stack of floating point values and stack of integers. Use exception
handling to handle the special conditions underflow and overflow of the stack.

#include<iostream>
#include<cstdlib>
using namespace std;
template<class T>
class stack
{
T *st;
int top;
int max;
public:
stack(int size)
{
top=-1;max=size;
st=new T[size];
}
~stack(){delete st;}
void operator+(T );
void operator-(int);
void display();
};
template<class T>
void stack<T>::operator+(T item)
{
if(top==max-1)
throw ('o');
else
st[++top]=item;
return;
}

template<class T>
void stack<T>::operator-(int a)
{
if(top==-1)
throw ('u');
else
{

Dept. of CSE, SIT Tumkur Page 35


Object Oriented Programming with C++ Lab Manual

T ele=st[top--];
cout<<"item deleted= "<<ele<<endl;
}
}
template<class T>
void stack<T>::display()
{
if(top==-1)
cout<<"stack is empty"<<endl;
else
{
cout<<"bottom"<<" ";
for(int i=0;i<=top;i++)
{
cout<<st[i]<<" ";
}
cout<<"top";
}
return;
}
int main()
{
int count;
cout<<"Enter max size of stack"<<endl;
cin>>count;
stack<int> si(count);
stack<float> sf(count);
int ch,item,dd;
float itemf;
cout<<"\nEnter choice 1:for integer 2:for float\n";
cin>>dd;
cout<<"\n1-Push 2-Pop 3-Display 4-Exit\n";
while(1)
{
cout<<"\nEnter the choice"<<endl;
cin>>ch;
switch(ch)
{
case 1 :cout<<"\nEnter the item to be inserted"<<endl;
if(dd==1)
{
try{
cin>>item;
si+item;
}
catch(char s)
{

Dept. of CSE, SIT Tumkur Page 36


Object Oriented Programming with C++ Lab Manual

cout<<"stack overflow"<<endl;
}
}
else if(dd==2)
{
try{
cin>>itemf;
sf+itemf;
}
catch(char s)
{
cout<<"stack overflow"<<endl;
}
}
break;
case 2 :if(dd==1)
{
try
{
si-0;
}
catch(char s)
{
cout<<"stack undrflow"<<endl;
}
}
else if(dd==2)
{
try
{
sf-0;
}
catch(char s)
{
cout<<"stack underflow"<<endl;
}
}
break;
case 3 :cout<<"elements of stack"<<endl;
if(dd==1)
si.display();
else if(dd==2)
sf.display();
break;
case 4 :exit(0);
}
}return 0;}

Dept. of CSE, SIT Tumkur Page 37


Object Oriented Programming with C++ Lab Manual

Dept. of CSE, SIT Tumkur Page 38

Você também pode gostar