Escolar Documentos
Profissional Documentos
Cultura Documentos
Table of Contents
#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;
}
iMn = m;
iSc = s;
}
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);
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;
srand(time(NULL));
dRainInCm = ((rand()%20+1000)/1000.0);
int main()
{
RainGauge rainSensorArray[10];
double dAvgRainFall;
int i, iNum;
for(i=0;i<iNum;i++)
{
rainSensorArray[i].fnReadMeasurement();
}
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');
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;
{
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;
}
#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();
};
EXPRESSION::EXPRESSION(char *str)
{
strcpy(infix,str);
top=0;
}
void EXPRESSION::push(char ch)
{
s[++top]=ch;
}
char EXPRESSION::pop(void)
{
return(s[top--]);
}
/*---------------------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;
}
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);
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
#include<iostream>
using namespace std;
//Creating a Class fraction
class fraction
{
private:
int* num;
int* deno;
public:
fraction();
fraction operator-(fraction);
fraction operator+(fraction);
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
{
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;
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;
}
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++)
{
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;
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";
}
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)
{
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();
};
public:
void ugreadinfo();
friend void average_age(ugstudent *a,int n);
};
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;
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()
{
while(1)
{
}
average_age(ug,n);
break;
pg[i].readinfo();
pg[i].pgreadinfo();
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];
}
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;
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;
#include<iostream>
#include<cstdlib>
#include<fstream>
using namespace std;
class item
{
char name[20];
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";
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);
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;
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];
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";
}
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
{
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)
{
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;}