0% found this document useful (0 votes)
265 views60 pages

CPP All Programs-2019 SASTRA University

This document provides an overview of various C++ programming concepts including inline functions, function overloading, default parameters, classes and constructors/destructors, operator overloading, data conversion, pointers, inheritance, and files. It includes examples of code implementing these concepts, such as inline functions to find the cube of a number passed by reference or pointer, overloaded functions to find the absolute value of integers and floats, and functions using default parameters to calculate the sum of an arithmetic progression.

Uploaded by

star
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
265 views60 pages

CPP All Programs-2019 SASTRA University

This document provides an overview of various C++ programming concepts including inline functions, function overloading, default parameters, classes and constructors/destructors, operator overloading, data conversion, pointers, inheritance, and files. It includes examples of code implementing these concepts, such as inline functions to find the cube of a number passed by reference or pointer, overloaded functions to find the absolute value of integers and floats, and functions using default parameters to calculate the sum of an arithmetic progression.

Uploaded by

star
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

1

CPP Programs

Concepts Page.No

INLINE FUNCTIONS 2
FUNCTION OVERLOADING 2
DEFAULT PARAMETERS 3
CLASSES, CONSTRUCTORS AND DESTRUCTORS 5
OPERATOR OVERLOADING 8
DATA CONVERSION 17
POINTERS 21
INHERITANCE 24
MISCELLANEOUS PROGRAMS 30
FRIEND FUNCTION 36
VIRTUAL FUNCTIONS 38
C AND C++ STRINGS 40
FILES 46
MISCELLANEOUS PROGRAMS – II 50

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
2

FUNCTIONS cout<<endl<<"\n The greater of the two


1.Write an inline function called distances is :"<<d1.compare(d2);}
zerosmaller() by passing two int arguments 3. Inline function program to find cube
by reference which then sets the smaller using pass by reference method.
number to 0. Write a main() program to #include<iostream.h>
exercise this function. inline void cube(int &a)
#include<iostream> {a=a*a*a;}
using namespace std; int main()
inline void zerosmaller(int &a,int &b) { int x;
{ if(a>b) clrscr();
b=0; cout<<"enter the number: ";
if(a<b) cin>>x;
a=0; cube(x);
if(a==b) cout<<"the cube is: "<<x;
cout<<"both nos. are equal"; return 0;}
} 4. Inline function program to find cube
int main() using pointers.
{ int a,b; #include<iostream.h>
cout<<"enter 2 nos."; inline int cube(int *a)
cin>>a>>b; {
zerosmaller(a,b); return((*a)*(*a)*(*a));
cout<<endl<<a<<" "<<b; }
} int main()
2. INLINE MEMBER FUNCTIONS { int a;
Create a distance class with a data member clrscr();
of datatype int. Include a member function cout<<"enter the number: ";
to take input for distance and another inline cin>>a;
member function to compare two distances. cout<<"the cube is: "<<cube(&a);
Write a main() program to exercise the return 0;}
following functions. FUNCTION OVERLOADING
#include<iostream> 5. Write a program to find the absolute
using namespace std; value of an integer as well as a floating point
class dist value using function over loading.
{ int a; #include <iostream>
public: using namespace std;
void getd() int absolute(int);
{cout<<endl<<"Enter distance in meter: "; float absolute(float);
cin>>a;} int main()
inline int compare(dist d2) { int a = -5;
{return(a>d2.a)?a:d2.a;} float b = 5.5;
}; cout << "Absolute value of " << a << " = "
int main() << absolute(a) << endl;
{ dist d1,d2; cout << "Absolute value of " << b << " = " <<
d1.getd(); absolute(b);}
d2.getd(); int absolute(int var)
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
2

{ if (var < 0) Write a function called power() that takes N


var = -var; (double) and P (int) as input, and returns the
return var; result NP as a double value. Use a default
} argument of 2 for P, so that if this argument
float absolute(float var) is omitted, the number N will be squared.
{ if (var < 0.0) Overload power() function, to work with int,
var = -var; long, and float. Overload the power()
return var; function using char datatype also, which
} should print P times the given character N.
Write the main() program to exercise these
DEFAULT PARAMETERS overloaded functions with all argument
6.Write a function named sum() with 3 types.
parameters namely no of values (int n), //FUNTION PROTOTYPES
difference(int diff), and the value of the first #include<iostream.h>
term(int first_term). Set default values to int P;
these parameters and hence find the sum of double func(double N1,int P=2);
the corresponding AP by keeping one or int func(int N2,int P=2);
more of the arguments default. float func(float N3,int P=2);
#include<iostream> long int func(long int N4,int P=2);
#include<iomanip> void func(char N5,int P=2);
using namespace std; void main(void)
long int sum(int n,int diff=1,int first_term=1 ) { double N1;
{long sum=0;; cout<<"enter base";
for(int i=0;i<n;i++) cin>>N1;
{cout<<setw(5)<<first_term+diff*i; cout<<"enter power";
sum+=first_term+diff*i; cin>>P;
} cout<<"Square of " <<N1<<"is (default arg 2)
return sum; "<<func(N1)<<endl;
} cout<<N1<<"Power"<<P<<"is
int main() "<<func(N1,P)<<endl;
{cout<<endl<<"Sum="<<setw(7)<<sum(10)<< int N2;
endl; cout<<"enter base";
//first term=1; diff=1,n=10 cin>>N2;
//sums the series 1,2,3,4,5………10 cout<<"Square of " <<N2<<"is (default arg 2)
cout<<endl<<"Sum="<<setw(7)<<sum(6,3,2)< "<<func(N2)<<endl;
<endl; cout<<N2<<" Power "<<P<<" is
//first term=1; diff=2,n=10 "<<func(N2,P)<<endl;
//sums the series 2,5,8,11,14,17 float N3;
cout<<endl<<"Sum="<<setw(7)<<sum(10,2)< cout<<"enter base";
<endl; cin>>N3;
//first term=1; diff=2,n=10 cout<<"Square of " <<N3<<"is (default arg 2)
//sums the series 1,3,5………..19 "<<func(N3)<<endl;
return 0; cout<<N3<<" Power "<<P<<" is
} "<<func(N3,P)<<endl;
7. Raising a number ‗N‘ to the power ‗P‘ is long int N4;
the same as multiplying N by itself P times. cout<<"enter base";
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
3

cin>>N4; name(basically overload)to add two normal


cout<<"Square of " <<N4<<"is (default arg 2) variables.
"<<func(N4)<<endl; #include<iostream>
cout<<N4<<" Power "<<P<<" is using namespace std;
"<<func(N4,P)<<endl; class timex
char N5; {int min;
cout<<"enter base"; int sec;
cin>>N5; public:
cout<<"Square of " <<N5<<"is (default arg 2) void getd()
"; { cin>>min>>sec; }
func(N5); void disp()
cout<<N5<<" Power "<<P<<" is "; { cout<<min<<":"<<sec; }
func(N5,P); } void add(timex a,timex b)
double func(double N,int P) { a.sec+=b.sec+a.min*60+b.min*60;
{double pwr=1.0; a.min=a.sec/60;
int i; a.sec=a.sec%60;
for(i=1;i<=P;i++) cout<<a.min<<":"<<a.sec<<endl;}
pwr=pwr*N; };
return pwr; } int add(int a,int b)
int func(int N,int P) { int c;
{int pwr=1; c=a+b;
int i; return c;}
for(i=1;i<=P;i++) int main()
pwr=pwr*N; { timex a,b,c;
return pwr; } a.getd();
long int func(long int N,int P) b.getd();
{long int pwr=1; c.add(a,b);//member function called
int i; int x,y;//ordinary int variables
for(i=1;i<=P;i++) cin>>x>>y;
pwr=pwr*N; cout<<"x+y= "<<add(x,y); }
return pwr; } 9.Program to find the multiplied and the
float func(float N,int P) cubic values using inline function.
{float pwr=1.0; #include<iostream>
int i; using namespace std;
for(i=1;i<=P;i++) class line
pwr=pwr*N; { public:
return pwr; } inline float mul(float x,float y)
void func(char N,int P) { return(x*y);}
{int i; inline float cube(float x)
for(i=1;i<=P;i++) { return(x*x*x);}
cout<<N<<" "; } };
8. Create a class timex with data members int main()
min and sec . Write a member function to get {line obj;
input of time and another to display time. float val1,val2;
Write one more member function to add two cout<<"Enter two values:";
timex objects and also use the same function cin>>val1>>val2;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
4

cout<<"\nMultiplication value { Line line;


is:"<<obj.mul(val1,val2); // set line length
cout<<"\n\nCube value is line.setLength(6.0);
cout << "Length of line : " <<
:"<<obj.cube(val1)<<"\t"<<obj.cube(val2);}
line.getLength() <<endl;
Output: return 0;
Enter two values:57 }
Multiplication Value is: 35 When the above code is compiled and executed
Cube Value is: 25 343 following result is produced :
10. Program to find the largest of the two Object is being created
numbersusing inline function. Length of line : 6
#include<iostream> Parameterized Constructor
using namespace std; 12. A default constructor does not have any
inline int largest(int x, int y); parameteric values, but if needed we can have a
int main() constructor containing parameters/arguments. This
helps usin initialising values of our choice to the data
{ int n1,n2;
members of an object at the time of its creation as
cout<<"enter two values";
shown in the following example:
cin>>n1>>n2;
#include <iostream>
cout<<"the largest is"<<largest(n1,n2); } using namespace std;
int largest(int x, int y) class Line {
{ return((x > y)?x:y); } public:
Output: void setLength( double len );
enter two values89 double getLength( void );
the largest is9 Line(double len); // This is the constructor
CLASSES, CONSTRUCTORS AND private:
DESTRUCTORS double length;
11. Class and constructor };
#include <iostream> // Member functions definitions including constructor
using namespace std; Line::Line( double len)
class Line { { cout << "Object is being created, length = " << len
public: << endl;
void setLength( double len ); length = len;
double getLength( void ); }
Line(); // This is the constructor void Line::setLength( double len )
private:
{ length = len;
double length;
}
};
// Member functions definitions including double Line::getLength( void )
constructor { return length;
Line::Line(void) }
{ cout << "Object is being created" << endl; int main( ) {
} Line line(10.0);
void Line::setLength( double len ) // get initially set length.
{ length = len; cout << "Length of line : " << line.getLength()
} <<endl;
double Line::getLength( void ) // set line length again
{ return length; line.setLength(6.0);
} cout << "Length of line : " << line.getLength()
// Main function for the program
<<endl;
int main( )
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
5

} }
The Class Destructor 14.A class and object(having an int array
13. A destructor is a special member function of a data member) program to sort an array and
class that is executed whenever an object of it's class search any array number‘s location.
goes out of scope or whenever the delete expression #include<iostream.h>
is applied to a pointer to the object of that class.A class sort_search
destructor will have exact same name as the class {public:
prefixed with a symbol tilde (~) and it can neither
int a[10],n,t;
return a value nor can it take any parameters, unlike
void sort();
contructors which can have parameters only.
void search();
Destructor can be very useful for releasing resources
before coming out of the program like closing files, };
releasing memories etc. void sort_search::sort()
Following example explains the concept of destructor: {cout<<"enter the size"<<endl;
#include <iostream> cin>>n;
using namespace std; cout<<"enter the array elements"<<endl;
class Line { for(int i=0;i<n;i++)
public: cin>>a[i];
void setLength( double len ); for(i=0;i<n;i++)
double getLength( void ); {for(int j=0;j<(n-i-1);j++)
Line(); // This is the constructor {if(a[j]>a[j+1])
declaration {t=a[j];
~Line(); // This is the destructor: a[j]=a[j+1];
declaration a[j+1]=t;}}
private: }
double length; cout<<"the sorted array is "<<endl;
}; for(i=0;i<n;i++)
Line::Line(void) cout<<a[i]<<" ";
{ cout << "Object is being created" << endl; }
} void sort_search::search()
Line::~Line(void) {int n,a[10],data,flag=0;
{ cout << "Object is being deleted" << endl; cout<<"enter the size"<<endl;
} cin>>n;
void Line::setLength( double len ) cout<<"enter the array elements"<<endl;
{ length = len; for(int i=0;i<n;i++)
} cin>>a[i];
double Line::getLength( void ) cout<<"enter the number to be
{ return length; searched"<<endl;
} cin>>data;
// Main function for the program for(i=0;i<n;i++)
int main( ) {if(a[i]==data)
{ Line line; { flag=1;break;}
// set line length }
line.setLength(6.0); if(flag==1)
cout << "Length of line : " << line.getLength() cout<<"the given data"<<" "<<data<<"
<<endl; "<<"present in the location"<<" "<<i+1<<endl;
else
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
6

{cout<<"the given data is not present in the }


array"<<endl; void disp()
}} { cout<<endl<<rp<<" "<<ip; }
void main() };
{int ch; int main()
sort_search ss; {complex s1(10,25),s2(20,35),s3;
do int a=10;
{cout<<"sorting and searchimg"<<endl; s3.add(a,s1);
cout<<"main menu"<<endl; s3.disp();
cout<<"1.sort"<<endl; s3.add(s1,s2);
cout<<"2.search"<<endl; s3.disp();
cout<<"3.quit"<<endl; }
cout<<"enter your choice"<<endl; 16. Imagine a tollbooth at a bridge. Cars
cin>>ch; passing by the booth are expected to pay 50
if(ch==1) cent toll. Mostly they do, but sometimes a car
{ss.sort();} goes by without paying. The tollbooth keeps
else if(ch==2) track of the number of cars that have gone
{ss.search();} by, and of the total amount of money
}while(ch<3); collected. Model this tollbooth with a class
} called tollBooth. The two data items are-
15.Write a C++ program to create a class type unsigned int to hold the total number of
called Complex and implement the following cars and type double to hold the total
overloading functions ADD that returns a amount of money collected. A constructor
complex(class object) number: initializing both types to 0 and a member
ADD (a,s2)- where a is an integer(real part) function called payingCar() which
and s2 is a complex(class object) number. increments the car total and adds 50 to the
ADD (s1,s2)-where s1 and s2 are cash total. Another function, called
complex(class object) numbers. nopayCar(), increments the car total but
#include<iostream> adds nothing to the cash total. Finally, a
using namespace std; member function called display() displays
class complex the two totals. Make appropriate member
{ int rp; functions const.
int ip; Write a main function to test the class and its
public: functions. This program should allow the
complex() user to press one keyto count a paying car
{} and another to count a nonpaying car.
complex(int x,int y) Pressing the Esc(e) key shouldcause the
{ rp=x;ip=y;} program to print out the total cars and total
complex add(int a,complex s1) cash and then exit.
{ complex c; #include<iostream.h>
c.rp=a+s1.rp; class tollbooth
c.ip=s1.ip; {unsigned int p,n;
double a;
return c;
public:
} tollbooth()
complex add (complex s1,complex s2) {p=0;n=0;}
{ return complex((s1.rp+s2.rp),(s1.ip+s2.ip));
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
7

void paying_car() for(i=0;i<n;i++)


{p++; e[i].putData();
a=p*50; } }
void nonpay_car() 18.Array of objects - 2
{n++; } //Array of object - avg of 10 distances //
void display() #include<iostream.h>
{cout<<"No of paying cars "<<p; class distance
cout<<"\nNo of non-paying cars "<<n; { int feet;
cout<<"\ntotal cars "<<n+p; float inches;
cout<<"\namt collected "<<a; } public:
}; void getdata()
void main() {cout<<"\nEnter feet and inches ; ";
{ tollbooth t; cin>>feet>>inches;}
char c; void putdata()
cout<<"enter p/P for paying cars n/N for non- {cout<<endl<<feet<<"\t"<<inches;}
paying cars\n"; void avgdistance(distance *d) //void
do avgdistance(class distance d)
{cin>>c; {int i;
if(c=='p'||c=='P') int totalfeet=0;
t.paying_car(); float totalinches=0;
else if(c=='n'||c=='N') float avgdistancefeet,avgdistanceinches;
t.nonpay_car(); for(i=0;i<3;i++)
}while(c!='e'); {totalfeet+=d[i].feet;
t.display(); totalinches+=d[i].inches; }
} totalfeet+=(totalinches/12);
17.Array of objects - 1 totalinches=totalinches%12;
#include<iostream.h> avgdistancefeet=(float)totalfeet/3;
#include<iomanip.h> avgdistanceinches=totalinches/3;
using namespace std; cout<<endl<<"The average distance is
class employee ..."<<avgdistancefeet<<" feet
{private: "<<avgdistanceinches<<" inches"<<endl; }
int eno; };
char name[20]; int main()
public: {distance d[3];
void getData() for(int i=0;i<3;i++)
{ cin>>eno>>name; d[i].getdata();
} cout<<"\n-------------------------------------------";
void putData() for(i=0;i<3;i++)
{cout<<setw(10)<<eno<<setw(10)<<name<<'\ d[i].putdata();
n';} cout<<"\n-------------------------------------------";
}; d[0].avgdistance(d);
int main() }
{int i,n; OPERATOR OVERLOADING:
employee e[10]; ‗OVERLOADING UNARY OPERATORS‘
cout<<"enter number of employee "; 19.Overloading unary minus:
cin>>n; #include<iostream>
for(i=0;i<n;i++)
using namespace std;
e[i].getData();
cout<<setiosflags(ios::left); class space
cout<<setw(10)<<"Employye {int x;
no"<<setw(10)<<"Employee name\n"; int y;
cout<<setw(10)<<"___"<<setw(10)<<"__ \n"; int z;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
8

public: ++c2; //increment c2


void getdata(int a,int b,int c); ++c2; //increment c2
void display(void); cout << “\nc1=” << c1.get_count(); //display
void operator-(); again
}; cout << “\nc2=” << c2.get_count() << endl;
void space::getdata(int a,int b,int c) return 0;
{x=a; }
y=b; 21.Overloading ++ operator with a return
z=c;} type for overloaded operator function:
void space::display(void) #include <iostream>
{cout<< x <<" "; using namespace std;
cout<< y <<" "; class Counter
cout<< z <<"\n";} {private:
void space:: operator-() unsigned int count; //count
{x=-x; public:
y=-y; Counter() : count(0) //constructor
z=-z;} {}
int main() unsigned int get_count() //return count
{space s; { return count; }
s.getdata(10,-20,30); Counter operator ++ () //increment count
cout<<"s: "; {++count; //increment count
s.display(); Counter temp; //make a temporary Counter
-s; temp.count = count; //give it same value as this
cout<<" s : "; obj
s.display(); return temp; //return the copy}
return 0;} };
20.Overloading ++ operator without a return int main()
type for overloaded operator function: {Counter c1, c2; //c1=0, c2=0
#include <iostream> cout << “\nc1=” << c1.get_count(); //display
using namespace std; cout << “\nc2=” << c2.get_count();
class Counter ++c1; //c1=1
{private: c2 = ++c1; //c1=2, c2=2
unsigned int count; //count cout << “\nc1=” << c1.get_count(); //display
public: again
Counter() : count(0) //constructor cout << “\nc2=” << c2.get_count() << endl;
{} return 0;
unsigned int get_count() //return count }
{ return count; } 22.Program to create nameless temporary
void operator ++ () //increment (prefix) objects(anonymous object):
{++count;} #include <iostream>
}; using namespace std;
int main() class Counter
{Counter c1, c2; //define and initialize {private:
cout << “\nc1=” << c1.get_count(); //display unsigned int count; //count
cout << “\nc2=” << c2.get_count(); public:
++c1; //increment c1 Counter() : count(0) //constructor no args
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
9

{} { //return an unnamed temporary


Counter(int c) : count(c) //constructor, one arg return Counter(count++); //object initialized to
{} this count, then increment count
unsigned int get_count() //return count }
{ return count; } };
Counter operator ++ () //increment count int main()
{++count; // increment count, then return { Counter c1, c2; //c1=0, c2=0
return Counter(count); // an unnamed temporary cout << “\nc1=” << c1.get_count(); //display
object cout << “\nc2=” << c2.get_count();
} // initialized to this count ++c1; //c1=1
}; c2 = ++c1; //c1=2, c2=2 (prefix)
int main() cout << “\nc1=” << c1.get_count();
{Counter c1, c2; //c1=0, c2=0 cout << “\nc2=” << c2.get_count();
cout << “\nc1=” << c1.get_count(); //display c2 = c1++; //c1=3, c2=2 (postfix)
cout << “\nc2=” << c2.get_count(); cout << “\nc1=” << c1.get_count();
++c1; //c1=1 cout << “\nc2=” << c2.get_count() << endl;
c2 = ++c1; //c1=2, c2=2 return 0;
cout << “\nc1=” << c1.get_count(); //display }
again OVERLOADING BINARY OPERATORS:
cout << “\nc2=” << c2.get_count() << endl; 24.Overloading ‗+‘ operator to add to two
return 0; complex numbers:
} #include<iostream>
23.Overloading both postfix and prefix ++ using namespace std;
operators: class complex
#include <iostream> { float x;
using namespace std; float y;
class Counter public:
{private: complex()
unsigned int count; //count {}
public: complex(float real,float imaginary)
Counter() : count(0) //constructor no args { x=real;
{} y=imaginary;
Counter(int c) : count(c) //constructor, one }
arg complex operator+(complex);
{} void display(void);
unsigned int get_count() const //return };
count complex complex :: operator + (complex c)
{ return count; } { complex temp;
Counter operator ++ () //increment count temp.x=x+c.x;
(prefix) temp.y=y+c.y;
{ //increment count, then return return temp;
return Counter(++count); //an unnamed }
temporary object void complex :: display(void)
} //initialized to this count {cout<< x << " + i "<< y <<"\n";
Counter operator ++ (int) //increment count }
(postfix) int main()
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
10

{ complex c1,c2,c3; class Polar


c1=complex(2.5,3.5); { double a,r;
c2=complex(1.6,2.7); public:
c3=c1+c2; Polar() : a(0), r(0) {}
c3.display(): Polar(double x, double y) : a(x), r(y) {}
return 0; void read()
} { cout<<"\n\tAngle(In Degree): ";
25.Overloading '+' operator to add two time cin>>a;
objects: cout<<"\n\tRadius: ";
#include <iostream> cin>>r;
using namespace std; }
class time Polar operator+(Polar);
{ private: void show()
int hrs, mins, secs; { cout<<"("<<a<<","<<r<<")"; }
public: };
time() : hrs(0), mins(0), secs(0) //no-arg Polar Polar::operator+(Polar m)
constructor { double x1,y1,x2,y2,x3,y3;
{ } //3-arg constructor Polar res;
time(int h, int m, int s) : hrs(h), mins(m), secs(s) x1 = r*cos(a*3.14/180);
{} y1 = r*sin(a*3.14/180);
void display() //format 11:59:59 x2 = m.r*cos(m.a*3.14/180);
{ cout << hrs << “:” << mins << “:” << secs; } y2 = m.r*sin(m.a*3.14/180);
time operator + (time t2) //add two times x3 = x1 + x2;
{ int s = secs + t2.secs; //add seconds y3 = y1 + y2;
int m = mins + t2.mins; //add minutes res.a = atan(y3/x3) * (180/3.14);
int h = hrs + t2.hrs; //add hours res.r = sqrt(x3*x3 + y3*y3);
if( s > 59 ) //if secs overflow, return(res);
{ s -= 60; m++; } // carry a minute }
if( m > 59 ) //if mins overflow, int main()
{ m -= 60; h++; } // carry an hour { Polar p1,p2,p3;
return time(h, m, s); //return temp value} double x,y;
}; cout<<"\nEnter Co-ordinate-1: ";
int main() p1.read();
{ time time1(5, 59, 59); //create and initialze cout<<"\nEnter Co-ordinate-1: ";
time time2(4, 30, 30); // two times p2.read();
time time3; //create another time p3 = p1 + p2; // Long Int to Time
time3 = time1 + time2; //add two times Conversion Through Constructor
cout << “\ntime3 = “; time3.display(); //display cout<<"\n\nP1: ";
result p1.show();
cout << endl; cout<<"\nP2: ";
return 0;} p2.show();
26. Overloading ‗+‘ operator to add two cout<<"\n\nAdded Polar Result: ";
Polar coordinates objects. p3.show();
#include <iostream> return 0;}
#include <cmath> 27.Overloading '-' operator to substract two
using namespace std; distance objects:
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
11

#include <iostream> i += 12.0; //by 12.0 and


using namespace std; f--; //decrease feet by 1
class Distance //English Distance class } //return a temporary Distance
{ private: return Distance(f,i); //initialized to difference
int feet; }
float inches; int main()
public: //constructor (no args) {Distance dist1, dist3; //define distances
Distance() : feet(0), inches(0.0) dist1.getdist(); //get dist1 from
{ } //constructor (two args) user
Distance(int ft, float in) : feet(ft), inches(in) Distance dist2(3, 6.25); //define, initialize
{} dist2
void getdist() //get length from user dist3 = dist1 - dist2; //subtract
{cout << “\nEnter feet: “; cin >> feet; //display all lengths
cout << “Enter inches: “; cin >> inches; cout << “\ndist1 = “; dist1.showdist();
} cout << “\ndist2 = “; dist2.showdist();
void showdist() //display distance cout << “\ndist3 = “; dist3.showdist();
{ cout << feet << “\‟-” << inches << „\”‟; } cout << endl;
Distance operator + ( Distance ); //add two }
distances 28.Overloading ‗+‘ operator to add to two
Distance operator - ( Distance ); //subtract distance objects:
two distances #include <iostream>
}; using namespace std;
//add d2 to this distance class Distance //English Distance class
Distance Distance::operator + (Distance d2) {private:
//return the sum int feet;
{ int f = feet + d2.feet; float inches;
//add the feet public: //constructor (no args)
float i = inches + d2.inches; Distance() : feet(0), inches(0.0)
//add the inches {} //constructor (two args)
if(i >= 12.0) /if total exceeds 12.0, Distance(int ft, float in) : feet(ft), inches(in)
{ //then decrease inches {}
i -= 12.0; //by 12.0 and void getdist() //get length from user
f++; //increase feet by 1 {cout << “\nEnter feet: “; cin >> feet;
} //return a temporary Distance cout << “Enter inches: “; cin >> inches;
return Distance(f,i); //initialized to sum }
} void showdist() const //display distance
//subtract d2 from this dist { cout << feet << “\‟-” << inches << „\”‟; }
Distance Distance::operator - (Distance d2) Distance operator + ( Distance ) const;
//return the diff //add 2 distances
{int f = feet - d2.feet; //subtract };
the feet //add this distance to d2
float i = inches - d2.inches; //subtract Distance Distance::operator + (Distance d2)
the inches const //return sum
if(i < 0) //if inches less {int f = feet + d2.feet; //add the feet
than 0, float i = inches + d2.inches; //add the inches
{ //then increase inches if(i >= 12.0) //if total exceeds 12.0,
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
12

{ //then decrease inches };


i -= 12.0; //by 12.0 and int main()
f++; //increase feet by 1 {String s1 = “\nMerry Christmas! “; //uses
} //return a temporary Distance constructor 2
return Distance(f,i); //initialized to sum String s2 = “Happy new year!”;
} //uses constructor 2
int main() String s3; //uses constructor 1
{Distance dist1, dist3, dist4;//define distances s1.display(); //display strings
dist1.getdist(); //get dist1 from s2.display();
user s3.display();
Distance dist2(11, 6.25);//define, initialize dist2 s3 = s1 + s2; //add s2 to s1,
dist3 = dist1 + dist2; //single „+‟ operator //assign to s3
dist4 = dist1 + dist2 + dist3;//multiple „+‟ s3.display(); //display s3
operators cout << endl;
//display all lengths return 0;
cout << “dist1 = “; dist1.showdist(); }
cout << “dist2 = “; dist2.showdist(); 30. Overloaded arthimetic operators to work
cout << “dist3 = “; dist3.showdist(); with type int:
cout << “dist4 = “; dist4.showdist(); #include <iostream>
} using namespace std;
29.Overloading ‗+‘ operator to concatenate #include <process.h> //for exit()
two strings: class Int
#include <iostream> {private:
using namespace std; int i;
#include <string.h> //for strcpy(), strcat() public:
#include <stdlib.h> //for exit() Int() : i(0) //no-arg constructor
class String //user-defined string type {}
{enum { SZ=80 }; //size of String objects Int(int ii) : i(ii) //1-arg constructor
char str[SZ]; //holds a string { } // (int to Int)
public: void putInt() //display Int
String() //constructor, no args { cout << i; }
{ strcpy(str, “”); } void getInt() //read Int from kbd
String( char s[] ) //constructor, one arg { cin >> i; }
{ strcpy(str, s); } operator int() //conversion operator
void display() const //display the String { return i; } // (Int to int)
{ cout << str; } Int operator + (Int i2) //addition
String operator + (String ss) const //add Strings { return checkit( long double(i)+long double(i2)
{String temp; //make a temporary String ); }
if( strlen(str) + strlen(ss.str) < SZ ) Int operator - (Int i2) //subtraction
{strcpy(temp.str, str); //copy this string to temp { return checkit( long double(i)-long double(i2)
strcat(temp.str, ss.str); //add the argument string ); }
} Int operator * (Int i2) //multiplication
else { return checkit( long double(i)*long double(i2)
{ cout << “\nString overflow”; exit(1); } ); }
return temp; //return temp String Int operator / (Int i2) //division
} { return checkit( long double(i)/long double(i2)
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
13

); } height = hei;
Int checkit(long double answer) //check results }
{if( answer > 2147483647.0L || answer < - // Overload + operator to add two Box
2147483647.0L ) objects.
{ cout << “\nOverflow Error\n”; exit(1); } Box operator+(const Box& b) {
return Int( int(answer) ); Box box;
} box.length = this->length + b.length;
}; box.breadth = this->breadth + b.breadth;
int main() box.height = this->height + b.height;
{Int alpha = 20; return box;
Int beta = 7; }
Int delta, gamma; };
gamma = alpha + beta; //27 int main( )
cout << “\ngamma=”; gamma.putInt(); { Box Box1; // Declare Box1 of type Box
gamma = alpha - beta; //13 Box Box2; // Declare Box2 of type Box
cout << “\ngamma=”; gamma.putInt(); Box Box3; // Declare Box3 of type Box
gamma = alpha * beta; //140 double volume = 0.0; // Store the volume of
cout << “\ngamma=”; gamma.putInt(); a box here
gamma = alpha / beta; //2 // box 1 specification
cout << “\ngamma=”; gamma.putInt(); Box1.setLength(6.0);
delta = 2147483647; Box1.setBreadth(7.0);
gamma = delta + alpha; //overflow error Box1.setHeight(5.0);
delta = -2147483647; // box 2 specification
gamma = delta - alpha; //overflow error Box2.setLength(12.0);
cout << endl; Box2.setBreadth(13.0);
return 0;} Box2.setHeight(10.0);
31.Overloading '+' operator to add // volume of box 1
dimensions of two box objects: volume = Box1.getVolume();
#include <iostream> cout << "Volume of Box1 : " << volume
using namespace std; <<endl;
class Box { // volume of box 2
private: volume = Box2.getVolume();
double length; // Length of a box cout << "Volume of Box2 : " << volume
double breadth; // Breadth of a box <<endl;
double height; // Height of a box // Add two object as follows:
public: Box3 = Box1 + Box2;
double getVolume(void) { // volume of box 3
return length * breadth * height; volume = Box3.getVolume();
} cout << "Volume of Box3 : " << volume
void setLength( double len ) { <<endl;
length = len; }
} 32.Overloading '<' operator to compare two
void setBreadth( double bre ) { distance objects:
breadth = bre; #include <iostream>
} using namespace std;
void setHeight( double hei ) { class Distance //English Distance class
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
14

{private: char str[SZ]; //holds a string


int feet; public:
float inches; String() //constructor, no args
public: //constructor (no args) { strcpy(str, “”); }
Distance() : feet(0), inches(0.0) String( char s[] ) //constructor, one arg
{ } //constructor (two args) { strcpy(str, s); }
Distance(int ft, float in) : feet(ft), inches(in) void display() const //display a String
{} { cout << str; }
void getdist() //get length from user void getstr() //read a string
{cout << “\nEnter feet: “; cin >> feet; { cin.get(str, SZ); }
cout << “Enter inches: “; cin >> inches; bool operator == (String ss) const //check for
} equality
void showdist() const //display distance {return ( strcmp(str, ss.str)==0 ) ? true : false;}
{ cout << feet << “\‟-” << inches << „\”‟; } };
bool operator < (Distance) const; //compare int main()
distances {String s1 = “yes”;
}; String s2 = “no”;
//compare this distance with d2 String s3;
bool Distance::operator < (Distance d2) const cout << “\nEnter „yes‟ or „no‟: “;
//return the sum s3.getstr(); //get String from user
{float bf1 = feet + inches/12; if(s3==s1) //compare with “yes”
float bf2 = d2.feet + d2.inches/12; cout << “You typed yes\n”;
return (bf1 < bf2) ? true : false;} else if(s3==s2) //compare with “no”
int main() cout << “You typed no\n”;
{Distance dist1; //define Distance dist1 else
dist1.getdist(); //get dist1 from user cout << “You didn‟t follow instructions\n”;
Distance dist2(6, 2.5); //define and initialize return 0;}
dist2 34.Overloading arithmetic assignment
//display distances operator ‗+=‘ to add two distance objects:
cout << “\ndist1 = “; dist1.showdist(); #include <iostream>
cout << “\ndist2 = “; dist2.showdist(); using namespace std;
if( dist1 < dist2 ) //overloaded „<‟ operator class Distance //English Distance class
cout << “\ndist1 is less than dist2”; {private:
else int feet;
cout << “\ndist1 is greater than (or equal to) float inches;
dist2”; public: //constructor (no args)
cout << endl; Distance() : feet(0), inches(0.0)
return 0;} { } //constructor (two args)
33.Overloading ‗==‘ operators to compare Distance(int ft, float in) : feet(ft), inches(in)
two strings: {}
#include <iostream> void getdist() //get length from user
using namespace std; {cout << “\nEnter feet: “; cin >> feet;
#include <string.h> //for strcmp() cout << “Enter inches: “; cin >> inches;
class String //user-defined string type }
{private: void showdist() const //display distance
enum { SZ = 80 }; //size of String objects { cout << feet << “\‟-” << inches << „\”‟; }
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
15

void operator += ( Distance ); cout << “Element “ << j << “ is “ << temp <<
}; endl;
//add distance to this one }
void Distance::operator += (Distance d2) return 0;}
{feet += d2.feet; //add the feet 36.Example program for both left and right
inches += d2.inches; //add the inches hand side calling of a function:
if(inches >= 12.0) //if total exceeds 12.0, #include <iostream>
{ //then decrease inches using namespace std;
inches -= 12.0; //by 12.0 and #include <process.h> //for exit()
feet++; //increase feet const int LIMIT = 100; //array size
} //by 1 class safearay
} {private:
int main() int arr[LIMIT];
{Distance dist1; //define dist1 public:
dist1.getdist(); //get dist1 from user int& access(int n) //note: return by reference
cout << “\ndist1 = “; dist1.showdist(); {if( n< 0 || n>=LIMIT )
Distance dist2(11, 6.25); //define, initialize { cout << “\nIndex out of bounds”; exit(1); }
dist2 return arr[n];
cout << “\ndist2 = “; dist2.showdist(); }
dist1 += dist2; //dist1 = dist1 + dist2 };
cout << “\nAfter addition,”; int main()
cout << “\ndist1 = “; dist1.showdist(); {safearay sa1;
cout << endl; for(int j=0; j<LIMIT; j++) //insert elements
return 0;} sa1.access(j) = j*10; //*left* side of equal sign
35.Overloading subscript operator ‗[]‘ : for(j=0; j<LIMIT; j++) //display elements
#include <iostream> {int temp = sa1.access(j); //*right* side of equal
using namespace std; sign
#include <process.h> //for exit() cout << “Element “ << j << “ is “ << temp <<
const int LIMIT = 100; //array size endl;}
class safearay return 0;}
{private: 37.Overloading '<<' Operator to print time
int arr[LIMIT]; object:
public: #include<iostream.h>
int& operator [](int n) //note: return by class time
reference { int hr,min,sec;
{if( n< 0 || n>=LIMIT ) public:
{ cout << “\nIndex out of bounds”; exit(1); } time()
return arr[n]; { hr=0, min=0; sec=0; }
} time(int h,int m, int s)
}; { hr=h, min=m; sec=s; }
int main() friend ostream& operator << (ostream&out,
{safearay sa1; time &tm); //overloading '<<' operator
for(int j=0; j<LIMIT; j++) //insert elements };
sa1[j] = j*10; //*left* side of equal sign ostream& operator<< (ostream&out, time &tm)
for(j=0; j<LIMIT; j++) //display elements //operator function
{int temp = sa1[j]; //*right* side of equal sign { out << "Time is " << tm.hr << "hour : "
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
16

<<tm.min<< "min : " <<tm.sec<< "sec"; cout <<" multiplication value : " << endl;
return out;} for (i=0 ; i<m; i++)
int main() { for (j=0 ; j<n ; j++)
{ time tm(3,15,45); { f. a [i] [j]= 0;
cout<< tm; } for (int k=0; k<u.m ; k++)
38. Overloading operations on a matrix. { f. a[i] [j]= f.a[i] [j]+(a [i] [k]*u.a[k][j]);
#include<iostream.h> }
int i,j,k,t,u,c; cout<<f.a[i] [j]<<"\t";o
class mat }
{int m,n; cout<< endl;}
int a [3] [3]; }
public: iInt main()
mat() {} { mat p,q;
void getdata (); p.getdata();
void operator +(mat); q.getdata();
void operator -(mat); p+q;
void operator *(mat); p-q;
}; p*q;
void mat :: getdata() }
{cout<<"enter row and col"; PROGRAMS BASED ON DATA
cin>>m>>n; CONVERSION:
cout <<" enter the elements of matnx a"; 39.Program to show how compiler implicitly
for (i=0; i<m; i++) converts basic data types.
{for ( j=0; j<n; j++) #include <iostream>
{cin >>a[i][j];} using namespace std;
}} int main()
void mat :: operator +(mat c) { int num1;
{mat d; float num2 = 5.615;
cout <<" addition value" <<endl; num1=num2;//float convertion to int
for (i=0; i<m; i++) cout<<num1;
{for (j=0; j<n; j++) }
{d.a[i] [j] =a[i] [j]+c.a[i] [j]; 40.Program to show how a compiler
cout <<d. a[i] [j] <<"\t"; explicitly converts basic data types.
}cout << endl; #include <iostream>
}} using namespace std;
void mat :: operator -(mat c) int main()
{mat d; { int num1;
cout <<" subtracted value" <<endl; float num2 = 5.615;
for (i=0; i<m; i++) num1=static_cast<int>(num2); //float
{for (j=0; j<n; j++) convertion to int
{d.a[i] [j] =a[i] [j]-c.a[i] [j]; cout<<num1;
cout <<d. a[i] [j] <<"\t"; }
}cout << endl; 41.Conversion from basic to user defined
}} data type.
void mat :: operator *(mat u) #include <iostream>
{mat f; using namespace std;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
17

const float MeterToFloat=3.280833; Distance(int ft, float in) //two arguments


class Distance constructor
{ int feets; { feet=ft;
float inches; inches=in; }
public: operator float() //overloaded casting operator
Distance() //Distance Constructor { float feetinfractions=inches/12;
{ feets=0; feetinfractions+=float(feet);
inches=0.0; return (feetinfractions/MeterToFloat); }
} };
Distance(float numofmeters) //Single int main()
Parameter constructor { int feet;
{ float feetsinfloat= MeterToFloat * float inches;
numofmeters; cout <<"Enter distance in Feet and Inches.";
feets=int(feetsinfloat); cout<<"\nFeet:";
inches=12*(feetsinfloat-feets); cin>>feet;
} cout<<"Inches:";
void displaydist() // Method to display cin>>inches;
converted values Distance dist(feet, inches);
{ cout<<"Converted Value is: "<<feets<<"\' float meters=dist;
feets<<" // This will call overloaded casting operator
inches"<<inches<<'\"'<<" inches."; cout<<"Converted Distance in Meters is: "<<
} meters;
}; }
int main() 43.Progarm to convert user defined class of
{ cout <<"Float to distance types feet,inches to class of type
conversion.\n**********************\n"; metres,centimetres class and vice versa:-
float meters; #include<iostream>
cout<<"Enter values in meter:"; #include<math.h>
cin >>meters; using namespace std;
Distance distance = meters; class distancemetre
distance.displaydist(); { private:
} int metre;
42.Conversion from user defined data type to float centimetre;
basic data type public:
#include <iostream> distancemetre()// defualt constructor
using namespace std; { metre=0;
const float MeterToFloat=3.280833; centimetre=0.0; }
// Meter to feet distancemetre(int m,float c)//paramatric
class Distance constructor
{ int feet; { metre=m;
float inches; centimetre=c; }
public: int getmetre()
Distance()// Default Constructor? { return metre; }
{ feet=0; int getcentimetre()
inches=0.0; { return centimetre; }
} void display()
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
18

{ cout<<"Metre= break;
"<<metre<<endl<<"Centimetre= case 2:
"<<centimetre<<endl;} cout<<"Enter feet of int value ";
}; cin>>a;
class distancefeet cout<<"Enter inches of float or int value ";
{ private: cin>>b;
int feet; distancefeet df1(a,b);
float inch; df1.display();
public: distancemetre dm1;
distancefeet():feet(0),inch(0) dm1=df1;
{} dm1.display();
distancefeet(int f,float i) break;
{ feet=f; }
inch=i; } }
distancefeet(distancemetre d) 44. Conversion between C strings and string
{ float objects:
in=(d.getmetre()*100+d.getcentimetre())/2.54; #include<iostream>
feet=in/12; #include<string.h>
inch=fmod(in,12); } using namespace std;
operator distancemetre() class String
{ float a=feet*12+inch; { private:
int m=(a*2.54)/100; enum{sz=80};
float cm=(a*2.54)-(m*100); char str[sz]
return distancemetre(m,cm); } public:
void display() String()
{ cout<<"Feet= "<<feet<<endl<<"inches= { str[0]='\0'; }
"<<inch<<endl; } String(char a[])
}; { strcpy(str,a); }
int main() void get()
{ int n; { cin.getline(str,80); }
int a; void display()
float b; { cout<<"string that you entered is
cout<<"Enter 1 to convert metre to feet type or "<<endl<<str<<endl; }
2 to convert feet to metre type"; operator char*()//conversion operator
cin>>n; { return str; }
switch(n) };
{ case 1: int main()
cout<<"Enter metre of int value "; { char a[30];//normal c string
cin>>a; cout<<"Enter the string";
cout<<"Enter centimetre of float or int value "; cin.getline(a,30);/*gets the input as char array
cin>>b; and stores them in a*/
distancemetre dm(a,b); String s=a;//uses parametric construtor
dm.display(); s.display();
distancefeet df(dm);/*conversion takes place String s1="bonne annee!!!";
in constructor char b[30];
df.display(); strcpy(b,static_cast<char*>(s1));/*convrsion
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
19

using overloaded operator*/ };


cout<<"string that changed from string obj to class time24
char array"<<endl; { private:
cout<<b<<endl; int hour24;
} int min24;
45.Program to convert time12 to time24 and int seconds24;
vice verasa: (user defined to user public:
defined type conversion) time24()
#include<iostream> {}
#include<string.h> time24(int h,int m,int s)
using namespace std; { hour24=h;
class time12 min24=m;
{ private: seconds24=s; }
char meridian[2]; time24(time12 t12)
int hours12,minutes12,seconds12; {if(t12.getpm_am()=="pm")
public: { if(t12.gethours12()==12)
time12() { hour24=t12.gethours12(); }
{} else
time12(char a[],int h,int m,int s) { hour24=t12.gethours12()+12; }
{ strcpy(meridian,a); min24=t12.getminutes12();
hours12=h; seconds24=t12.getseconds12(); }
minutes12=m; else
seconds12=s; { if(t12.gethours12()==12)
} { hour24=00; }
void get12() else
{ cout<<"Enter hours= "; { hour24=t12.gethours12(); }
cin>>hours12; min24=t12.getminutes12();
cout<<"Enter minutes= "; seconds24=t12.getseconds12();
cin>>minutes12; }}
cout<<"Enter seconds= "; void gettime24()
cin>>seconds12; { cout<<"Enter hours= ";
cout<<"Enter pm or am"; cin>>hour24;
cin>>meridian; } cout<<"Enter minutes= ";
string getpm_am() cin>>min24;
{ return meridian; } cout<<"Enter seconds= ";
int gethours12() cin>>seconds24;}
{ return hours12; operator time12()
} { int h,m,s;
int getminutes12() char a[2];
{ return minutes12; } if(hour24==12)
int getseconds12() { h=12;
{ return seconds12; } strcpy(a,"pm"); }
void display12()const if(hour24<12)
{ cout<<"Time in 12 format is"<<endl; { h=hour24;
cout<<hours12<<"-"<<minutes12<<"- strcpy(a,"am");
"<<seconds12<<" "<<meridian<<endl; } if(hour24>12)
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
20

{ h=hour24-12; sec=i%60;
strcpy(a,"pm"); } }
if(hour24==0) disp()
{cout<<hrs<<":"<<min<<":"<<sec;
{ strcpy(a,"am");
}
h=12; } };
m=min24; int main()
s=seconds24; {long int l;
return time12(a,h,m,s);} cin>>l;
} tim m(l);
void display24() m.disp();
return 0;}
{cout<<"Time in 24 format is"<<endl;
POINTERS
cout<<hour24<<"-"<<min24<<"- 47. GENERIC POINTER
"<<seconds24<<endl; } Program to show the usage of generic(void)
}; pointers.
int main() #include <iostream>
{ int n; using namespace std;
cout<<"Enter 1 to convert 12 to 24 or 2 for int main()
{ int *a,a1=5;
vice verse";
float* b,b1=10;
cin>>n; void *c;
switch(n) b=&b1;
{ case 1: a=&a1;
time12 t12; cout<<"\nThe value of the integer pointer is:
t12.get12(); "<<*a;
cout<<"\nThe value of the float pointer is:
t12.display12();
"<<*b;
time24 t24(t12); c=&a1;
t24.display24(); cout<<"The value of the generic pointer can be
break; ( pointing to an integer
case 2: ):"<<*static_cast<int*>(c);
time24 t24a; c=&b1;
t24a.gettime24(); cout<<" and (pointing to a float ):
"<<*static_cast<float*>(c);
t24a.display24();
a=reinterpret_cast<int*>(b);
time12 t12a=t24a; cout<<"\nThe value of a float pointer pointing
t12a.display12(); to an integer is: "<<*b;
break; }
} The value of the integer pointer is: 5
} The value of the float pointer is: 10
46. Conversion of basic to user defined data The value of the generic pointer can be (
type: pointing to an integer ): 5 and (pointing to a
#include<iostream.h> float ): 10
class tim The value of a float pointer pointing to an
{int hrs,min,sec; integer is: 10
public: 48. POINTERS AND ARRAYS
tim() {hrs=0;min=0;sec=0;} Program to assign an int array and a
tim(long int i) character array to an int pointer and
{min=i/60; character pointer respectively and
min=min%60; manipulating them using unary operator
hrs=i/3600; ‗++‖ :

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
21

#include <iostream> BEFORE: 5


using namespace std; AFTER: 6
int main() SECOND TYPE:
{ int a[]={1,2,3,4,5,6,7}; BEFORE: 6
int *ptr; AFTER: 7
ptr=a;
cout<<"Manipulations done: "; 50.CONSTANT POINTER AND POINTER
cout<<'\n'<<*ptr; TO A CONSTANT
cout<<'\n'<<*ptr++; #include <iostream>
cout<<'\n'<<*(++ptr); using namespace std;
cout<<'\n'<<(*ptr)++; int main() {
cout<<'\n'<<*ptr<<'\n'; int a[]={1,2,3,4,5};
char s[]="Helloo"; const int* ptr=a;
char*sptr; int* const p=a;
sptr=s; cout<<*ptr<<" ";
cout<<'\n'<<*sptr; cout<<*(++ptr)<<" ";
cout<<'\n'<<sptr; cout<<'\n'<<*p<<" "<<(*p)++;
cout<<'\n'<<*sptr++; return 0;
cout<<'\n'<<*++sptr; }
} 12
Manipulations done: 21
1 51. DYNAMIC MEMORY ALLOCATION
1 #include <iostream>
3 #include<string.h>
3 using namespace std;
4 int main() {
char s[]="HELLO ALL.",*p;
H int l;
Helloo l=strlen(s);
H p=new char[l+1];
l strcpy(p,s);
49 POINTERS AND CALL BY cout<<p;
REFERENCES cout<<*p;
#include <iostream> delete[]p;
using namespace std; return 0;
void change(int &a) }
{ a++;} HELLO ALL.
void changeptr(int *a) H
{ (*a)++;} 52.THIS POINTER
int main() Program to find the maximum of two
{ int x=5; numbers using ‗this‘ pointer :
cout<<"\nFIRST TYPE: "; #include<iostream.h>
cout<<"\nBEFORE: "<<x; using namespace std;
change(x); class max
cout<<"\nAFTER: "<<x; { int a;
cout<<"\nSECOND TYPE: "; public:
cout<<"\nBEFORE: "<<x; void getdata()
changeptr(&x); { cout<<"Enter the Value :";
cout<<"\nAFTER: "<<x; cin>>a;
return 0; }
} max &greater(max &x)
FIRST TYPE: { if(x.a>=a)
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
22

return x; {cout<<"the no is in "<<i+1<<" position\n";


elsereturn *this; flag=1; }
} }
void display() if(flag==0)
{ cout<<"Maximum No. is : "<<a<<endl; cout<<"no not in stack\n";
} }
}; void stack::pop()
main() {if(!isempty())
{ max one,two,three; { top--;
one.getdata(); --size;
two.getdata(); cout<<"stack top is deleted !!";
three=one.greater(two); }
three.display(); else
} cout<<"stack is empty, u cant delete \n";
53. Pointers for stack operations }
Program to perform stack operations such as void stack ::display()
pushing,popping,searching,displaying using { int n=top;
pointers. if(!isempty())
#include<iostream.h> { cout<<"output ";
class stack for(int i=n;i>=0;i--)
{ { cout<<no[i]<<" ";}
int no[10]; }
public: else
int top,size; cout<<"stack is empty, nothing to display\n";
stack() }
{top=-1; void main()
} { stack a;
void push(); stack *ptr=&a;
void pop(); int p,i,o;
void display(); char opt='y';
void search(); clrscr();
int isempty(); cout<<"enter the choice ";
}; while(opt=='y')
int stack::isempty() {
{return (size==0?1:0); cout<<"\n1.insrt\n2.delete\n3.search\n4.
} display\n";
void stack::push() cin>>p;
{cout<<"enter no of elements :"; switch(p)
cin>>size; {case 1:
cout<<"enter elements :\n"; ptr->push();
for(int i=0;i<size;i++) break;
{ cin>>no[i]; case 2:
top++; ptr->pop();
} break;
} case 3:
void stack::search() ptr->search();
{ int m; break;
cout<<"enter the no to be searched: "; case 4:
cin>>m; ptr->display();
int flag=0; break;
for(int i=0;i<size;i++) }
{ if(no[i]==m) cout<<"do u want to continue? ";

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
23

cin>>opt; } numbers using simple inheritance:


} //public access specifier
54.Progam to show the usage of ‗new‘ and #include<iostream>
‗delete‘ operators for char data type. using namespace std;
#include <string.h> class B
#include <iostream.h> { protected:
class String { char *s;
int len; int a,b;
public: public:
String() void getdata()
{s=new char[81]; {cout<<"enter the two numbers"l;
len=80; } cin>>a>>b; }
String(int n) void show()
{s=new char[n + 1];
{cout<<"the numbers you entered are:
len=n; }
String(char *p) “<<a<<b; }
{ len=strlen(p); };
s=new char[len + 1]; class D:public B
strcpy(s, p); } { int c;
String(String &str); public:
~String() {delete []s;} void mul()
void assign (char *str) {
{ c=a*b; }
strcpy(s, str);
len=strlen(str); } void display()
void print() { {cout<<"result="<<c<<endl;}
cout << s << '\n';} };
void concat(String &a, String &b); int main()
}; { D d;
String::String(String &str) { d.getdata();
len=str.len;
s=new char[len + 1]; d.show();
strcpy(s, str.s);} d.mul();
void String::concat(String &a, String &b) d.display();
{ len=a.len + b.len; }
delete []s; Output:
s=new char[len + 1]; enter the two numbers
strcpy(s, a.s);
34
strcat(s, b.s);
strcpy(a.s, "ipek"); 56
} the numbers you entered are
int main() 34
{ char *str="Hello everybody. "; 56
String a(str), b, c("Have a nice day. "), result=1904
both, quote=c; 56. Program to find the product of two
b.assign("How are you? ");
numbers using simple inheritance:
both.concat(a, b);
quote.print(); //private access specifier
a.print(); #include<iostream>
both.print(); using namespace std;
return 0;} class B
INHERITANCE {protected:
55. Program to find the product of two int a,b;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
24

public: cout<<"name : "<<nm<<endl; }


void getdata() };
{ cout<<"enter the two numbers"<<endl; class marks : public student
cin>>a>>b; } {protected:
void show() int s1;
{ cout<<"the numbers you entered are"; int s2;
cout<<a<<endl; int s3;
cout<<b<<endl; } public:
}; void getmarks()
class D:private B { cout<<"enter three subject marks
{ int c; "<<endl;
public: cin>>s1>>s2>>s3;
void mul() }
{ getdata(); void putmarks()
c=a*b;} { cout <<"subject 1:"<<s1<<endl;
void display() cout<<" subject 2 : "<<s2<<endl;
{ show(); cout <<"subject 3:"<<s3<<endl;
cout<<"results="<<c<<endl;} }
}; };
int main() class result : public marks // derived from
{D d; marks
d.mul(); {private:
d.display(); } int t;
Output: float p;
enter the two numbers public:
45 void process()
56 { t= s1+s2+s3;
the numbers you entered are p = t/3.0; }
45 void printresult()
56 { cout<<"total = "<<t<<endl;
result=2520 cout<<"per = "<<p<<endl; }
57. Program to read and display students };
details and marks using ‗Multilevel int main()
Inheritance‘: { result x;
#include<iostream> x.read();
using namespace std; x.getmarks();
class student // base class x.process();
{private: x.display();
int rl; x.putmarks();
char nm[20]; x.printresult();
public: }
void read`() Output:
{ cout<<"enter Roll no and Name "; enter Roll no and Name
cin>>rl>>nm; } 34
void display() Sneha
{ cout <<"Roll NO:"<<rl<<endl; enter three subject marks
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
25

23 enter n value
45 5
34 m=6
Roll No:34 n=5
name: sneha 59. Progam to get the details of an employee
subject 1 : 23 and student and display their details using
subject 2 : 45 ‗Multiple inheritance‘:
subject 3 : 34 #include<iostream.h>
total =102 class emp
{protected:
per = 34
char name[10],gen;
int no,sal,age;
58. Simple program to show how ‗Multiple public:
inheritance‘ works: int g;
#include<iostream> void getdata()
using namespace std; {cout<<"enter the no,name,gen,age and sal";
class base1 cin>>no>>name>>gen>>age>>sal;
cout<<"research interest?";
{ protected: cin>>g; }
int m; void display()
public: {cout<<"empno:"<<no<<"\nname:"<<name<<"
void get_m() \ngen:"<<gen<<"\nage:"<<age<<"\nsal:"<<sal;
{ cout<<"enter m value"<<endl; }
cin>>m; } };
class student
};
{ protected:
class base2 char name[10],dept[10];
{protected: int regno,yr;
int n; float cgpa;
public: public:
void get_n() int g;
{ cout<<"enter n vakue"<<endl; void getdata()
{cout<<"enter name , no,dept,yr,cgpa and
cin>>n; }
research interest:";
}; cin>>name>>regno>>dept>>yr>>cgpa>>g;}
class derived: public base1,public base2 void display()
{ public: {cout<<"name:"<<name<<"\nregno:"<<regno<
void display() <"\ndept"<<dept<<"\nyr:"<<yr<<"\ncgpa"<<cg
{cout<<"m ="<<m<<endl; pa; }
cout<<"n ="<<n<<endl; } };
class research : public emp,public student
}; { public:
int main() void display()
{ derived d1; {emp::display(); }
d1.get_m(); void display1()
d1.get_n(); {student::display(); }
d1.display(); };
void main()
}
{ research q[25];
Output: int i,j,u,v;
enter a value cout<<"no of employees";
6
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
26

cin>>v; int main()


for(i=0;i<v;i++) { Square objS;
{q[i].emp::getdata(); Cube objC;
}
int sqr,cube;
cout<<"enter no of students";
cin>>u; objS.getNumber();
for(j=0;j<u;j++) objS.getSquare();
{q[j].student::getdata(); objS.display();
} objC.getNumber();
for(i=0;i<v;i++) objC.getCube();
{if((q[i].emp::g)==1) objC.display(); }
q[i].display(); }
Output:
for(j=0;j<u;j++)
{if((q[j].student::g)==1) Enetr an integer number:12
q[j].display1(); } 144
} Enter an integer number:5
60. Program to calculate the square and cube 125
of a number using ‗Hierarchical
Inheritance‘: 61.A program to explain‗Hierarchical
#include <iostream> Inheritance‘ by creating a class person and
using namespace std; derving a class student and employee
class Number publicaly from person class.
{ protected: #include <iostream>
int num; using namespace std;
public: class person
void getNumber() { char name[100],gender[10];
{ cout << "Enter an integer number: "; int age;
cin >> num; } public:
void display() void getdata()
{ cout<<num<<endl; } { cout<<"Name: ";
}; cin>>name;
cout<<"Age: ";
//Base Class 1, to calculate square of a number cin>>age;
class Square:public Number cout<<"Gender: ";
{ public: cin>>gender;
void getSquare() }
{ num=num*num; } void display()
void display() { cout<<"Name: "<<name<<endl;
{ cout<<num<<endl; } cout<<"Age: "<<age<<endl;
}; cout<<"Gender: "<<gender<<endl; }
//Base Class 2, to calculate cube of a number };
class Cube:public Number class student: public person
{ public: { char institute[100], level[20];
void getCube() public:
{ num=num*num*num; } void getdata()
void display() { person::getdata();
{ cout<<num<<endl; } cout<<"Name of College/School: ";
}; cin>>institute;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
27

cout<<"Level: "; details of the book and tape respectively


cin>>level; } using ‗Hierarchical Inheritance‘.
void display() #include<iostream>
using namespace std;
{ person::display();
class Publication
cout<<"Name of College/School: { protected:
"<<institute<<endl; string title;
cout<<"Level: "<<level<<endl; } float price;
}; public:
class employee: public person void getdata()
{ char company[100]; { cout<<"\nEnter the title";
cin>>title;
float salary;
cout<<"\n Enter the price "; cin>>price;
public: }
void getdata() void putdata()
{ person::getdata(); { cout<<"\nTitle"<<"\t"<<title;
cout<<"Name of Company: "; cout<<"\nPrice"<<"\t"<<price; }
cin>>company; };
cout<<"Salary: Rs."; class Book:public Publication
{ int page_count;
cin>>salary; }
public:
void display() void getdata()
{ person::display(); { cout<<"\nEnter the book details";
cout<<"Name of Company: Publication::getdata();
"<<company<<endl; cout<<"\n Enter the page count of the book";
cout<<"Salary: Rs."<<salary<<endl; } cin>>page_count; }
void putdata()
};
{ cout<<"\nBook details";
int main() Publication::putdata();
{ student s; cout<<"\n pagecount"<<"\t"<<page_count;
employee e; } };
s.getdata(); class Tape:public Publication
s.display(); { int time;
e.getdata(); public:
void getdata()
e.display();
{ Publication::getdata();
} cout<<"\n Enter the playing time ";
Output: cin>>time;
}
void putdata()
{ cout<<"\n Tape details";
Publication::putdata();
cout<<"\n Playing time"<<"\t"<<time; }
};
int main()
{ int ch;
char op;
do
{ cout<<"1.Book";
cout<<"2.Tape";
62. Program to create a class publication and cout<<"\n enter ur choice";
from that deriving class tape and books cin>>ch;
publicaly which would get and display the
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
28

switch(ch) public:
{ case 1: void getdata()
{ Book B; {cout<<"enter the score in sports
B.getdata();
quota"<<endl;
B.putdata();
break; cin>>score; }
} void displays()
case 2: {cout<<"score in sports quota"<<endl;
{ Tape T; cout<<score<<endl; }
T.getdata(); };
T.putdata(); class result: public marks ,public sports
break;
{private:
} }
cout<<"\nDo you want to continue y/n"; float total;
cin>>op; public:
}while(op=='y'||op=='Y') ; void ans()
} {total=mark1+mark2+score; }
63. Program explaining ‗Hybrid void display()
Inheritance‘. {cout<<"the total score of the student"<<endl;
#include<iostream> cout<<total<<endl;}
using namespace std; };
class student int main()
{ protected: {result r1;
int rollno; r1.getd();
public: r1.getm();
void getd() r1.getdata();
{ cout<<"enter the rollnumber"; r1.ans();
cin>>rollno; } r1.putd();
void putd() r1.displaym();
{ cout<<"rollnumber of the student is"; r1.displays();
cout<<rollno<<endl; } r1.display();}
}; Output:
class marks: public student
{protected:
float mark1,mark2;
public:
void getm()
{cout<<"enter the marks of two
subjects"<<endl;
cin>>mark1>>mark2; }
void displaym()
{cout<<"marks obtained"<<endl;
cout<<mark1<<endl;
cout<<mark2<<endl; } 64. Ambiguity Resolution
}; //over riding in simple inheritance
class sports 64.#include<iostream>
{ protected: using namespace std;
int score; class A
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
29

{ public: n
void display() 66.Program to execrise Inheritance of
{cout<<"A"<<endl;} constructors.
}; #include<iostream>
class B:public A using namespace std;
{ public: class A
void display() { public:
{ cout<<"b"<<endl; } A()
}; {cout<<"a"<<endl; }
int main() A(int a)
{ B a; {cout<<"a(int)"<<endl;}
a.display(); };
a.A::display(); class B:public A
a.B::display(); } { public:
Output: B()
b {cout<<"b"<<endl;}
a B(int a)
b {cout<<"b(int)"<<endl;}
65.Over riding example 2. };
#include<iostream> class C:public B
using namespace std; {public:
class m C()
{public: { cout<<"c"<<endl;}
void display() C(int a)
{cout<<"m"<<endl;} {cout<<"c(int)"<<endl; }
}; };
class n int main()
{ public: {C obj1;
void display() C obj2(5);}
{cout<<"n"<<endl;} Output:
}; a
class p: public m,public n b
{ public: c
void display() a
{cout<<"p"<<endl; b(int)
m::display(); 67. Program to show the order of
n::display();d constructor calling
} When a class is inherited virtually.
}; class Base1
int main() { public:
{p p1; Base1() { cout<<”Base 1”; }
p1.display(); };
} class Base2
Output: { public:
p Base2(){ cout<<”Base2”; }
m };
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
30

class Der:public Base1, virtual public Base2 {add s; //creating objects


{ public: s.getdata();
Der() { cout<<”Derived class”; } cout<<s.sum;
}
};
70. Basic program- 3.
int main()
#include<iostream>
{Der D; return 0; } using namespace std;
class abc
OUTPUT: {int a; //it is understood it is private even it is
Base2 not mentioned so
Base1 protected:
Derived Class int b;
public:
MISCELLANEOUS PROGRAMS - I int c;
68. Basic program- 1. void getanddisp()
#include<iostream> {cin>>a>>b>>c;
using namespace std; cout<<a;
class add cout<<b;
{private: cout<<c; } };
int a,b; //data members int main()
public: {abc d;
int sum; cout<<d.a; //can't accesssinceit is a
void getdata() //member functions privatedata member
{a=5; cout<<d.b; //can't access since it is declared
b=9; in protected
sum=a+b; cout<<d.c; //correct
}
d.getanddisp();
};
return 0;
int main()
{add s; //creating objects }
s.getdata(); 71. Basic program- 4
cout<<s.sum; return0; #include<iostream>
} using namespace std;
69. Basic program- 2. class abc
#include<iostream> {int a,b;
using namespace std; public:
class add void setdata(int c,int d)
{private: {a=c;
int a,b; b=d;
public: }
int sum; void getdata()
void getdata(); //prototyping the {cin>>a>>b;
memberfunctions }
}; void display()
void add:: getdata()//outside the class {cout<<"\n"<<a<<"\n"<<b;
definition } };
{a=5;
int main()
b=9;
sum=a+b; {abc x, v;
} v.setdata(4,8);
int main() cout<<"enter 2 values";
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
31

x.getdata(); display();
v.display(); }
x.display(); };
} int main()
72. Basic program- 5 {abc x, v;
#include<iostream> v.setdata(4,8);
using namespace std; v.display(); //error :display() is private can't
class abc be accessed from main()
{int a,b; x.getdata();
public: return 0; }
void setdata(int c,int d) 74. Basic program- 7.
{a=c; #include<iostream>
b=d; using namespace std;
display();//nesting of member functions class counter
} {int a;
void getdata() static int count;
{cout<<"\n enter 2 nos"; public:
cin>>a>>b; void getdata()
display(); {cout<<”enter a no”;
} cin>>a;
void display() count++;
{cout<<"\n"<<a<<"\n"<<b; }
} }; void display()
int main() {cout<<”a=”<<a;
{abc x, v; }
v.setdata(4,8); static void show() //static member
x.getdata(); function can access only static data
return 0; members
} {cout<<”no of object created”<<count;}
73. Basic program- 6. };
#include<iostream> int counter::count=0; //initialising a static data
using namespace std; member
class abc int main()
{private: {counter a,b, c;
int a,b; a.getdata();
void display() //member a.display();
functions can also be private counter::show();
{ cout<<a<<b; //count=1 accessing static member functions
} b.getdata();
public: b.display();
void setdata(int c,int d) counter::show();
{a=c; //count==2
b=d; c.getdata();
display(); //calling private member c.display();
functions counter::show(); //count=3
} return 0;
void getdata() }
{cin>>a>>b; 75.Program to create Array of objects.

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
32

#include<iostream> static int count; //static variable


using namespace std; public:
class abc counter() //default constructor
{int a,b; {a=0;
public: count++;}
void getdata() counter(int b) //parametric constructor and
{cin>>a; it can't be written without a default
} constructor
void display() {a=b;
{cout<<"\n"<<a; count++;}
} }; void getdata()
int main() {cout<<"enter a no";
{abc x[5];//creating array of objects cin>>a;
cout<<"enter 5 no's"; }
for(int i=0;i<5;i++) void display()
{ x[i].getdata(); {cout<<"\n a="<<a<<"\tno of objects
} created:"<<count;}
for(int i=0;i<5;i++) };
{ x[i].display();} int counter::count=0; //initialising static data
return 0;} member
76. Passing an object as parameter for int main()
adding two objects. {counter c;
#include<iostream> c.getdata();
using namespace std; c.display();
class addition counter d;
{int a; d.getdata();
public: d.display();
void getdata() return 0;}
{cout<<"enter a value"; 78. Program two copy one object to another
cin>>a; using ‗Copy constructor‘:
} #include<iostream>
void add(addition d) using namespace std;
{int s; class abc
s=a+d.a; {int a;
cout<<"sum"<<s; public:
}}; abc()
int main() {a=0;}
{addition a,b; abc(int b)
a.getdata(); {a=b;}
b.getdata(); void getdata()
a.add(b); {cin>>a;}
return 0; void display()
} {cout<<a;}
77. Static data member ~abc() //destructor
#include<iostream> {cout<<”\n destructor called”;}
using namespace std; };
class counter int main()
{int a; {abc d,f(d); //copy constructor

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
33

d.getdata(); { // real represents the real data of object c3


abc e=d; //copy constructor because this function is called using code
abc g=abc(3); //copy constructor c3.add(c1,c2);
abc h; real=comp1.real+comp2.real;
h=d; //copy constructor 88888888 // imag represents the imag data of object c3
return 0; //destructor called and because this function is called using code
destructor called statement will be c3.add(c1,c2);
printed for 5 times
imag=comp1.imag+comp2.imag; }
}
void displaySum()
79. Program for initializing default values
{ cout << "Sum = " << real<< "+"
for class objets using constructor.
#include<iostream> << imag << "i"; }
using namespace std; };
class Example { int main()
// Variable Declaration { Complex c1,c2,c3;
int a,b; c1.readData();
public: c2.readData();
//Constructor c3.addComplexNumbers(c1, c2);
Example() { c3.displaySum();
// Assign Values In Constructor return 0;
a=10; }
b=20; 81.Program to find whether a number is
cout<<"Im Constructor\n"; } prime or not using class.
void Display() { // parametric constructor
cout<<"Values :"<<a<<"\t"<<b; } #include<iostream>
}; using namespace std;
int main() // Class Declaration
{ Example Object; class prime
// Constructor invoked. { //Member Varibale Declaration
Object.Display(); int a,k,i;
// Wait For Output Screen public:
return 0;} prime(int x)
80.Program to pass two objects as arguments { a=x; }
to a function and add them. // Object Creation For Class
#include <iostream> void calculate()
using namespace std; { k=1;
class Complex {
{ private: for(i=2;i<=a/2;i++)
int real; if(a%i==0)
int imag; { k=0;
public: break;
Complex(): real(0), imag(0) { } }
void readData() else
{ cout << "Enter real and imaginary number { k=1; }
respectively:"<<endl; }}
void show()
cin >> real >> imag; }
{ if(k==1)
void addComplexNumbers(Complex comp1,
cout<<"\n"<<a<<" is Prime Number.";
Complex comp2)
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
34

else return 0;}


cout<<"\n"<<a<<" is Not Prime Numbers."; 83. Source Code to demonstrate the working
} of overloaded constructors
}; //constructor with one default parameter
int main() #include <iostream>
{ int a , opt; using namespace std;
do{ cout<<"Enter the Number:"; class Area
cin>>a; { private:
// Object Creation For Class int length;
prime obj(a); int breadth;
// Call Member Functions public:
obj.calculate(); // Constructor with no arguments
obj.show(); Area(): length(5), breadth(2) { }
cout<<"do u want to continue?"; // Constructor with two arguments
cin>>opt; Area(int l, int b): length(l), breadth(b){ }
}while(opt==1); void GetLength()
return 0;} { cout << "Enter length and breadth
82. Program to find Area of rectangle using respectively: ";
class. cin >> length >> breadth; }
//constructors int AreaCalculation() { return length * breadth;
#include <iostream> }
using namespace std; void DisplayArea(int temp)
class Area { cout << "Area: " << temp << endl; }
{ private: };
int length; int main()
int breadth; { Area A1, A2(2, 1);
public: int temp;
// Constructor cout << "Default Area when no argument is
Area(): length(5), breadth(2){ } passed." << endl;
void GetLength() temp = A1.AreaCalculation();
{ cout << "Enter length and breadth A1.DisplayArea(temp);
respectively: "; cout << "Area when (2,1) is passed as
cin >> length >> breadth; } argument." << endl;
int AreaCalculation() { return (length * temp = A2.AreaCalculation();
breadth); } A2.DisplayArea(temp);
void DisplayArea(int temp) return 0;}
{ cout << "Area: " << temp; } 84. Program to pass and return an object
}; using function.
int main() #include <iostream>
{ Area A1, A2; using namespace std;
int temp; class Complex
A1.GetLength(); {
temp = A1.AreaCalculation(); private:
A1.DisplayArea(temp); int real;
cout << endl << "Default Area when value is int imag;
not taken from user" << endl; public:
temp = A2.AreaCalculation(); Complex(): real(0), imag(0) { }
A2.DisplayArea(temp); void readData()

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
35

{ cout << "Enter real and imaginary class integer


number respectively:"<<endl; { int n,m;
cin >> real >> imag; } public:
Complex addComplexNumbers(Complex integer()
comp2) { m=0;n=0; }
{ Complex temp; integer(int a, int b)
// real represents the real data of object { m=a;n=b;}
c3 because this function is called using integer(integer & i)
code c3.add(c1,c2); { m=i.m; n=i.n; }
temp.real = real+comp2.real; void disp()
// imag represents the imag data of { cout<<m<<n<<"\n"; }
object c3 because this function is called };
using code c3.add(c1,c2); int main()
temp.imag = imag+comp2.imag; { integer i1;
return temp; } integer i2(20,40);
void displayData() integer i3(i2);
{ cout << "Sum = " << real << "+" integer i4=i3;
<< imag << "i"; } i1.disp();
}; i2.disp();
int main() i3.disp();
{ Complex c1, c2, c3; i4.disp();
c1.readData(); return 0;}
c2.readData(); 86.Program to convert and add two objects
c3 = c1.addComplexNumbers(c2); of different classes using friend function.
c3.displayData(); #include<iostream.h>
return 0;} #include<math.h>
FRIEND FUNCTION //using namespace std;
85.Program to calculate the average of two class dm;
class db
values using friend function.
{ float feet;
#include<iostream> float inches;
using namespace std; public:
class base void get_data()
{ int val1,val2; { float n;
public: cout<<"\n Enter the distance in feets \n";
void get() cin>>feet;
{ cout<<"Enter two values:"; cout<<"\n Enter the distance in inches \n";
cin>>val1>>val2; } cin>>inches;
friend float mean(base ob); if(inches==12)
}; { inches=0;
float mean(base ob) feet++;
}
{ return float(ob.val1+ob.val2)/2;}
if(inches>12)
int main()
{ n=inches/12;
{ base obj; inches=fmod(inches,12);
obj.get(); feet+=n;
cout<<"\n Mean value is : "<<mean(obj); } }
// copy constructors }
#include<iostream> friend void add(dm ,db );
using namespace std; };
class dm
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
36

{ float metres; return(c3); }


float cms; intmain()
public: {Complex c1(1.1,2.2), c2(3.3, 4.4);
void getdata() Complex c3 = add(c1, c2);
{ float n; c3.print();
cout<<"\n Enter distance in metres \n"; return(0); }
cin>>metres; 88. Program to multiply two vectors to give a
cout<<"\n Enter distance in centimeters \n"; matrix as product using friend function.
cin>>cms; #include <iostream.h>
if(cms==100) class Matrix;
{ cms=0; class Vector{
metres++; } int vec[3];
if(cms>100) public:
{ n=cms/100; void Init();
cms=fmod(cms,100); friend Vector multiply(Matrix &, Vector &);
metres+=n; } } void display();
friend void add(dm , db ); };
}; class Matrix
void add(dm m ,db f) {int mat[3][3];
{ float met,cm; public:
met= m.metres+(f.feet)/3.2808; Matrix();
cm= m.cms+(f.inches)*2.54; friend Vector multiply(Matrix &, Vector &);
cout<<"\n Sum of the distances is : };
\t"<<met<<"\n"<<cm<<endl;} Matrix::Matrix()
int main() {cout<<"\nEnter the data for the matrix:";
{ dm a; for(int r=0; r<3;r++)
db b; for(int c=0; c<3;c++)
a.getdata(); cin>>mat[r][c];
b.get_data(); }
add(a,b); void Vector::display()
return 0;} {for(int i=0; i<3;i++)
cout<<vec[i]<<" ";
87. Prorgram to add two complex number }
using friend function. void Vector::Init()
#include <iostream.h> {cout<<"\nEnter the data for the vector:";
class Complex{ for(int i=0; i<3;i++)
float real; // real part of the complex number cin>>vec[i];
float imag; // imaginary part of the complex }
number Vector multiply(Matrix &m, Vector &v)
public: {Vector r;
Complex(float = 0.0, float = 0.0); for (int i=0; i < 3; i++)
void print() {r.vec[i] = 0;
{ cout << real << "+" << imag << "i" << endl; } for (int j=0; j <3; j++)
friend Complex add(Complex&, Complex&); r.vec[i] += (m.mat[i][j] * v.vec[j]);}
}; return r;}
Complex::Complex(float r, float i) intmain()
{real=r; { Vector V1,V2;
imag=i; } Matrix M1;
Complex add(Complex& c1, Complex& c2) V1.Init();
{Complex c3; V2=multiply(M1,V1);
c3.real=c1.real + c2.real; V2.display();
c3.imag=c1.imag + c2.imag; return(0);}

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
37

89. Program to add and subtract two };


coordinate objects using friend function. class ad1
#include <iostream.h> {int c,d;
class Coords { public:
int x, y; void get()
public: {cin>>c>>d;}
Coords(int xVal = 0, int yVal = 0) friend void put(ad,ad1);
{ x = xVal; };
y = yVal; } void put(ad ob,ad1 ob1)
int retX() const { return x; } {cout<<ob.a<<ob.b<<ob1.c<<ob1.d;}
int retY() const { return y; } void main()
friend Coords operator+ (const Coords&, const {ad ob;
Coords&); ad1 ob1;
friend Coords operator- (Coords&); ob.get(); ob1.get();
}; put(ob,ob1);
Coords operator+ (const Coords& left, const }
Coords& right) { VIRTUAL FUNCTIONS.
Coords result; 91.Porgram to exercise virtual function.
result.x = left.x + right.x; class A
result.y = left.y + right.y; { int a;
return result; public:
} A()
Coords operator- (Coords &obj) { { a = 1; }
Coords result; virtual void show()
result.x = -obj.x; { cout <<a; }
result.y = -obj.y; };
return result; Class B: public A
} { int b;
int main() public:
{ Coords a(1, 2); B()
Coords b(3, 4); { b = 2; }
Coords v, z, w; virtual void show()
v = a + b; { cout <<b; }
// v = operator+(a, b); (same) };
cout << v.retX() << "," << v.retY() << endl; int main()
w = 3 + b; // ADT(Automatic Data Type) { A *pA;
conversion B oB;
cout << w.retX() << "," << w.retY() << endl; pA = &oB;
z = -b; pA→show();
// z = operator-(b); (same) return 0; }
cout << z.retX() << "," << z.retY() << endl; 92. Program to calculate area of shapes using
return(0); } virtual function.
90.Program to demonstrate friend function. #include<iostream>
#include<stdio.h> using namespace std;
#include<iostream.h> class shape
class ad1; { protected:
class ad double base,height;
{int a,b; public:
public: void getdata(int i,int j)
void get() { base=i;
{cin>>a>>b;} height=j;
friend void put(ad,ad1); }

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
38

virtual void area() class Dclass : public Bclass


{cout<<"\n\nTriangle Area {public:
"<<(0.5*base*height); void disp()
cout<<"\n\nRectangle Area "<<(base*height); { cout << "DERIVED DERIVED\n"; }
} void sh()
}; { cout << "derived derived\n"; }
class triangle:public shape };
{ double a; int main()
public: {
void area() Bclass B;
{ a=0.5*base*height; Dclass D;
cout<<"\n\nTriangle area "<<a; } Bclass *ptr;
}; cout << "ptr points to base class\n" ;
class rectangle:public shape ptr = &B;
{ double b; ptr->disp();
public: ptr->sh();
void area() cout << "ptr points derived class\n";
{ b=base*height; ptr = &D;
cout<<"\n\nRectangle area "<<b;} ptr->disp();
}; ptr->sh();
int main() return 0;}
{ shape *s; Result
triangle t; ptr points to base class
rectangle r; BASE BASE
int k,l,ch; base base
cout<<"\n\nEnter base "; ptr points derived class
cin>>k; BASE BASE
cout<<"\n\nEnter height "; derived derived
cin>>l; 94.Program to calculate area of shapes using
cout<<"\n\n1. Triangle 2.Rectangle "; ‗pure virtual function‘ and pointers.
cin>>ch; # include<iostream.h>
if(ch==1) class shape
{ s=&t; {protected:
s->getdata(k,l); double m1,m2;
s->area(); public:
} void getdata()
if(ch==2) {cout<<"enter the measurement 1 and 2 :";
{ s=&r; cin>>m1>>m2; }
s->getdata(k,l); virtual void display()=0;
s->area(); };
} class triangle: public shape
return 0;} {protected:
93. Program to demonstrate the working of double area;
virtual functions using pointers. public:
#include <iostream.h> void display()
class Bclass { area=(m1*m2)/2;
{public: cout<<"area of triangle:"<<area; }
void disp() };
{ cout << " BASE BASE\n" ; } class rectangle:public shape
virtual void sh() {protected:
{ cout << "base base\n"; } double area;
}; public:

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
39

void display() {static int count;


{ area=m1*m2; int code;
cout<<"area of rectangle:"<<area;} public:
}; void setcode()
class circle:public shape {code=++count;}
{protected: void showcode()
double area;
{cout<<"test paper code: "<<code<<"\n";}
public:
static void showcount()
void display()
{area=3.14*m1*m1; {cout<<"no of test papers: "<<count<<"\n";
cout<<"the area of a circle:"<<area;} }
}; };
void main() int test ::count;
{triangle t; int main()
rectangle r; {test t1,t2;
circle c; t1.setcode();
int n,opt; t2.setcode();
shape *ptr; test::showcount(); //static member fun
cout<<"\nEnter the no of choices "; accessing
cin>>n; test t3;
for(int i=1;i<=n;i++)
t3.setcode();
{ cout<<endl<<"\nenter choice:\n";
cout<<"1.triangle\n"; t2.showcount(); //static member fun accessing
cout<<"2.rectanlge\n"; t1.showcode();
cout<<"3.Circle\n"; t2.showcode();
cin>>opt; t3.showcode();
switch(opt) return 0;
{ case 1: }
ptr=&t; C AND C++ STRINGS
ptr->getdata(); 96. Write a program to find the length of a
ptr->display(); string.
break; #include<iostream>
case 2: using namespace std;
ptr=&r; int main( )
ptr->getdata(); { char str[80];
ptr->display(); cout<<"Enter string: ";
break; cin.getline(str, 80);
case 3: int i; //Hold length of string
ptr=&c; for(i = 0; str[i] != '\0'; i++);
ptr->getdata(); cout << "Length of string is: " << i;
ptr->display(); return 0;}
break; OTP:
}} Enterstring: Education
} Length of string is: 9
95. Program to demonstrate the working of
97. Write a program to display a string
static member function and a static data type
backwards.
for class test which gets and shows a paper‘s #include<iostream>
code and also counts the total number of test using namespace std;
papers . int main( )
#include<iostream> { char str[80];
using namespace std; cout<<"Enter string: ";
class test cin.getline(str, 80);
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
40

int l; //Hold length of string Output:


//Find the length of the string Enter first string: Computer
for(l = 0; str[l] != '\0'; l++); Enter second string: Science
//Display the string backwards
for(int i = l - 1; i >= 0; i--) The first string after adding second string
{ cout << str[i]; } content:
}
Output:
ComputerScience
Enter string: fate is not an eagle
elgae na ton si etaf
100.Write a program to compare two strings
98. Write a program to count the number of
to check if they are equal or not.
words in a string.
#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main( )
int main( )
{ char str1[80], str2[80];
{ char str[80];
cout<<"Enter first string: ";
cout << "Enter a string: ";
gets(str1);
cin.getline(str,80);
cout<<"Enter second string: ";
int words = 0; // Holds number of words
gets(str2);
for(int i = 0; str[i] != '\0'; i++)
int i;
{ if (str[i] == ' ') //Checking for spaces
for (i = 0; str1[i] == str2[i] && str1[i]!= '\0' &&
{ words++; }
str2[i] != '\0'; i++);
}
if(str1[i] - str2[i] == 0)
cout << "The number of words = " <<
cout << "Strings are equal";
words+1 << endl;
else
}
cout << "Strings are not equal";
Output:
return 0;}
Enter a String: You can do anything, but not Output:
everything. Enter first string: Mango
The number of words = 7 Enter second string: Man
99.Write a program to concatenate one Strings are not equal
string contents to another without using 101.Write a program to check if a string is
inbuilt functions. palindrome or not.
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main( ) int main( )
{ char str1[80], str2[80]; { char str[80];
cout<<"Enter first string: "; cout<<"Enter string: ";
cin.getline(str1, 80); cin.getline(str, 80);
cout<<"Enter second string: "; int l; //Hold length of string
cin.getline(str2, 80); //finding length of string
int l = 0; //Hold length of first string for(l = 0; str[l] != '\0'; l++);
//Find length of first string. //Comparing first element with last element t
for(l = 0; str1[l] != '\0'; l++); //ill middle of string
//Adding second string content in first int i;
for(int i = 0; str2[i] != '\0'; i++) for(i = 0; (i < l/2) && (str[i] == str[l - i - 1]);
{ str1[l++] = str2[i]; } i++);
str1[l] = '\0';
cout << "\nThe first string after adding if(i == l/2)
second string content:\n\n" << str1; cout << "Palindrome";
} else
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
41

cout << "Not a palindrome"; str[i] = str[j];


} str[j] = temp; }
Output: cout << "Reverse string: " << str << endl;}
Enter string: radar Output:
Palindrom Enter string: spoon
102.Write a program to find a substring Reverse string: noops
within another string, If found then to 104.Write a program to convert the given
display its starting position. string into lowercase character string,
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main( ) int main( )
{ char str1[80], str2[80]; { char str[80];
cout<<"Enter first string: "; cout<<"Enter string: ";
cin.getline(str1, 80); cin.getline(str, 80);
cout<<"Enter second string: "; for(int i=0;str[i]!='\0';i++)
cin.getline(str2, 80); { str[i] = (str[i] >= 'A' && str[i] <= 'Z') ?
int l = 0; //Hold length of second string (str[i] + 32) : str[i];
//finding length of second string }
for(l = 0; str2[l] != '\0'; l++); cout<<"Lowercase string: " << str << endl;
int i, j; }
for(i = 0, j = 0; str1[i] != '\0' && str2[j] != Output:
'\0'; i++) Enter string: Hello World
{ if(str1[i] == str2[j]) Lowercase string: hello world
{ j++; } 105.Write a program to convert the given
else string into a uppercase character
{ j = 0; } string.
} #include<iostream>
if(j == l) using namespace std;
cout<<"Substring found at position "<< i - int main( )
j + 1; { char str[80];
else cout << "Enter a string: ";
cout<<"Substring not found"; cin.getline(str,80);
} for(int i = 0; str[i] != '\0'; i++)
Output: {str[i] = (str[i] >= 'a' && str[i] <= 'z') ?
Enter first string: Mango (str[i] - 32) : str[i];
Enter second string: go }
Substring found at position 4 cout << "\nConverted string: " << str;
103.Write a program to find the reverse any }
given string. Output:
#include<iostream> Enter a string: People always fear change.
using namespace std; Converted string: PEOPLE ALWAYS
int main( ) FEAR CHANGE.
{ char str[80]; 106. Find the output of the following
cout<<"Enter string: "; program. Assume that all necessary
cin.getline(str, 80); header files are included?
int l; //Hold length of string
void Encrypt(char T[])
for(l = 0; str[l] != '\0'; l++); //finding length
{ for (int i = 0; T[i] != '\0'; i += 2)
of string
if (T[i] == 'A' || T[i] == 'E')
int temp;
T[i] = '#';
for(int i = 0, j = l - 1; i < l/2; i++, j--)
else if (islower(T[i]))
{ temp = str[i];
T[i] = toupper(T[i]);
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
42

else Reversed string = gnirts si sihT iaH


T[i] = '@';} 109.Write a c++ program using string class
int main() which gets a string and a substringand the
{ char text[]="SaVE EArtH"; program should replace the substring with
Encrypt(text); new user given string.
cout << text << endl;} #include<iostream>
Output:
#include<string.h>
@a@E@E#rTH
using namespace std;
107.Write the output of the following
int main()
program.
{ string s;
int main()
char c[20],h[20];
{ char name[] = "CoMPutER";
for (int x = 0; x < strlen(name); x++) int b,flag=0;
if (islower(name [x])) cout<<"Enter the string:";
name [x] = toupper(name[x]); getline(cin,s);
else cout<<"\nEnter the sub string:";
if (isupper(name[x])) cin.getline(c,20);
if (x % 2 == 0) cout<<"\nEnter the replacement string:";
name[x] = tolower(name[x]); cin.getline(h,10);
else for(int i=0;i<s.size()/strlen(c);i++)
name[x] = name[x-1]; { flag=0;
cout << name; b=s.find(c);
} if(b>=0)
Output:
{ s.replace(b,strlen(c),h);
cOmmUTee
flag=1; }
108.Write a program that reverses the given
}
string using string class and a rev()
if(flag=0)cout<<"no str";
function whichalso displays the result.
cout<<'\n'<<s;
#include<iostream>
}
#include<string.h>
Output:
using namespace std;
Enter the string: Hi I am c++. I am working
void rev(string);
good.
int main()
Enter the sub string: I am
{ string s;
Enter the replacement string:this is
cout<<"Enter the string to be reversed:";
Hi this is c++. this is working good.
getline(cin,s);
110.Write a c++ program that inserts a
rev(s);
string and as well as replaces any string.
}
#include <string>
void rev(string s)
#include <iostream>
{ char c;
using namespace std;
for(int i=0,j=s.size();i<s.size()/2-1;i++,j--)
int main() {
{ c=s[i];
string s = "Hai";
s[i]=s[j];
cout << s << endl;
s[j]=c;
s.insert(3, " I am Java");
}
cout << s << endl;
cout<<"\nReversed string ="<<s;
s.replace(3,10,"I am c++");
}
cout << s << endl;
Output:
return 0;}
Enter the string to be reversed:Hai This is
Output:
string
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
43

Enter the string: Hai hello


Number of vowels = 4
113.Write a cpp program that finds no. of
111.Write a program to concatenate two words in a sentence.
strings without using any inbuilt functions. Source code:
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std; using namespace std;
int main () int main ()
{string str1,str2; {string s;
string str3; int i,count=0,len;
int len ; cout<<"Enter the string:";
cout<<"Enter the string1:"; getline(cin,s);
getline(cin,str1); len = s.size();
cout<<"Enter the string2:"; while(i<len)
getline(cin,str2); {if(s.at(i)==' ')
str3 = str1 + str2; count++;
cout << "str1 + str2 : " << str3 << endl; i++;
len = str3.size(); }
cout << "str3.size() : " << len << endl; cout << "Number of words = " << count+1 <<
return 0;} endl;
Output: return 0;}
Output:
Enter the string: this is cpp
Number of words = 3
112.Write a program that counts the 114.Write a c++program to Sort a given
Number of Vowels in a given sentence using string using selection sort algorithm.
string class functions. #include <iostream>
#include <iostream> #include <string>
#include <string> using namespace std;
using namespace std; string small(string s[],int n,int i)
int main () {string smal=s[0];
{string s,s1("aeiouAEIOU"); for(;i<n+1;i++)
int f,i,count=0,len; { if(smal<s[i])
cout<<"Enter the string:"; smal=s[i];
getline(cin,s); }
len = s.size(); return smal;
f=s.find_first_of(s1,0); }
if(f>=0) int main ()
count++; {string s[10],temp,smal;
i=f+1; int i,k,j;
for(;i<len;) cout<<"Enter no. of strings:";
{ f=s.find_first_of(s1,i); cin>>k;
count++; cout<<"\nEnter the strings:";
i=f+1;} for(i=0;i<k+1;i++)
cout << "Number of vowels = " << count << getline(cin,s[i]);
endl; for(i=0;i<k+1;i++)
return 0;} { smal=small(s,k,i);

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
44

for(j=i;j<k+1;j++) #include<iostream.h>
{ if(smal>s[j]) #include<string.h>
{ temp=s[i]; int len;
s[i]=s[j]; class st
s[j]=temp;} {char str[128];
} public:
void getdata()
}
{cout<<"enter string with alphabets:\n";
cout<<endl; cin.getline(str,128,'\n');
for(i=0;i<k+1;i++) }
cout<<s[i]<<" "; void stln()
return 0;} {len=strlen(str);
Output: }
void srt()
{int i,j;
char temp;
for (i=0; i<len-2; i++)
{for (j=i+1; j<len-1; j++)
{if (str[i] > str[j])
115. Program to reverse a given string {temp = str[i];
belonging to class str and display the str[i] = str[j];
reversed string. str[j] = temp; }
#include<iostream.h> }
#include<string.h> }
class str }
{char st[50]; void putdata()
public: {cout<<"string is: "<<str;}
void getdata() };
{cin.getline(st,50,'\n');} int main (void)
void reverseIt() { st s;
{int l,i;char t; char temp;
l=strlen(st)-2; s.getdata();
for(i=0;i<=l/2;i++) s.stln();
{t=st[i]; s.srt();
st[i]=st[l-i]; s.putdata();
st[l-i]=t; return 0;}
}} 117. Program to remove any repeated
void putdata() characters of a string and display the edited
{cout<<"reversed string is "<<st<<"\n";} string.
}; #include <iostream>
main() using namespace std;
{ int i,l,t; int main()
char st1[50]; { string t;
str s; getline(cin,t);
cout<<"enter string1 "; cout<<"\n\nOriginal String: "<<t;
s.getdata(); int i,j;
s.reverseIt(); char c;
s.putdata(); for(i=0;i<t.length();i++)
return 0;} { c = t.at(i);
116.Program to sort a given string for(j=i+1;j<t.length();j++)
characters in alphabetical order. { if(c==t.at(j))
#include <stdlib.h> { t.replace(j,1,"");

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
45

j--; cout<<"\ninfo written into file\n";


} system("pause");
} return 0;}
} OUTPUT:
cout<<"\n\nRepeated Characters Removed info written into file
String: "<<t;
return 0;} 119. Program to read from text file and
display it
Files #include<iostream>
Opening a file #include<fstream>
Opening file using constructor (store as using namespace std;
char). int main()
ofstreamfout(“results.txt”); //output only {ifstream fin;
ifstream fin(“data.txt”); //input only fin.open("out.txt");
charch;
Opening file using open() while(!fin.eof()) //eof()----detecting end of
ofstreamofile; file
ofile.open(“data1.txt”); {fin.get(ch);
cout<<ch; }
ifstreamifile; fin.close();
ifile.open(“data2.txt”); return 0;
File mode parameter Meaning system("pause");}
ios::app Append to end of file
ios::ate go to end of file on opening OUTPUT:
ios::binary file open in binary mode Time is a great teacher
ios::in open file for reading only 120.Program to count number of characters
ios::out open file for writing only in a text file.
#include<iostream>
fstream file; #include<fstream>
(store as binary). using namespace std;
file.open ("example.bin", ios::out | ios::app | int main()
ios::binary); {ifstream fin;
file.close();//Closing file fin.open("out.txt");
Input and output operation charch;
put() and get() and getline() function int count=0;
file.get(ch); while(!fin.eof()) //eof()----detecting end of
file.put(ch); file
{fin.get(ch);
write() and read() function count++;
file.read((char *)&obj, sizeof(obj)); }
file.write((char *)&obj, sizeof(obj)); cout<<"Number of characters in file is "<<
count<<endl;
118. Program to write in a text file fin.close();
#include<iostream> system("pause");
#include<fstream> return 0;}
using namespace std; OUTPUT:
int main() Number of characters in file is 24
{ofstreamfout; 121.Program to count number of words.
fout.open("out.txt"); #include<iostream>
charstr[300]="Time is a great teacher"; #include<fstream>
fout<<str; using namespace std;
fout.close(); int main()

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
46

{ifstream fin; }
fin.open("out.txt"); fin.close();
char word[30]; fout.close();
int count=0; //note now sample.txt is linked with input
while(!fin.eof()) //eof()----detecting end of stream
file fin.open("sample.txt");
{fin>> word; while(!fin.eof()) //eof()----detecting end of
count++; } file
cout<<"Number of words in file is "<< {fin.get(ch);
count<<endl; cout<<ch;
fin.close(); }
system("pause"); cout<<"\n";
return 0;} fin.close();
OUTPUT: fout.close();
Number of words in file is 5 system("pause"); return 0;}
122.Program to count number of lines. OUTPUT:
#include<iostream> Time is a great teacher
#include<fstream> BASIC OPERATION ON BINARY FILE IN
using namespace std; C++
int main() 124. (PROGRAM FOR READING,
{ifstream fin; WRITING, SEARCH AND DISPLAY IN
fin.open("out.txt"); BINARY FILE)
charstr[80]; #include<iostream>
int count=0; #include<stdlib.h>
while(!fin.eof()) #include<fstream>
{fin.getline(str,80); using namespace std;
count++; class student
} {intadmno;
cout<<"Number of lines in file is "<< char name[20];
count<<endl; public:
fin.close(); void getdata()
system("pause"); {cout<<"\nEnter The admission no. ";
return 0; cin>>admno;
} cout<<"\nEnter The Name of The Student ";
OUTPUT: cin>>(name); }
Number of lines in file is 1 void showdata()
123. Program to copy contents of one file to {cout<<"\nAdmission no. : "<<admno;
another file (store as char). cout<<"\nStudent Name : ";
(dealing with more than one file at a time) puts(name); }
#include<iostream> int retadmno()
#include<fstream> {return admno; }
using namespace std; }obj;
int main() voidwrite_data()//Function to write in a binary
{ifstream fin; file
fin.open("out.txt"); {ofstreamoFile;
ofstreamfout; oFile.open("student.dat",ios::binary|ios::app);
fout.open("sample.txt"); obj.getdata();
charch; oFile.write((char*)&obj,sizeof(obj));
while(!fin.eof()) //eof()----detecting end of oFile.close();
file }
{fin.get(ch); //note info is read from out.txt //function to display records of binary file
fout<<ch;//note info is written into sample.txt void display() {

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
47

ifstreamiFile; 5.exit
iFile.open("student.dat",ios::binary); 2
while(iFile.read((char*)&obj,sizeof(obj)))
{obj.showdata(); } Admission no. : 1
iFile.close(); Student Name : a
}
void search() //Function to search and display enter your choice
from binary file 1.enter details
{ int n; 2.view all details
cout<<"\nenter the admn no:"; 3.view last entry
cin>>n; 4.search
ifstreamiFile; 5.exit
iFile.open("student.dat",ios::binary); 1
while(iFile.read((char*)&obj,sizeof(obj)))
{if(obj.retadmno()==n) Enter The admission no. 2
obj.showdata();
} Enter The Name of The Student b
iFile.close();}
int main() enter your choice
{ intch,y=1; 1.enter details
write_data(); 2.view all details
do{ 3.view last entry
cout<<"\nenter your choice\n1.enter 4.search
details\n2.view all details\n3.view last 5.exit
entry\n4.search\n5.exit"; 2
cin>>ch;
switch(ch) Admission no. : 1
{case 1: write_data(); Student Name : a
break;
case 2: display(); Admission no. : 2
break; Student Name : b
case 3: obj.showdata();
break; enter your choice
case 4: search(); 1.enter details
break; 2.view all details
case 5: y=0; 3.view last entry
break; 4.search
default : 5.exit
cout<<"\nwrong choice"; 3
}
}while(y==1); Admission no. : 2
return 0;} Student Name : b
OUTPUT:
Enter The admission no. 1 enter your choice
1.enter details
Enter The Name of The Student a 2.view all details
3.view last entry
enter your choice 4.search
1.enter details 5.exit
2.view all details 4
3.view last entry
4.search enter the admn no:1

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
48

File Pointers And Their Manipulation:


Admission no. : 1 All i/o streams objects have, at least, one
Student Name : a internal stream pointer:
ifstream, like istream, has a pointer known as
enter your choice the get pointer that points to the element to be
1.enter details read in the next input operation.
2.view all details
3.view last entry ofstream, like ostream, has a pointer known as
4.search the put pointer that points to the location where
5.exit the next element has to be written.
5
-------------------------------- Finally, fstream, inherits both, the get and the
Process exited after 35.32 seconds with return put pointers, from iostream (which is itself
value 0 derived from both istream and ostream).
Press any key to continue . . .
These internal stream pointers that point to the
ERROR HANDLING FUNCTION reading or writing locations within a stream can
FUNCTION RETURN VALUE AND be manipulated using the following member
MEANING functions:
eof():
True (non zero) if end of file is encountered seekg() moves get pointer(input) to a specified
while reading; otherwise return false(zero) location
fail(): seekp() moves put pointer (output) to a specified
true when an input or output operation has location
failed tellg() gives the current position of the get
bad(): pointer
true if an invalid operation is attempted or any tellp() gives the current position of the put
unrecoverable error has occurred. pointer
good():
125. Program to return true if no error The other prototype for these functions is:
occurs. seekg(offset, refposition );
#include <fstream> seekp(offset, refposition );
#include<iostream>
using namespace std; The parameter offset represents the number of
int main() bytes the file pointer is to be moved from the
{ location specified by the parameter refposition.
ifstream file; The refposition takes one of the following three
file.open("a:test.dat"); constants defined in the ios class.
if(!file)
Cout<<"can't open group.dat"; ios::beg start of the file
else ios::cur current position of the pointer
Cout<<"file opened successfully"; ios::end end of the file
Cout<<"\nfile"<<file;
Cout<<"error status :"<<file.rdstate(); example:
Cout<<"good()"<<file.good(); file.seekg(-10, ios::cur);
Cout<<"eof()"<<file.eof();
Cout<<"fail()"<<file.fail(); The seekp() and tellp() member functions are
Cout<<"bad()"<<file.bad();<<end; identical to the above two functions, but they
file.close(); are identified with the put pointer. The seekg()
return 0; and tellg() member functions are defined in the
} istream class. The seekp() and tellp() member
functions are defined in the ostream class.

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
49

}
126. Program to find out the number of sri(float in,float ft)
records in the file billfile.dat by using the { i=in;
inbuilt seekg() and tellg() functions. f=ft;
#include<fstream.h> f=f+in/12;
#include<iostream.h> cout<<"f is"<<f<<endl;
class bill //cout<<"metres is"<<f/mtf<<endl;
{private: cout<<"meters"<<int(f/mtf);
intiBill_no; cout<<"cm"<<((f/mtf)-int(f/mtf))*100;
floatfBill_amt; }
public: };
void getdata() int main()
{cout<<”Enter Bill number”; { float ft,in;
cin>>iBill_no; cout<<"enter feet and inches"<<endl;
cout<<”Enter Bill amount”; cin>>ft>>in;
cin>>fBill_amt; sri s1(in,ft);
} }
void showdata() 128. Program to convert dollar to rupees.
{cout<<”Bill number ”<<iBill_no<<endl; #include<iostream>
cout<<”Bill amount ”<<fBill_amt<<endl; using namespace std;
} float dtr=65.005;
}; class doll //dollar to
void main() rupees(basic to object)//
{fstream Fi1(“billfile.dat”,ios::in); { private:
Fi1.seekg(0,ios::end); float d;
int iEnd; public:
iEnd=Fi1.tellg(); doll()
cout<<”The size of the file is “<<iEnd<<endl; { d=0.0;
cout<<”Size of one record is }
”<<sizeof(bill)<<endl‟ doll(float dollar)
ini iNorec=iEnd/sizeof(bill); { d=dollar;
cout<<”There are “<<iNorec<<”records in the cout<<"rupees is"<<d*dtr<<endl;
file”<<endl; }
}
};
MISCELLANEOUS PROGRAMS – II int main()
127. Program to convert object of class foot { float doller;
to object of class meter. cout<<"enter a dollars"<<endl;
#include<iostream> //basic to object from cin>>doller;
foot and inches to m and cm// doll d1(doller);
using namespace std; }
float mtf=3.280833; 129. Program to convert temperature
class sri centigrade to kelvin.
{ #include<iostream>
private: using namespace std;
float i; class conv
float f; {private: //convert temperature
public: crntigrade to kelvin(basic to
sri() object)//**********//
{ float d;
i=0.0; public:
f=0.0; conv()

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
50

{ d=0.0; } rate=0.0;}
conv(float deg) road(int c,int n,float r)
{d=deg; { code=c;
cout<<"temprature in Kelvin no=n;
is"<<d+273.15<<endl; rate=r;
} }
}; int retcode()
int main() { return code;
{ float d; }
cout<<"enter temp in degrees"<<endl; int retno()
cin>>d; { return no;
conv c1(d); }
} float retrate()
130. Program to conert rupees to dollars. { return rate;
#include<iostream> }
using namespace std; };
float dtr=65.005; class wide
class rup { private:
{ // convert rupee to dollar by object to basic// int code;
private: float fv;
float rup; public:
public: wide()
void get(float r) { code=0;
{ rup=r; fv=0.0;
} }
operator float() wide(road k)
{ cout<<"dollars { code=k.retcode();
is"<<rup/dtr<<endl; cout<<"hi"<<k.retcode()<<endl;
} fv=k.retno()*k.retrate();
}; }
int main() void show()
{ float rupee; {cout<<"code is"<<code<<endl;
cout<<"enter dollar"<<endl; cout<<"total rate"<<fv<<endl;
cin>>rupee; }
rup r1; };
r1.get(rupee); int main()
rupee=r1; { int x,y;
} float z;
131. Program to pass an object of one class cout<<"enter code"<<endl;
as a parameter to another class‘s cin>>x;
constructor. cout<<"enter no"<<endl;
#include<iostream> cin>>y;
using namespace std; cout<<"enter rate"<<endl;
class road cin>>z;
{ private: road r1(x,y,z);
int code; wide w1(r1);
int no; w1.show();
float rate; }
public: 132. Program to display the radius or area of
road() a circle from the given area or radius
{ code=0; respectively.
no=0; #include<iostream>

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
51

using namespace std; cin>>a;


class area; area a1(a);
class radius radius r1;
{private: r1=a1;
float rad; }
public: }
radius()
{rad=0.0; 133. Write a program to swap two numbers
.} using inline function.
radius(float r) #include<iostream>
{rad=r;
using namespace std; //swapping
}
float retrad() of two numbers using inline//*************//
{return rad; inline int swap(int a,int b);
} int main()
area(radius k) { int a,b;
{cout<<"area cout<<"enter a and b"<<endl;
is"<<3.14*k.retrad()*k.retrad(); cin>>a>>b;
}
swap(a,b);
};
class area }
{private: inline int swap(int a,int b)
float ar; { int t;
public: t=a;
area() a=b;
{ar=0.0; b=t;
}
cout<<"a is "<<a<<endl;
area(float are)
{ar=are; cout<<"b is "<<b<<endl;
} }
float retarea() 134. Program to check if the given number is
{return ar; an Armstrong number or not using class.
} #include<iostream>
radius(area v) #include<cmath>
{cout<<"radius is"<<v.retarea()/3.14; using namespace std;
} class armstrong
}; { //check given number
int main() is armstrong or not using classes and
{ int n; objects//*********//
cout<<"enter 1(to find radius) and 2(to find private:
circle)"<<endl; int a;
cin>>n; public:
if(n==1) void get()
{float r; {cout<<"enter a "<<endl;
cout<<"enter radius of circle"<<endl; cin>>a;
cin>>r; }
radius r1(r); void check()
area a1(r1); { int b=a;
} int c=a;
else int k=0,i,t,sum=0;
{float a; for(i=0;b!=0;i++)
cout<<"enter area"<<endl; {

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
52

b=b/10; m2.get();
k++; m3=dammi.add(m1,m2);
} m3.show();
for(i=0;c!=0;i++) }
{ t=c%10; 136. class and object
sum=sum+pow(t,k); #include<iostream>
c=c/10; #include<cstring>
} using namespace std;
if(sum==a) class bank
{cout<<"armstrong number"<<endl; { private:
} int cid;
else char name[30];
{cout<<"not a Armstrong no"<<endl; float balance;
} //bank deposite and withdrawl
} public:
}; bank()
int main() {cid=11111;
{ armstrong k; strcpy(name,"sastra");
k.get(); balance=100000;
k.check(); }
} void deposite()
135.Program to overload ‗+‘ operator using {float m;
classes and objects. cout<<"enter money to bedepositd"<<endl;
include<iostream> cin>>m;
using namespace std; balance=balance+m;
class metre }
{ private: void withdraw()
int m; {float m;
int cm; cout<<"enter money to be withdraw"<<endl;
public: cin>>m;
void get() //returning an object balance=balance-m;
using data members meter and }
centimeter//********************// void display()
{ cout<<"enetr m"<<endl; {cout<<"cid:"<<cid<<endl;
cin>>m; cout<<"name:"<<name<<endl;
cout<<"enter cm"<<endl; cout<<"remaining balance"<<balance<<endl;
cin>>cm; }
} };
metre add(metre mm1,metre mm2) int main()
{ metre m3; { bank b1;
m3.m=mm1.m+mm2.m; int n;
m3.cm=mm1.cm+mm2.cm; cout<<"enter n"<<endl;
return m3; cin>>n;
} if(n==1)
void show() {b1.deposite(); }
{cout<<"metre is"<<m<<endl; else
cout<<"centimetre is"<<cm<<endl; {b1.withdraw(); }
} b1.display();
}; }
int main() 137. Overloading +
{ metre m1,m2,dammi,m3; #include<iostream>
m1.get(); using namespace std;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
53

class exam int mks;


{ private: public:
int im; bonus()
int em; { mks=0; }
public: //// +=operator ///////////
exam() bonus(int marks)
{ im=0; { mks=marks; }
em=0; } void operator+=(int bone)
exam(int inter,int exter) { mks+=bone; }
{ im=inter; void show()
em=exter; } {cout<<"marks"<<mks<<endl; }
exam operator+(exam kk2) };
{ exam kk3; int main()
kk3.im=im+kk2.im; { int marks,b;
kk3.em=em+kk2.em; bonus b2;
return kk3; cout<<"enter marks"<<endl;
} cin>>marks;
exam operator-(exam kk2) bonus b1(marks);
{ exam kk4; cout<<"enter bonusmarks"<<endl;
kk4.im=im-kk2.im; cin>>b;
kk4.em=em-kk2.em; marks+=b;
return kk4; } b1.show();
void show() }
{ cout<<"internal"<<im<<endl; 139. Overloading '<' operator to compare
cout<<"external"<<em<<endl; two distance objects:
} #include <iostream>
}; using namespace std;
int main() class Distance //English Distance class
{ exam k3,k4; {private:
int in1,ex1,in2,ex2; int feet;
cout<<"enter int and ext for k1"<<endl; float inches;
cin>>in1>>ex1; public: //constructor (no args)
cout<<"enter int and ext for k2"<<endl; Distance() : feet(0), inches(0.0)
cin>>in2>>ex2; { } //constructor (two args)
exam k1(in1,ex1); Distance(int ft, float in) : feet(ft), inches(in)
exam k2(in2,ex2); {}
k3=k1+k2; void getdist() //get length from user
k4=k1-k2; {cout << “\nEnter feet: “; cin >> feet;
k3.show(); cout << “Enter inches: “; cin >> inches;
k4.show(); }
} void showdist() const //display distance
138. overload += { cout << feet << “\‟-” << inches << „\”‟; }
#include<iostream> bool operator < (Distance) const; //compare
using namespace std; distances
class bonus };
{ private: //compare this distance with d2
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
54

bool Distance::operator < (Distance d2) const int b,flag=0;


//return the sum cout<<"Enter the string:";
{float bf1 = feet + inches/12; getline(cin,s);
cout<<"\nEnter the sub string:";
float bf2 = d2.feet + d2.inches/12;
cin.getline(c,20);
return (bf1 < bf2) ? true : false;} cout<<"\nEnter the replacement string:";
int main() cin.getline(h,20);
{Distance dist1; //define Distance dist1 for(int i=0;i<s.size();i++)
dist1.getdist(); //get dist1 from user { b=s.find(c);
//define and initialize dist2 if(b>=0)
Distance dist2(6, 2.5); { s.replace(b,strlen(c),h);
flag=1; }
//display distances
}
cout << “\ndist1 = “; dist1.showdist(); if(flag==0)cout<<"no str";
cout << “\ndist2 = “; dist2.showdist(); cout<<'\n'<<s
if( dist1 < dist2 ) //overloaded „<‟ operator }
cout << “\ndist1 is less than dist2”; 142. Usage and manipulation of static
else variables and member functions.
cout << “\ndist1 is greater than (or equal to) #include<iostream>
using namespace std;
dist2”;
class test
cout << endl; { static int x;
return 0;} static int y;
140. Program to find the reverse of the given public:
string. //test();
#include<iostream> void getd() {cin>>x; } //* ok you can change
#include<string.h> the static data member value, since it is not
using namespace std; const
void rev(string); // static void disp() //** error static
int main() member function can use only static data
{ string s; // {cout<<y;}
cout<<"Enter the string to be reversed:"; static void output() // @ ok
getline(cin,s); {cout<<x;}
rev(s); void outs() // @@ ok normal member
} function can handle static data member
void rev(string s) {cout<<x; // $ ok
{ char c; }
for(int i=0,j=s.size()-1;i<s.size()/2-1;i++,j--) };
{ c=s[i]; int test::x=10;
s[i]=s[j]; //test::test(){y=10;
s[j]=c; //}
} int main()
cout<<"\nReversed string ="<<s; { test t1;
} t1.getd(); // * ok
141. Program to find a substring and replace //t1.disp(); //** error
that string with any user given string. t1.output(); // @ ok
#include<iostream> t1.outs(); //@@ ok
#include<string.h> test::outs(); // $ ok, it is logical to call a static
using namespace std; member function that use a common static
int main() datamember without object .
{ string s; }
char c[20],h[20];
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
55

143. Program to count the number of vowels void disp()


in a given string using find_first_of() inbuilt {cout<<"The value of temp is"<<f<<endl;
string function. }
#include <iostream> float getf()
#include <string> {return f;}
using namespace std; };
int main () class weather2
{string s,s1("aeiouAEIOU"); {float c;
int f,i,count=0,len; public:
cout<<"Enter the string:"; weather2()
getline(cin,s); {c=0.0;}
len = s.size(); weather2(weather1 w)
f=s.find_first_of(s1); {c=w.getf()-273.15;
if(f>=0) }
count++; void getd()
i=f+1; {cout<<"The value of temp in celcius is";
for(;i<len;) cin>>c;
{ f=s.find_first_of(s1,i); }
count++; void disp()
i=f+1;} {cout<<"The value of temp is"<<c<<endl;
cout << "Number of vowels = " << count << }
endl; operator weather1 ()
return 0;} {float ft;
ft=c+273.15;
144. In meteorological department generally return weather1(ft);
maintained atmosphere temperature for }
every state individually. Assume that in };
state1, data maintained in the form of int main()
Farenheit but in state2 maintained in {weather1 w1;
Celsius. There is one situation arises that w1.getd();
they wants to share their data.(i) Convert weather2 w2=w1;
state1 weather report into celsius before w2.disp();
sharing. (ii)Convert state2 weather report to weather1 w3;
form understand by state1. Do this w3=w2;
conversion in data conversion technique. To w3.disp();}
implement this create classes called weather1
with member data Faren and weather2 with 145. Design a Meal class with two fields—one
member data celcius(float type). In main that holds the name of the entrée, the other
function get the input that holds a calorie count integer. Include a
and test the functionalities. constructor that sets a Meal‘s fields with
#include<iostream> parameters, or uses default values when no
using namespace std; parameters are provided. a) Include an
class weather1 overloaded operator+()function that allows
{float f; you to add two or more Meal objects. Adding
public: two Meal objects means adding their calorie
weather1() values and creating a summary Meal object
{f=0.0;} in which you store ―Daily Total‖ in the
weather1(float ft):f(ft){} entrée field. b) Include an overloaded
void getd() operator==() function to compare two Meal
{cout<<"Enter the value of temp in fahrenheit"; object based on the calorie count. c) Write a
cin>>f; main()function that declares four Meal
} objects named breakfast, lunch, dinner, and

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
56

total. Provide values for the breakfast, lunch, cout<<"\nTotal details: ";
and dinner objects. Include the statement cout<<"THE TOTAL FOOD";
total = breakfast + lunch + dinner; in your total.disp();
program, then display values for the four if((breakfast==dinner))
Meal objects. d) Include statements in main cout<<"\nbreakfast and dinner same
to find the objects that have same calorie calories\n";
count. else if((breakfast==lunch))
#include <iostream> cout<<"\nbreakfsat and lunch same calories\n";
using namespace std; else if((lunch==dinner))
class meal cout<<"\nlunch and dinner same calories\n";
{ else
int cal; cout<<"\nNo calories are same\n";
char food[30]; }
public:
meal()
{ cal=0; } 146. Create a class named STUDENT with
meal(int c) the following private data members -
{ c=cal; } Name(string), RegNo(long) and Dept(string).
void getd() Include member functions - getStudInfo() to
{ cout<<"\nEnter the food item and the take input for its data members and
calories: "; dispStudInfo() to output the details. Derive a
cin>>food>>cal; class named ACADEMIC from STUDENT
} with the following additional data members -
void disp() YearOfStudy(int) and CGPA(float). Derive
{ cout<<"\nThe food item is: "<<food; another class named COCURRICULAR
cout<<"\nCalories for the food are: "<<cal; from STUDENT with a data member -
} SkillSet(2-dimensional char array of
meal operator+(meal a) dimension 5 X 10). Override the base class
{ meal b; member functions in both the derived classes
b.cal=cal+a.cal; to get information for their data members,
return meal(b); apart from invoking the base class member
} function. In main method, demonstrate the
bool operator==(meal d) functioning of the above hierarchy by
{ return((cal==d.cal)?true:false); creating 2 array of objects, one each for
} ACADEMIC and COCURRICULAR. From
}; ACADEMIC array of objects, display the
int main() details of the students with CGPA &gt; 7.5
{ (Hint : Include appropriate member function
meal breakfast,dinner,lunch,total; to do this). Also display the details of all the
cout<<"\nEnter the details of breakfast : "; objects in COCURRICULAR array of
breakfast.getd(); objects.*/
cout<<"\nEnter the details of dinner : "; #include<iostream>
dinner.getd(); #include<string>
cout<<"\nEnter the details of lunch : "; #include<string.h>
lunch.getd(); using namespace std;
total=breakfast+lunch+dinner; class STUDENT
cout<<"\nBreakfast details: "; {
breakfast.disp(); string name,dept;
cout<<"\nDinner details: "; long rno;
dinner.disp(); public:
cout<<"\nLunch details: "; void getst()
lunch.disp(); {cout<<"Enter name,dept,rno:"<<endl;

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
57

cin>>name>>dept>>rno; ACADEMIC a[n];


} int i;
void dispst() for(i=0;i<n;i++)
{cout<<"name:"<<name<<endl; {a[i].getst();
cout<<"dept:"<<dept<<endl; c[i].getst();
cout<<"rno:"<<rno<<endl; }
} for(i=0;i<n;i++)
}; {a[i].dispst();
class ACADEMIC:public STUDENT c[i].dispst();
{int year; }
float cgpa; for(i=0;i<n;i++)
public: {a[i].check();
ACADEMIC():year(0),cgpa(0.0){} }
void getst() }
{STUDENT::getst();
cout<<"enter year and cgpa:"<<endl; 147. Create a class called Distance that has
cin>>year>>cgpa; separate member data int for feet, and float
} for inches. A constructor should initialize
void dispst() this data to 0. Another member function
{STUDENT::dispst(); should display it, in 3‘-5‖ format. Create two
cout<<year<<"year"<<cgpa<<"cgpa"<<endl; objects H and W to maintain the distance
} walked by Husband (H) and wife (W) as they
void check() are in fitness challenge. Define a function
{cout<<"displaying details of students whose addDistance(Distance today) to add the
cgpa more than 7.5"<<endl; today‘s walking distance to the calling
if(cgpa>7.50) object. Write a function Winner() that takes
{STUDENT::dispst(); two Distance objects H and W as arguments
cout<<year<<"year"<<cgpa<<"cgpa"<<endl; and display the one who walked longer
} distance as winner along with the difference
} of distance |H-W|. Collect the distances
}; walked by them in 5 days repeatedly and add
class COCURRICULAR:public STUDENT using addDistance() also display daily winner
{string skill[5]; with respect to the total distance walked till
public: that day.
void getst() #include<iostream>
{cout<<"enter skills"<<endl; using namespace std;
class distance
for(int i=0;i<5;i++) {
{cin>>skill[i]; int feet;
} float inches;
} public:
void dispst() distance()
{feet=0;
{cout<<"List of skills"<<endl; inches=0;
for(int i=0;i<5;i++) }
{cout<<skill[i]; void addDistance(int f,float i)
} { feet+=f;
} inches+=i;
}
}; void winner(distance a,distance b)
int main() { float y;int x;
{int n; x=a.feet-b.feet;
cout<<"enter no.of students"<<endl; y=a.inches-b.inches;
cin>>n; if(a.feet>b.feet)
{ cout<<"\nwinner : H";
COCURRICULAR c[n]; }
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
58

else if(a.feet<b.feet) member function CalBMI() from main to


{ cout<<"\nwinner : W"; calculate and return first person‘s body mass
}
else index (BMI). Display stage in the function
{ if(y>0) and BMI in main(). Call the overloaded
{ cout<<"\nwinner : H"; member function CalBMI() using a float
} argument passed by reference to calculate
else if(y<0) second person‘s BMI. Display stage in the
{ cout<<"\nwinner : W";
} function and BMI in main()
else A person‘s BMI is calculated with the
cout<<"\nwinner :H&M"; following formula:
} BMI = weight * 703 / height2
if(x>0) BMI is often used to determine whether a
if(y<0)
{ y+=12; person with sedentary lifestyle is overweight
x--; or underweight for his or her height. The
} member functions CalBMI() should display a
if(x>=0) message indicating whether the person has
cout<<"\nlead by :"<<x<<"\'-"<<y<<"\""; optimal weight, is underweight, or is
else cout<<"\nlead by :"<<-x<<"'-"<<y<<"\"";
} overweight. A person‘s weight is considered
void display() to be optimal if his or her BMI is between
{ cout<<"total distance walked till 18.5 and 25. If the BMI is less than 18.5, the
date"<<feet<<"\'"<<inches<<"\""; person is considered to be underweight. If
} the BMI value is greater than 25, the person
}h,w,g;
int main() is considered to be overweight. Note: stage-
{ int a,n;float b; optimal weight, underweight, overweight.
cout<<"enter the no of entries to be compared"; #include<iostream>
cin>>n; using namespace std;
for(int i=0;i<n;i++) class bmi
{cout<<"\nEnter husband data for day { public:
"<<i+1<<":"<<"\n Enter feet "; float weight;
cin>>a; int height;
cout<<"Enter inches "; bmi()
cin>>b; {weight=0.0;
h.addDistance(a,b); height=0;
cout<<"Enter wife data for day "<<i+1<<":"<<"\n Enter }
feet "; bmi(float wt,int ht)
cin>>a; { weight=wt;
cout<<"Enter inches "; height=ht;
cin>>b; }
w.addDistance(a,b); void getmeasure()
cout<<"day "<<i+1<<" result:\n"; {cout<<"\n Enter the weight and height of second
cout<<"HUSBAND:\n"; person:";
h.display(); cin>>weight>>height;
cout<<"\n WIFE:\n"; }
w.display(); float calbmi()
g.winner(h,w); { float bmi1;
} double t=0;
} t=height*height;
bmi1=((weight*703)/(t));
if(bmi1>=18.5 && bmi1<=25)
148. Write a program to create a class BMI {cout<<"\n Optimal wight.";}
with data members weight (input should be else if(bmi1<18.5)
in pounds) and height (input should be in {cout<<"\n Underweight!!";}
inches). Create a parametric constructor to else if(bmi1>25)
pass the data members from main to the {cout<<"\n Overwight!!!";}
return bmi1;
object B1. Create a Getmeasure() member }
function to get input for object B2. Call the float calbmi(float &k)
{ float bmi2;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
59

double t=0;
t=height*height;
bmi2=((k*703)/(t));
if(bmi2>=18.5 && bmi2<=25)
{cout<<"\n Optimal wight.";}
else if(bmi2<18.5)
{cout<<"\n Underweight!!";}
else if(bmi2>25)
{cout<<"\n Overwight!!!";}
return bmi2;
}
};
int main()
{ float bmi1,bmi2;
float wt1;
int ht1;
cout<<"\n Enter the wight and height of person 1:";
cin>>wt1>>ht1;
bmi p1(wt1,ht1);
bmi p2;
p2.getmeasure();
float t;
t=p2.weight;
bmi1=p1.calbmi();
cout<<"\n The BMI of 1st person:"<<bmi1;
bmi2=p2.calbmi(t);
cout<<"\n The BMI of 2nd person:"<<bmi2;
}

Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section


& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University

You might also like