100% found this document useful (2 votes)
638 views

CPP All Programs

1. The document discusses various C++ functions including inline functions, function overloading, default parameters, and classes. It provides code examples to demonstrate different types of functions like inline member functions, overloaded absolute value functions, a function with default parameters, and power functions overloaded for different data types. 2. The examples show how to create a Distance class with member functions, and how the same function name can be used for member and ordinary functions. Code is provided to find the maximum of two numbers using an inline function. 3. Examples demonstrate using inline functions to find multiplication and cubic values of numbers in a class. The last example finds the largest of two numbers passed to an inline function. The document also covers classes

Uploaded by

Rishi Khan
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
100% found this document useful (2 votes)
638 views

CPP All Programs

1. The document discusses various C++ functions including inline functions, function overloading, default parameters, and classes. It provides code examples to demonstrate different types of functions like inline member functions, overloaded absolute value functions, a function with default parameters, and power functions overloaded for different data types. 2. The examples show how to create a Distance class with member functions, and how the same function name can be used for member and ordinary functions. Code is provided to find the maximum of two numbers using an inline function. 3. Examples demonstrate using inline functions to find multiplication and cubic values of numbers in a class. The last example finds the largest of two numbers passed to an inline function. The document also covers classes

Uploaded by

Rishi Khan
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/ 94

FUNCTIONS

1. Write an inline function called zerosmaller() that is passed two int arguments by reference
and then sets the smaller number to 0. Write a main() program to exercise this function.
#include<iostream>
using namespace std;
inline void zerosmaller(int &a,int &b)
{ if(a>b)
b=0;
if(a<b)
a=0;
if(a==b)
cout<<"both nos. are equal";
}
int main()
{ int a,b;
cout<<"enter 2 nos.";
cin>>a>>b;
zerosmaller(a,b);
cout<<endl<<a<<" "<<b;
}
2. INLINE MEMBER FUNCTIONS
Create a distance class with a data member of int type. Include a member function to take input
for distance and another inline member function to compare two distances. Write a main()
program to do the following functions.
#include<iostream>
using namespace std;
class dist
{ int a;
public:
void getd()
{ cout<<endl<<"enter distance in meter: ";
cin>>a;
}
inline int compare(dist d2)
{ return (a>d2.a)?a:d2.a;
}
};
int main()
{ dist d1,d2;
d1.getd();
d2.getd();
cout<<endl<<"the greater of the two distances is :"<<d1.compare(d2);
}
3. inline
#include<iostream.h>
#include<conio.h>
inline void cube(int &a)
{
a=a*a*a;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
int main()
{ int x;
clrscr();
cout<<"enter the number: ";
cin>>x;
cube(x);
cout<<"the cube is: "<<x;
getch();
return 0;
}

4. inline
#include<iostream.h>
#include<conio.h>
inline int cube(int *a)
{
return((*a)*(*a)*(*a));
}
int main()
{ int a;
clrscr();
cout<<"enter the number: ";
cin>>a;
cout<<"the cube is: "<<cube(&a);
getch();
return 0;
}

FUNCTION OVERLOADING
5. Write a program to find the absolute value of an integer as well as a floating point no using
function over loading.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}
int absolute(int var)
{ if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return var;
}
DEFAULT PARAMETERS
6.Write a function sum with 3 parameters namely no of values (int), difference(int), and the value
of the first term(int). give default value to these parameters . hence find the sume of the
corresponding AP by giving one or more of the arguments default.

#include<iostream>
#include<iomanip>
using namespace std;
long int sum(int n,int diff=1,int first_term=1 )
{long sum=0;;
for(int i=0;i<n;i++)
{cout<<setw(5)<<first_term+diff*i;
sum+=first_term+diff*i;
}
return sum;
}
int main()
{cout<<endl<<"Sum="<<setw(7)<<sum(10)<<endl;
//first term=1; diff=1,n=10
//sums the series 1,2,3,4,510

cout<<endl<<"Sum="<<setw(7)<<sum(6,3,2)<<endl;
//first term=1; diff=2,n=10
//sums the series 2,5,8,11,14,17

cout<<endl<<"Sum="<<setw(7)<<sum(10,2)<<endl;
//first term=1; diff=2,n=10
//sums the series 1,3,5..19
return 0;
}
7. Raising a number N to the power P is the same as multiplying N by itself P times. Write a
function called power() that takes N (double) and P (int) as input, and returns the result NP as a
double value. Use a default argument of 2 for P, so that if this argument is omitted, the number N
will be squared. Overload power() function, to work with int, long, and float. Overload the power()
function for char datatype also, which should print P times the given character N. Write the
main() program to exercise these overloaded functions with all argument types.
//FUNTION PROTOTYPES
int P;
double func(double N1,int P=2);
int func(int N2,int P=2);
float func(float N3,int P=2);
long int func(long int N4,int P=2);
void func(char N5,int P=2);

void main(void)
{ double N1;
cout<<"enter base";
cin>>N1;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<"enter power";
cin>>P;
cout<<"Square of " <<N1<<"is (default arg 2) "<<func(N1)<<endl;
cout<<N1<<" Power "<<P<<" is "<<func(N1,P)<<endl;

int N2;
cout<<"enter base";
cin>>N2;
cout<<"Square of " <<N2<<"is (default arg 2) "<<func(N2)<<endl;
cout<<N2<<" Power "<<P<<" is "<<func(N2,P)<<endl;
float N3;
cout<<"enter base";
cin>>N3;
cout<<"Square of " <<N3<<"is (default arg 2) "<<func(N3)<<endl;
cout<<N3<<" Power "<<P<<" is "<<func(N3,P)<<endl;
long int N4;
cout<<"enter base";
cin>>N4;
cout<<"Square of " <<N4<<"is (default arg 2) "<<func(N4)<<endl;
cout<<N4<<" Power "<<P<<" is "<<func(N4,P)<<endl;
char N5;
cout<<"enter base";
cin>>N5;
cout<<"Square of " <<N5<<"is (default arg 2) ";
func(N5);
cout<<N5<<" Power "<<P<<" is ";
func(N5,P);
}
double func(double N,int P)
{double pwr=1.0;
int i;
for(i=1;i<=P;i++)
pwr=pwr*N;
return pwr;
}
int func(int N,int P)
{int pwr=1;
int i;
for(i=1;i<=P;i++)
pwr=pwr*N;
return pwr;
}
long int func(long int N,int P)
{long int pwr=1;
int i;
for(i=1;i<=P;i++)
pwr=pwr*N;
return pwr;
}
float func(float N,int P)

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{float pwr=1.0;
int i;
for(i=1;i<=P;i++)
pwr=pwr*N;
return pwr;
}
void func(char N,int P)
{int i;
for(i=1;i<=P;i++)
cout<<N<<" ";
}
8. Using the same function name for member function and ordinary function. Create a class timex
with data members min and sec . Write a member function to get input of time and another to
display time. Write another member function add to add two timex objects and also use the same
function name to add two normal variables.
#include<iostream>
using namespace std;
class timex
{ int min;
int sec;
public:
void getd()
{ cin>>min>>sec;

}
void disp()
{ cout<<min<<":"<<sec;
}
void add(timex a,timex b)
{ a.sec+=b.sec+a.min*60+b.min*60;
a.min=a.sec/60;
a.sec=a.sec%60;
cout<<a.min<<":"<<a.sec<<endl;
}
};
int add(int a,int b)
{ int c;
c=a+b;
return c;
}
int main()
{ timex a,b,c;
a.getd();
b.getd();
c.add(a,b);//member function called
int x,y;//ordinary int variables
cin>>x>>y;
cout<<"x+y= "<<add(x,y);
}
9. To write a program to find the multiplication values and the cubic values using inline function.

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include<iostream>
using namespace std;
class line
{ public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{ return(x*x*x);}
};
void main()
{line obj;
float val1,val2;
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is :"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
}
Output:
Enter two values:57
Multiplication Value is: 35
Cube Value is: 25 343

10. To find the largest of the two using inline functions


#include<iostream>
using namespace std;
inline int largest(int x, int y);
int main()
{ int n1,n2;
cout<<"enter two values";
cin>>n1>>n2;
cout<<"the largest is"<<largest(n1,n2);
}
int largest(int x, int y)
{
return((x > y)?x:y);
}
Output:
enter two values89
the largest is9
____________________________________________________________________________________
__________________________________________________________________
CLASSES, CONSTRUCTORS AND DESTRUCTORS
11. Class and constructor
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{ cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{ length = len;
}
double Line::getLength( void )
{ return length;
}
// Main function for the program
int main( )
{ Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
#include <iostream>
using namespace std;
class Line
{ public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
Line::Line(void)
{ cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{ length = len;
}
double Line::getLength( void )
{ return length;
}
int main( )
{ Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Parameterized Constructor

12. A default constructor does not have any parameter, but if you need, a constructor can have parameters. This
helps you to assign initial value to an object at the time of its creation as shown in the following example:

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{ cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{ length = len;
}
double Line::getLength( void )
{ return length;
}
int main( ) {
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}

The Class Destructor


13. A destructor is a special member function of a class that is executed whenever an object of it's class goes out
of scope or whenever the delete expression is applied to a pointer to the object of that class.A destructor will have
exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out of the program like closing
files, releasing memories etc.
Following example explains the concept of destructor:
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
Line::Line(void)
{ cout << "Object is being created" << endl;
}
Line::~Line(void)

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{ cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{ length = len;
}
double Line::getLength( void )
{ return length;
}
// Main function for the program
int main( )
{ Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
14. destructor
#include <iostream>
using namespace std;
class Line
{ public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
Line::Line(void)
{ cout << "Object is being created" << endl;
}
Line::~Line(void)
{ cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{ length = len;
}
double Line::getLength( void )
{ return length;
}
int main( )
{ Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
15.class and object
#include<iostream.h>
#include<conio.h>
class sort_search
{public:

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
int a[10],n,t;
void sort();
void search();
};
void sort_search::sort()
{cout<<"enter the size"<<endl;
cin>>n;
cout<<"enter the array elements"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
{for(int j=0;j<(n-i-1);j++)
{if(a[j]>a[j+1])
{t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
cout<<"the sorted array is "<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}
void sort_search::search()
{int n,a[10],data,flag=0;
cout<<"enter the size"<<endl;
cin>>n;
cout<<"enter the array elements"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"enter the number to be searched"<<endl;
cin>>data;
for(i=0;i<n;i++)
{if(a[i]==data)
{ flag=1;break;
}
}
if(flag==1)
cout<<"the given data"<<" "<<data<<" "<<"present in the location"<<" "<<i+1<<endl;
else
{cout<<"the given data is not present in the array"<<endl;
}
}
void main()
{int ch;
sort_search ss;
do
{cout<<"sorting and searchimg"<<endl;
cout<<"main menu"<<endl;
cout<<"1.sort"<<endl;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<"2.search"<<endl;
cout<<"3.quit"<<endl;
cout<<"enter your choice"<<endl;
cin>>ch;
if(ch==1)
{ss.sort();
}
else if(ch==2)
{ss.search();
}
}while(ch<3);
}

16.Write a C++ program to create a class called Complex and implement the following
overloading functions ADD that returns a complex number:
1. ADD (a,s2)- where a is an integer(real part) and s2 is a complex number.
2. ADD (s1,s2)-where s1 and s2 are complex numbers.
#include<iostream>
using namespace std;
class complex
{ int rp;
int ip;
public:
complex()
{}
complex(int x,int y)
{ rp=x;ip=y;
}
complex add(int a,complex s1)
{ complex c;
c.rp=a+s1.rp;
c.ip=s1.ip;
return c;
}
complex add (complex s1,complex s2)
{ return complex((s1.rp+s2.rp),(s1.ip+s2.ip));
}
void disp()
{ cout<<endl<<rp<<" "<<ip;

}
};
int main()
{complex s1(10,25),s2(20,35),s3;
int a=10;
s3.add(a,s1);
s3.disp();
s3.add(s1,s2);
s3.disp();
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
17. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll.
Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the
number of cars that have gone by, and of the total amount of money collected. Model this tollbooth
with a class called tollBooth. The two data items are a type unsigned int to hold the total number
of cars, and a type double to hold the total amount of money collected. A constructor initializes
both of these to 0. A member function called payingCar() increments the car total and adds 0.50 to
the cash total. Another function, called nopayCar(), increments the car total but adds nothing to
the cash total. Finally, a member function called display() displays the two totals. Make
appropriate member functions const.
Include a program to test this class. This program should allow the user to push one key
to count a paying car, and another to count a nonpaying car. Pushing the Esc key should
cause the program to print out the total cars and total cash and then exit.
#include<iostream.h>
class tollbooth
{unsigned int p,n;
double a;
public:
tollbooth()
{p=0;n=0;}
void paying_car()
{p++;
a=p*50;
}
void nonpay_car()
{n++;
}
void display()
{ cout<<"No of paying cars "<<p;
cout<<"\nNo of non-paying cars "<<n;
cout<<"\ntotal cars "<<n+p;
cout<<"\namt collected "<<a;
}
};
void main()
{ tollbooth t;
char c;
cout<<"enter p/P for paying cars n/N for non-paying cars\n";
do
{cin>>c;
if(c=='p'||c=='P')
t.paying_car();
else if(c=='n'||c=='N')
t.nonpay_car();
}while(c!='s');
t.display();
}
18.Array of objects
#include<iostream.h>
#include<iomanip.h>
using namespace std;
class employee
{private:
int eno;
char name[20];

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
public:
void getData()
{ cin>>eno>>name;
}
void putData()
{cout<<setw(10)<<eno<<setw(10)<<name<<'\n';}
};

int main()
{int i,n;
employee e[10];
cout<<"enter number of employee ";
cin>>n;
for(i=0;i<n;i++)
e[i].getData();
cout<<setiosflags(ios::left);
cout<<setw(10)<<"Employye no"<<setw(10)<<"Employee name\n";
cout<<setw(10)<<"___________"<<setw(10)<<"_________ \n";
for(i=0;i<n;i++)
e[i].putData();
}

19.Passing arrays of distance objects


Array of object - avg of 10 distances
#include<iostream.h>
class distance
{ int feet;
float inches;
public:
void getdata()
{ cout<<"\nEnter feet and inches ; ";
cin>>feet>>inches;
}
void putdata()
{ cout<<endl<<feet<<"\t"<<inches;
}
void avgdistance(distance *d) //void avgdistance(class distance d)
{ int i;
int totalfeet=0;
float totalinches=0;
float avgdistancefeet,avgdistanceinches;

for(i=0;i<3;i++)
{ totalfeet+=d[i].feet;
totalinches+=d[i].inches;
}
totalfeet+=(totalinches/12);
totalinches=totalinches%12;
avgdistancefeet=(float)totalfeet/3;
avgdistanceinches=totalinches/3;
cout<<endl<<"The average distance is ..."<<avgdistancefeet<<" feet "<<avgdistanceinches<<"
inches"<<endl;
}
};
int main()
{distance d[3];
for(int i=0;i<3;i++)
d[i].getdata();

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<"\n-----------------------------------------------------";
for(i=0;i<3;i++)
d[i].putdata();
cout<<"\n-----------------------------------------------------";
d[0].avgdistance(d);
}

OPERATOR OVERLOADING AND DATA CONVERSION


OVERLOADING UNARY OPERATORS
20.Overloading unary minus:
#include<iostream>
using namespace std;
class space
{int x;
int y;
int z;
public:
void getdata(int a,int b,int c);
void display(void);
void operator-();
};
void space::getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{cout<< x <<" ";
cout<< y <<" ";
cout<< z <<"\n";
}
void space:: operator-()
{x=-x;
y=-y;
z=-z;
}
int main()
{space s;
s.getdata(10,-20,30);
cout<<"s: ";
s.display();
-s;
cout<<" s : ";
s.display();
return 0;
}
21.Overloading ++ operator without return type for overloaded operator function:
#include <iostream>
using namespace std;
class Counter

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{private:
unsigned int count; //count
public:
Counter() : count(0) //constructor
{}
unsigned int get_count() //return count
{ return count; }
void operator ++ () //increment (prefix)
{
++count;
}
};
int main()
{Counter c1, c2; //define and initialize
cout << \nc1= << c1.get_count(); //display
cout << \nc2= << c2.get_count();
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
cout << \nc1= << c1.get_count(); //display again
cout << \nc2= << c2.get_count() << endl;
return 0;
}

22.Overloading ++ operator with return type for overloaded operator function:


#include <iostream>
using namespace std;
class Counter
{private:
unsigned int count; //count
public:
Counter() : count(0) //constructor
{}
unsigned int get_count() //return count
{ return count; }
Counter operator ++ () //increment count
{++count; //increment count
Counter temp; //make a temporary Counter
temp.count = count; //give it same value as this obj
return temp; //return the copy
}
};
int main()
{Counter c1, c2; //c1=0, c2=0
cout << \nc1= << c1.get_count(); //display
cout << \nc2= << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << \nc1= << c1.get_count(); //display again
cout << \nc2= << c2.get_count() << endl;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return 0;
}

23.Example program to create nameless temporary objects:


#include <iostream>
using namespace std;
class Counter
{private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{}
Counter(int c) : count(c) //constructor, one arg
{}
unsigned int get_count() //return count
{ return count; }
Counter operator ++ () //increment count
{++count; // increment count, then return
return Counter(count); // an unnamed temporary object
} // initialized to this count
};
int main()
{Counter c1, c2; //c1=0, c2=0
cout << \nc1= << c1.get_count(); //display
cout << \nc2= << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << \nc1= << c1.get_count(); //display again
cout << \nc2= << c2.get_count() << endl;
return 0;
}
24.Overloading both postfix and prefix ++ operators:
#include <iostream>
using namespace std;
class Counter
{private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{}
Counter(int c) : count(c) //constructor, one arg
{}
unsigned int get_count() const //return count
{ return count; }
Counter operator ++ () //increment count (prefix)
{ //increment count, then return
return Counter(++count); //an unnamed temporary object
} //initialized to this count
Counter operator ++ (int) //increment count (postfix)
{ //return an unnamed temporary

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return Counter(count++); //object initialized to this
} //count, then increment count
};
int main()
{ Counter c1, c2; //c1=0, c2=0
cout << \nc1= << c1.get_count(); //display
cout << \nc2= << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2 (prefix)
cout << \nc1= << c1.get_count(); //display
cout << \nc2= << c2.get_count();
c2 = c1++; //c1=3, c2=2 (postfix)
cout << \nc1= << c1.get_count(); //display again
cout << \nc2= << c2.get_count() << endl;
return 0;
}
OVERLOADING BINARY OPERATORS:
25.Overloading + operator to add to two complex numbers:
#include<iostream>
using namespace std;
class complex
{ float x;
float y;
public:
complex()
{}
complex(float real,float imaginary)
{ x=real;
y=imaginary;
}
complex operator+(complex);
void display(void);
};
complex complex :: operator + (complex c)
{ complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return temp;
}
void complex :: display(void)
{cout<< x << " + i "<< y <<"\n";
}
int main()
{ complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
c3.display():
return 0;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
26.Overloading '+' operator to add two time objects:
#include <iostream>
using namespace std;
class time
{ private:
int hrs, mins, secs;
public:
time() : hrs(0), mins(0), secs(0) //no-arg constructor
{ } //3-arg constructor
time(int h, int m, int s) : hrs(h), mins(m), secs(s)
{}
void display() //format 11:59:59
{ cout << hrs << : << mins << : << secs; }
time operator + (time t2) //add two times
{ int s = secs + t2.secs; //add seconds
int m = mins + t2.mins; //add minutes
int h = hrs + t2.hrs; //add hours
if( s > 59 ) //if secs overflow,
{ s -= 60; m++; } // carry a minute
if( m > 59 ) //if mins overflow,
{ m -= 60; h++; } // carry an hour
return time(h, m, s); //return temp value
}
};
int main()
{ time time1(5, 59, 59); //create and initialze
time time2(4, 30, 30); // two times
time time3; //create another time
time3 = time1 + time2; //add two times
cout << \ntime3 = ; time3.display(); //display result
cout << endl;
return 0;
}

27.Overloading '-' operator to substract two distance objects:


#include <iostream>
using namespace std;
class Distance //English Distance class
{ private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{cout << \nEnter feet: ; cin >> feet;
cout << Enter inches: ; cin >> inches;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
void showdist() //display distance
{ cout << feet << \- << inches << \; }
Distance operator + ( Distance ); //add two distances
Distance operator - ( Distance ); //subtract two distances
};
//add d2 to this distance
Distance Distance::operator + (Distance d2) //return the sum
{ int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
i -= 12.0; //by 12.0 and
f++; //increase feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to sum
}
//subtract d2 from this dist
Distance Distance::operator - (Distance d2) //return the diff
{int f = feet - d2.feet; //subtract the feet
float i = inches - d2.inches; //subtract the inches
if(i < 0) //if inches less than 0,
{ //then increase inches
i += 12.0; //by 12.0 and
f--; //decrease feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to difference
}
int main()
{Distance dist1, dist3; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(3, 6.25); //define, initialize dist2
dist3 = dist1 - dist2; //subtract
//display all lengths
cout << \ndist1 = ; dist1.showdist();
cout << \ndist2 = ; dist2.showdist();
cout << \ndist3 = ; dist3.showdist();
cout << endl;
}
28.Overloading + operator to add to two distance objects:
#include <iostream>
using namespace std;
class Distance //English Distance class
{private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{} //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
void getdist() //get length from user
{cout << \nEnter feet: ; cin >> feet;
cout << Enter inches: ; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << \- << inches << \; }
Distance operator + ( Distance ) const; //add 2 distances
};
//add this distance to d2
Distance Distance::operator + (Distance d2) const //return sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
i -= 12.0; //by 12.0 and
f++; //increase feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to sum
}
int main()
{Distance dist1, dist3, dist4; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2; //single + operator
dist4 = dist1 + dist2 + dist3; //multiple + operators
//display all lengths
cout << dist1 = ; dist1.showdist(); cout << endl;
cout << dist2 = ; dist2.showdist(); cout << endl;
cout << dist3 = ; dist3.showdist(); cout << endl;
cout << dist4 = ; dist4.showdist(); cout << endl;
}
29.Overloading + operator to concatenate two strings:
#include <iostream>
using namespace std;
#include <string.h> //for strcpy(), strcat()
#include <stdlib.h> //for exit()
class String //user-defined string type
{enum { SZ=80 }; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor, no args
{ strcpy(str, ); }
String( char s[] ) //constructor, one arg
{ strcpy(str, s); }
void display() const //display the String
{ cout << str; }
String operator + (String ss) const //add Strings
{String temp; //make a temporary String
if( strlen(str) + strlen(ss.str) < SZ )

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{strcpy(temp.str, str); //copy this string to temp
strcat(temp.str, ss.str); //add the argument string
}
else
{ cout << \nString overflow; exit(1); }
return temp; //return temp String
}
};
int main()
{String s1 = \nMerry Christmas! ; //uses constructor 2
String s2 = Happy new year!; //uses constructor 2
String s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1,
//assign to s3
s3.display(); //display s3
cout << endl;
return 0;
}
30. Overloaded arthimetic operators to work with type int:
#include <iostream>
using namespace std;
#include <process.h> //for exit()
class Int
{private:
int i;
public:
Int() : i(0) //no-arg constructor
{}
Int(int ii) : i(ii) //1-arg constructor
{ } // (int to Int)
void putInt() //display Int
{ cout << i; }
void getInt() //read Int from kbd
{ cin >> i; }
operator int() //conversion operator
{ return i; } // (Int to int)
Int operator + (Int i2) //addition
{ return checkit( long double(i)+long double(i2) ); }
Int operator - (Int i2) //subtraction
{ return checkit( long double(i)-long double(i2) ); }
Int operator * (Int i2) //multiplication
{ return checkit( long double(i)*long double(i2) ); }
Int operator / (Int i2) //division
{ return checkit( long double(i)/long double(i2) ); }
Int checkit(long double answer) //check results
{if( answer > 2147483647.0L || answer < -2147483647.0L )
{ cout << \nOverflow Error\n; exit(1); }

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return Int( int(answer) );
}
};
int main()
{Int alpha = 20;
Int beta = 7;
Int delta, gamma;
gamma = alpha + beta; //27
cout << \ngamma=; gamma.putInt();
gamma = alpha - beta; //13
cout << \ngamma=; gamma.putInt();
gamma = alpha * beta; //140
cout << \ngamma=; gamma.putInt();
gamma = alpha / beta; //2
cout << \ngamma=; gamma.putInt();
delta = 2147483647;
gamma = delta + alpha; //overflow error
delta = -2147483647;
gamma = delta - alpha; //overflow error
cout << endl;
return 0;
}

31.Overloading '+' operator to add dimensions of two box objects:


#include <iostream>
using namespace std;
class Box {
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return box;
}
};
int main( )
{ Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
}

32.Overloading '<' operator to compare two distance objects:


#include <iostream>
using namespace std;
class Distance //English Distance class
{private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{cout << \nEnter feet: ; cin >> feet;
cout << Enter inches: ; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << \- << inches << \; }
bool operator < (Distance) const; //compare distances
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
//compare this distance with d2
bool Distance::operator < (Distance d2) const //return the sum
{float bf1 = feet + inches/12;
float bf2 = d2.feet + d2.inches/12;
return (bf1 < bf2) ? true : false;
}
int main()
{Distance dist1; //define Distance dist1
dist1.getdist(); //get dist1 from user
Distance dist2(6, 2.5); //define and initialize dist2
//display distances
cout << \ndist1 = ; dist1.showdist();
cout << \ndist2 = ; dist2.showdist();
if( dist1 < dist2 ) //overloaded < operator
cout << \ndist1 is less than dist2;
else
cout << \ndist1 is greater than (or equal to) dist2;
cout << endl;
return 0;
}

33.Overloading == operators to compare two strings:


#include <iostream>
using namespace std;
#include <string.h> //for strcmp()
class String //user-defined string type
{private:
enum { SZ = 80 }; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor, no args
{ strcpy(str, ); }
String( char s[] ) //constructor, one arg
{ strcpy(str, s); }
void display() const //display a String
{ cout << str; }
void getstr() //read a string
{ cin.get(str, SZ); }
bool operator == (String ss) const //check for equality
{return ( strcmp(str, ss.str)==0 ) ? true : false;
}
};
int main()
{String s1 = yes;
String s2 = no;
String s3;
cout << \nEnter yes or no: ;
s3.getstr(); //get String from user
if(s3==s1) //compare with yes
cout << You typed yes\n;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
else if(s3==s2) //compare with no
cout << You typed no\n;
else
cout << You didnt follow instructions\n;
return 0;
}

34.Overloading arithmetic assignment operator(+=) to add two distance objects:


#include <iostream>
using namespace std;
class Distance //English Distance class
{private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{}
void getdist() //get length from user
{cout << \nEnter feet: ; cin >> feet;
cout << Enter inches: ; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << \- << inches << \; }
void operator += ( Distance );
};
//add distance to this one
void Distance::operator += (Distance d2)
{feet += d2.feet; //add the feet
inches += d2.inches; //add the inches
if(inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet
} //by 1
}
int main()
{Distance dist1; //define dist1
dist1.getdist(); //get dist1 from user
cout << \ndist1 = ; dist1.showdist();
Distance dist2(11, 6.25); //define, initialize dist2
cout << \ndist2 = ; dist2.showdist();
dist1 += dist2; //dist1 = dist1 + dist2
cout << \nAfter addition,;
cout << \ndist1 = ; dist1.showdist();
cout << endl;
return 0;
}
35.example program to Overload subscript operator([]) :

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
class safearay
{private:
int arr[LIMIT];
public:
int& operator [](int n) //note: return by reference
{if( n< 0 || n>=LIMIT )
{ cout << \nIndex out of bounds; exit(1); }
return arr[n];
}
};
int main()
{safearay sa1;
for(int j=0; j<LIMIT; j++) //insert elements
sa1[j] = j*10; //*left* side of equal sign
for(j=0; j<LIMIT; j++) //display elements
{int temp = sa1[j]; //*right* side of equal sign
cout << Element << j << is << temp << endl;
}
return 0;
}
36.Example program for both left and right hand side calling of a function:
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
class safearay
{private:
int arr[LIMIT];
public:
int& access(int n) //note: return by reference
{if( n< 0 || n>=LIMIT )
{ cout << \nIndex out of bounds; exit(1); }
return arr[n];
}
};
int main()
{safearay sa1;
for(int j=0; j<LIMIT; j++) //insert elements
sa1.access(j) = j*10; //*left* side of equal sign
for(j=0; j<LIMIT; j++) //display elements
{int temp = sa1.access(j); //*right* side of equal sign
cout << Element << j << is << temp << endl;
}
return 0;
}
37.overloading '<<' Operator to print time object:

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include<iostream.h>
#include<conio.h>
class time
{ int hr,min,sec;
public:
time()
{ hr=0, min=0; sec=0;
}
time(int h,int m, int s)
{ hr=h, min=m; sec=s; }
friend ostream& operator << (ostream&out, time &tm); //overloading '<<' operator
};
ostream& operator<< (ostream&out, time &tm) //operator function
{ out << "Time is " << tm.hr << "hour : " <<tm.min<< "min : " <<tm.sec<< "sec";
return out;
}
void main()
{ time tm(3,15,45);
cout<< tm; }

38. overloading operations on matrix.


#include<iostream.h>
#include<conio.h>
int i,j,k,t,u,c;
class mat
{int m,n;
int a [3] [3];
public:
mat() {}
void getdata ();
void operator +(mat);
void operator -(mat);
void operator *(mat);
};
void mat :: getdata()
{cout<<"enter row and col";
cin>>m>>n;
cout <<" enter the elements of matnx a";
for (i=0; i<m; i++)
{for ( j=0; j<n; j++)
{cin >>a[i][j];}
}
}
void mat :: operator +(mat c)
{mat d;
cout <<" addition value" <<endl;
for (i=0; i<m; i++)
{for (j=0; j<n; j++)
{d.a[i] [j] =a[i] [j]+c.a[i] [j];
cout <<d. a[i] [j] <<"\t";

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}cout << endl;
}
}
void mat :: operator -(mat c)
{mat d;
cout <<" subtracted value" <<endl;
for (i=0; i<m; i++)
{for (j=0; j<n; j++)
{d.a[i] [j] =a[i] [j]-c.a[i] [j];
cout <<d. a[i] [j] <<"\t";
}cout << endl;
}
}
void mat :: operator *(mat u)
{mat f;
cout <<" multiplication value : " << endl;
for (i=0 ; i<m; i++)
{ for (j=0 ; j<n ; j++)
{ f. a [i] [j]= 0;
for (int k=0; k<u.m ; k++)
{ f. a[i] [j]= f.a[i] [j]+(a [i] [k]*u.a[k][j]);
}
cout<<f.a[i] [j]<<"\t";
}
cout<< endl;
}
}
main()
{ mat p,q;
p.getdata();
q.getdata();
p+q;
p-q;
p*q;
}

PROGRAMS BASED ON DATA CONVERSION:


39.program gives how compiler implicitly converts basic data types.
#include <iostream>
using namespace std;
int main()
{ int num1;
float num2 = 5.615;
num1=num2;//float convertion to int
cout<<num1;
}

40.program gives how compiler explicitly converts basic data types.


#include <iostream>
using namespace std;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
int main()
{ int num1;
float num2 = 5.615;
num1=static_cast<int>(num2);
cout<<num1;
}
41.Conversion from basic to user defined data type.
#include <iostream>
using namespace std;
const float MeterToFloat=3.280833;
class Distance
{ int feets;
float inches;
public:
Distance() //Distance Constructor
{ feets=0;
inches=0.0;
}
Distance(float numofmeters) //Single Parameter constructor
{ float feetsinfloat= MeterToFloat * numofmeters;
feets=int(feetsinfloat);
inches=12*(feetsinfloat-feets);
}
void displaydist() // Method to display converted values
{ cout<<"Converted Value is: "<<feets<<"\' feets<<"
inches"<<inches<<'\"'<<" inches.";
}
};
int main()
{ cout <<"Float to distance conversion.\n********************************\n";
float meters;
cout<<"Enter values in meter:";
cin >>meters;
Distance distance = meters;
distance.displaydist();
}
42.Conversion from user defined data type to basic data type
#include <iostream>
using namespace std;
const float MeterToFloat=3.280833;
// Meter to feet
class Distance
{ int feet;
float inches;
public:
Distance()// Default Constructor?
{ feet=0;
inches=0.0;
}
Distance(int ft, float in) //two arguments constructor

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{ feet=ft;
inches=in;
}
operator float() //overloaded casting operator
{ float feetinfractions=inches/12;
feetinfractions+=float(feet);
return (feetinfractions/MeterToFloat);
}
};
int main()
{ int feet;
float inches;
cout <<"Enter distance in Feet and Inches.";
cout<<"\nFeet:";
cin>>feet;
cout<<"Inches:";
cin>>inches;
Distance dist(feet, inches);
float meters=dist;
// This will call overloaded casting operator
cout<<"Converted Distance in Meters is: "<< meters;
}
43.progarm to convert user defined class of types feet,inches class to metres,centimetres class or
vice versa:-
#include<iostream>
#include<math.h>
using namespace std;
class distancemetre
{ private:
int metre;
float centimetre;
public:
distancemetre()// defualt constructor
{ metre=0;
centimetre=0.0;
}
distancemetre(int m,float c)//paramatric constructor
{ metre=m;
centimetre=c;
}
int getmetre()
{ return metre;
}
int getcentimetre()
{ return centimetre;
}
void display()
{ cout<<"Metre= "<<metre<<endl<<"Centimetre= "<<centimetre<<endl;
}
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class distancefeet
{ private:
int feet;
float inch;
public:
distancefeet():feet(0),inch(0)
{}
distancefeet(int f,float i)
{ feet=f;
inch=i;
}
distancefeet(distancemetre d)
{ float in=(d.getmetre()*100+d.getcentimetre())/2.54;
feet=in/12;
inch=fmod(in,12);
}
operator distancemetre()
{ float a=feet*12+inch;
int m=(a*2.54)/100;
float cm=(a*2.54)-(m*100);
return distancemetre(m,cm);
}
void display()
{ cout<<"Feet= "<<feet<<endl<<"inches= "<<inch<<endl;
}
};
int main()
{ int n;
int a;
float b;
cout<<"Enter 1 to convert metre to feet type or 2 to convert feet to metre type";
cin>>n;
switch(n)
{ case 1:
cout<<"Enter metre of int value ";
cin>>a;
cout<<"Enter centimetre of float or int value ";
cin>>b;
distancemetre dm(a,b);
dm.display();
distancefeet df(dm);/*conversion takes place in constructor
df.display();
break;
case 2:
cout<<"Enter feet of int value ";
cin>>a;
cout<<"Enter inches of float or int value ";
cin>>b;
distancefeet df1(a,b);
df1.display();

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
distancemetre dm1;
dm1=df1;
dm1.display();
break;
}
}
44. Conversion between C strings and string objects:
#include<iostream>
#include<string.h>
using namespace std;
class String
{ private:
enum{sz=80};
char str[sz]
public:
String()
{ str[0]='\0';
}
String(char a[])
{ strcpy(str,a);
}
void get()
{ cin.getline(str,80);
}
void display()
{ cout<<"string that you entered is "<<endl<<str<<endl;
}
operator char*()//conversion operator
{ return str;
}
};
int main()
{ char a[30];//normal c string
cout<<"Enter the string";
cin.getline(a,30);/*gets the input as char array and stores them in a*/
String s=a;//uses parametric construtor
s.display();
String s1="bonne annee!!!";
char b[30];
strcpy(b,static_cast<char*>(s1));/*convrsion using overloaded operator*/
cout<<"string that changed from string obj to char array"<<endl;
cout<<b<<endl;
}
45.Program to convert time12 to time24 and vice versa:
#include<iostream>
#include<string.h>
using namespace std;
class time12
{ private:
char meridian[2];

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
int hours12,minutes12,seconds12;
public:
time12()
{}
time12(char a[],int h,int m,int s)
{ strcpy(meridian,a);
hours12=h;
minutes12=m;
seconds12=s;
}
void get12()
{ cout<<"Enter hours= ";
cin>>hours12;
cout<<"Enter minutes= ";
cin>>minutes12;
cout<<"Enter seconds= ";
cin>>seconds12;
cout<<"Enter pm or am";
cin>>meridian;
}
string getpm_am()
{ return meridian;
}
int gethours12()
{ return hours12;
}
int getminutes12()
{ return minutes12;
}
int getseconds12()
{ return seconds12;
}
void display12()const
{ cout<<"Time in 12 format is"<<endl;
cout<<hours12<<"-"<<minutes12<<"-"<<seconds12<<" "<<meridian<<endl;
}
};
class time24
{ private:
int hour24;
int min24;
int seconds24;
public:
time24()
{}
time24(int h,int m,int s)
{ hour24=h;
min24=m;
seconds24=s;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
time24(time12 t12)
{if(t12.getpm_am()=="pm")
{
if(t12.gethours12()==12)
{ hour24=t12.gethours12();
}
else
{ hour24=t12.gethours12()+12;
}
min24=t12.getminutes12();
seconds24=t12.getseconds12();
}
else
{ if(t12.gethours12()==12)
{ hour24=00;
}
else
{ hour24=t12.gethours12();
}
min24=t12.getminutes12();
seconds24=t12.getseconds12();
}
}
void gettime24()
{ cout<<"Enter hours= ";
cin>>hour24;
cout<<"Enter minutes= ";
cin>>min24;
cout<<"Enter seconds= ";
cin>>seconds24;
}
operator time12()
{ int h,m,s;
char a[2];
if(hour24==12)
{ h=12;
strcpy(a,"pm");
}
if(hour24<12)
{ h=hour24;
strcpy(a,"am");
if(hour24>12)
{ h=hour24-12;
strcpy(a,"pm");
}
if(hour24==0)
{ strcpy(a,"am");
h=12;
}
m=min24;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
s=seconds24;
return time12(a,h,m,s);
}
}
void display24()
{cout<<"Time in 24 format is"<<endl;
cout<<hour24<<"-"<<min24<<"-"<<seconds24<<endl;
}
};
int main()
{ int n;
cout<<"Enter 1 to convert 12 to 24 or 2 for vice verse";
cin>>n;
switch(n)
{ case 1:
time12 t12;
t12.get12();
t12.display12();
time24 t24(t12);
t24.display24();
break;
case 2:
time24 t24a;
t24a.gettime24();
t24a.display24();
time12 t12a=t24a;
t12a.display12();
break;
}
}

46. data conversion


#include<iostream.h>
class tim
{
int hrs,min,sec;

public:
tim() {hrs=0;min=0;sec=0;}
tim(long int i)
{
min=i/60;
min=min%60;
hrs=i/3600;
sec=i%60;
}
disp()
{cout<<hrs<<":"<<min<<":"<<sec;
}
};
int main()
{long int l;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cin>>l;

tim m(l);
m.disp();
return 0;
}
_________________________________________________________
POINTERS
47. GENERIC POINTER
#include <iostream>
using namespace std;
int main()
{ int *a,a1=5;
float* b,b1=10;
void *c;

b=&b1;
a=&a1;

cout<<"\nThe value of the integer pointer is: "<<*a;


cout<<"\nThe value of the float pointer is: "<<*b;

c=&a1;
cout<<"The value of the generic pointer can be ( pointing to an integer ):
"<<*static_cast<int*>(c);
c=&b1;
cout<<" and (pointing to a float ): "<<*static_cast<float*>(c);

a=reinterpret_cast<int*>(b);
cout<<"\nThe value of a float pointer pointing to an integer is: "<<*b;
}

The value of the integer pointer is: 5


The value of the float pointer is: 10
The value of the generic pointer can be ( pointing to an integer ): 5 and (pointing to a float ): 10
The value of a float pointer pointing to an integer is: 10

48. POINTERS AND ARRAYS


#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5,6,7};
int *ptr;
ptr=a;
cout<<"Manipulations done: ";
cout<<'\n'<<*ptr;
cout<<'\n'<<*ptr++;
cout<<'\n'<<*(++ptr);
cout<<'\n'<<(*ptr)++;
cout<<'\n'<<*ptr<<'\n';
char s[]="Helloo";
char*sptr;
sptr=s;
cout<<'\n'<<*sptr;
cout<<'\n'<<sptr;
cout<<'\n'<<*sptr++;
cout<<'\n'<<*++sptr;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
Manipulations done:
1
1
3
3
4

H
Helloo
H
l
___________________________________________________________________________

49 POINTERS AND CALL BY REFERENCES


#include <iostream>
using namespace std;
void change(int &a)
{
a++;
}

void changeptr(int *a)


{
(*a)++;
}

int main()
{ int x=5;
cout<<"\nFIRST TYPE: ";
cout<<"\nBEFORE: "<<x;
change(x);
cout<<"\nAFTER: "<<x;

cout<<"\nSECOND TYPE: ";


cout<<"\nBEFORE: "<<x;
changeptr(&x);
cout<<"\nAFTER: "<<x;

return 0;
}
FIRST TYPE:
BEFORE: 5
AFTER: 6
SECOND TYPE:
BEFORE: 6
AFTER: 7

50.CONSTANT POINTER AND POINTER TO A CONSTANT


#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
const int* ptr=a;
int* const p=a;
cout<<*ptr<<" ";

cout<<*(++ptr)<<" ";

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<'\n'<<*p<<" "<<(*p)++;
return 0;
}

12
21

51. DYNAMIC MEMORY ALLOCATION


#include <iostream>
#include<string.h>
using namespace std;
int main() {
char s[]="HELLO ALL.",*p;
int l;
l=strlen(s);
p=new char[l+1];
strcpy(p,s);
cout<<p;
cout<<*p;
delete[]p;
return 0;
}

HELLO ALL.
H

52.THIS POINTER
#include<iostream.h>
using namespace std;
class max
{ int a;
public:
void getdata()
{ cout<<"Enter the Value :";
cin>>a;
}
max &greater(max &x)
{ if(x.a>=a)
return x;
elsereturn *this;
}
void display()
{ cout<<"Maximum No. is : "<<a<<endl;
}
};
main()
{ max one,two,three;
one.getdata();
two.getdata();
three=one.greater(two);
three.display();
}
53. Pointers for stack operations
#include<iostream.h>
#include<conio.h>
class stack

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{
int no[10];
public:
int top,size;
stack()
{top=-1;
}
void push();
void pop();
void display();
void search();
int isempty();
};
int stack::isempty()
{return (size==0?1:0);
}
void stack::push()
{cout<<"enter no of elements :";
cin>>size;
cout<<"enter elements :\n";
for(int i=0;i<size;i++)
{ cin>>no[i];
top++;
}
}
void stack::search()
{ int m;
cout<<"enter the no to be searched: ";
cin>>m;
int flag=0;
for(int i=0;i<size;i++)
{ if(no[i]==m)
{cout<<"the no is in "<<i+1<<" position\n";
flag=1;
}
}
if(flag==0)
cout<<"no not in stack\n";
}

void stack::pop()
{if(!isempty())
{ top--;
--size;
cout<<"stack top is deleted !!";
}
else
cout<<"stack is empty, u cant delete \n";
}

void stack ::display()


{ int n=top;
if(!isempty())
{ cout<<"output ";
for(int i=n;i>=0;i--)
{ cout<<no[i]<<" ";
}
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
else
cout<<"stack is empty, nothing to display\n";
}

void main()
{ stack a;
stack *ptr=&a;
int p,i,o;
char opt='y';
clrscr();
cout<<"enter the choice ";
while(opt=='y')
{ cout<<"\n1.insrt\n2.delete\n3.search\n4.display\n";
cin>>p;
switch(p)
{case 1:
ptr->push();
break;
case 2:
ptr->pop();
break;
case 3:
ptr->search();
break;
case 4:
ptr->display();
break;
}
cout<<"do u want to continue? ";
cin>>opt;
}
}

54. new operator


#include <string.h>
#include <iostream.h>
#include <conio.h>

class String {
char *s;
int len;

public:
String() {
s=new char[81];
len=80;
}
String(int n) {
s=new char[n + 1];
len=n;
}
String(char *p) {
len=strlen(p);
s=new char[len + 1];
strcpy(s, p);
}
String(String &str);

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
~String() {
delete []s;
}
void assign (char *str) {
strcpy(s, str);
len=strlen(str);
}
void print() {
cout << s << '\n';
}
void concat(String &a, String &b);
};

String::String(String &str) {
len=str.len;
s=new char[len + 1];
strcpy(s, str.s);
}

void String::concat(String &a, String &b) {


len=a.len + b.len;
delete []s;
s=new char[len + 1];
strcpy(s, a.s);
strcat(s, b.s);
strcpy(a.s, "ipek");
}

main()
{
clrscr();
char *str="Hello everybody. ";
String a(str), b, c("Have a nice day. "), both, quote=c;
b.assign("How are you? ");
both.concat(a, b);
quote.print();
a.print();
both.print();
return 0;
}
____________________________________________________________________________________

INHERITANCE
55.Simple Inheritance
//public access specifier
#include<iostream>
using namespace std;
class B
{ protected:
int a,b;
public:
void getdata()
{
cout<<"enter the two numbers"<<endl;
cin>>a>>b;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
void show()
{
cout<<"the numbers you entered are: <<a<<b;
}
};
class D:public B
{
int c;
public:
void mul()
{
c=a*b;
}
void display()
{
cout<<"result="<<c<<endl;
}
};
int main()
{ D d;
d.getdata();
d.show();
d.mul();
d.display();
}
Output:

56. private access specifier


#include<iostream>
using namespace std;
class B
{ protected:
int a,b;
public:
void getdata()
{ cout<<"enter the two numbers"<<endl;
cin>>a>>b;
}
void show()
{ cout<<"the numbers you entered are"<<endl;
cout<<a<<endl;
cout<<b<<endl;
}
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class D:private B
{ int c;
public:
void mul()
{
getdata();
c=a*b;
}
void display()
{
show();
cout<<"results="<<c<<endl;
}
};
int main()
{
D d;
d.mul();
d.display();
}
Output:

57.Multilevel Inheritance
#include<iostream>
using namespace std;
class student // base class
{
private:
int rl;
char nm[20];
public:
void read`()
{ cout<<"enter Roll no and Name ";
cin>>rl>>nm;
}
void display()
{ cout <<"Roll NO:"<<rl<<endl;
cout<<"name : "<<nm<<endl;
}
};
class marks : public student
{protected:
int s1;
int s2;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
int s3;
public:
void getmarks()
{ cout<<"enter three subject marks "<<endl;
cin>>s1>>s2>>s3;
}
void putmarks()
{ cout <<"subject 1:"<<s1<<endl;
cout<<" subject 2 : "<<s2<<endl;
cout <<"subject 3:"<<s3<<endl;
}
};
class result : public marks // derived from marks
{private:
int t;
float p;
public:
void process()
{ t= s1+s2+s3;
p = t/3.0;
}
void printresult()
{ cout<<"total = "<<t<<endl;
cout<<"per = "<<p<<endl;
}
};
int main()
{ result x;
x.read();
x.getmarks();
x.process();
x.display();
x.putmarks();
x.printresult();
}
Output:

58. Multiple inheritance


#include<iostream>

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
using namespace std;
class base1
{ protected:
int m;
public:
void get_m()
{ cout<<"enter m value"<<endl;
cin>>m;
}
};
class base2
{ protected:
int n;
public:
void get_n()
{ cout<<"enter n vakue"<<endl;
cin>>n;
}
};
class derived: public base1,public base2
{ public:
void display()
{ cout<<"m ="<<m<<endl;
cout<<"n ="<<n<<endl;
}
};
int main()
{ derived d1;
d1.get_m();
d1.get_n();
d1.display();
}
Output:

59.Multiple inheritance
#include<iostream.h>
#include<conio.h>
class emp
{
protected:
char name[10],gen;
int no,sal,age;
public:
int g;
void getdata()
{

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<"enter the number,name,gen,age and sal";
cin>>no>>name>>gen>>age>>sal;
cout<<"research interest?";
cin>>g;
}

void display()
{

cout<<"empno:"<<no<<"\nname:"<<name<<"\ngen:"<<gen<<"\nage:"<<age<<"\nsal:"<<sal;
}
};

class student
{
protected:
char name[10],dept[10];
int regno,yr;
float cgpa;
public:
int g;
void getdata()
{
cout<<"enter name , no,dept,yr,cgpa and research interest:";
cin>>name>>regno>>dept>>yr>>cgpa>>g;
}

void display()
{

cout<<"name:"<<name<<"\nregno:"<<regno<<"\ndept"<<dept<<"\nyr:"<<yr<<"\ncgpa"<<cgpa
;
}
};

class research : public emp,public student


{
public:
void display()
{
emp::display();
}

void display1()
{
student::display();
}
};
void main()
{ research q[25];
int i,j,u,v;
cout<<"no of employees";
cin>>v;
for(i=0;i<v;i++)
{ q[i].emp::getdata();
}
cout<<"enter no of students";
cin>>u;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
for(j=0;j<u;j++)
{q[j].student::getdata();
}
for(i=0;i<v;i++)
{if((q[i].emp::g)==1)
q[i].display();
}
for(j=0;j<u;j++)
{ if((q[j].student::g)==1)
q[j].display1();
}
}
60.Hierarchical Inheritance
#include <iostream>
using namespace std;
class Number
{ protected:
int num;
public:
void getNumber()
{ cout << "Enter an integer number: ";
cin >> num;
}
void display()
{ cout<<num<<endl;
}
};

//Base Class 1, to calculate square of a number


class Square:public Number
{ public:
void getSquare()
{ num=num*num;
}
void display()
{ cout<<num<<endl;
}
};
//Base Class 2, to calculate cube of a number
class Cube:public Number
{ public:
void getCube()
{ num=num*num*num;
}
void display()
{ cout<<num<<endl;
}
};
int main()
{ Square objS;
Cube objC;
int sqr,cube;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
objS.getNumber();
objS.getSquare();
objS.display();
objC.getNumber();
objC.getCube();
objC.display();
}
Output:

61. Hierarchical Inheritance


#include <iostream>
using namespace std;
class person
{ char name[100],gender[10];
int age;
public:
void getdata()
{ cout<<"Name: ";
cin>>name;
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{ cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};

class student: public person


{ char institute[100], level[20];
public:
void getdata()
{ person::getdata();
cout<<"Name of College/School: ";
cin>>institute;
cout<<"Level: ";
cin>>level;
}
void display()
{ person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class employee: public person
{ char company[100];
float salary;
public:
void getdata()
{ person::getdata();
cout<<"Name of Company: ";
cin>>company;
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{ person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
int main()
{ student s;
employee e;
s.getdata();
s.display();
e.getdata();
e.display();
}
Output:

62,. Hierarchical Inheritance


#include<iostream>
#include<conio.h>
using namespace std;
class Publication
{ protected:
string title;
float price;
public:
void getdata()
{ cout<<"\nEnter the title";

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cin>>title;
cout<<"\n Enter the price ";
cin>>price;
}
void putdata()
{ cout<<"\nTitle"<<"\t"<<title;
cout<<"\nPrice"<<"\t"<<price;
}
};
class Book:public Publication
{ int page_count;
public:
void getdata()
{ cout<<"\nEnter the book details";
Publication::getdata();
cout<<"\n Enter the page count of the book";
cin>>page_count;
}
void putdata()
{ cout<<"\nBook details";
Publication::putdata();
cout<<"\n pagecount"<<"\t"<<page_count;
}
};
class Tape:public Publication
{ int time;
public:
void getdata()
{ Publication::getdata();
cout<<"\n Enter the playing time ";
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";
cout<<"\n enter ur choice";
cin>>ch;
switch(ch)
{ case 1:
{
Book B;
B.getdata();
B.putdata();
break;
}
case 2:
{
Tape T;
T.getdata();

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
T.putdata();
break;
}
}
cout<<"\nDo you want to continue y/n";
cin>>op;
}while(op=='y'||op=='Y') ;
}
63. Hybrid Inheritance
#include<iostream>
using namespace std;
class student
{ protected:
int rollno;
public:
void getd()
{ cout<<"enter the rollnumber";
cin>>rollno;
}
void putd()
{ cout<<"rollnumber of the student is";
cout<<rollno<<endl;
}
};
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;
}
};
class sports
{ protected:
int score;
public:
void getdata()
{ cout<<"enter the score in sports quota"<<endl;
cin>>score;
}
void displays()
{ cout<<"score in sports quota"<<endl;
cout<<score<<endl;
}
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class result: public marks ,public sports
{private:
float total;
public:
void ans()
{
total=mark1+mark2+score;
}
void display()
{ cout<<"the total score of the student"<<endl;
cout<<total<<endl;
}
};
int main()
{ result r1;
r1.getd();
r1.getm();
r1.getdata();
r1.ans();
r1.putd();
r1.displaym();
r1.displays();
r1.display();
}
Output:

64. Ambiguity Resolution


//over riding in simple inheritance
#include<iostream>
using namespace std;
class A
{ public:
void display()
{
cout<<"A"<<endl;
}
};
class B:public A
{ public:
void display()

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{
cout<<"b"<<endl;
}
};
int main()
{ B a;
a.display();
a.A::display();
a.B::display();
}
Output:

65.over riding 2
#include<iostream>
using namespace std;
class m
{ public:
void display()
{
cout<<"m"<<endl;
}
};
class n
{ public:
void display()
{
cout<<"n"<<endl;
}
};
class p: public m,public n
{ public:
void display()
{ cout<<"p"<<endl;
m::display();
n::display();d
}
};
int main()
{ p p1;
p1.display();
}
Output:

66. Inheritance of constructors


#include<iostream>

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
using namespace std;
class A
{ public:
A()
{cout<<"a"<<endl;
}
A(int a)
{cout<<"a(int)"<<endl;
}
};
class B:public A
{ public:
B()
{
cout<<"b"<<endl;
}
B(int a)
{
cout<<"b(int)"<<endl;
}
};
class C:public B
{ public:
C()
{
cout<<"c"<<endl;
}
C(int a)
{
cout<<"c(int)"<<endl;
}
};
int main()
{ C obj1;
C obj2(5);
}

Output:
a
b
c
a
b(int)
67. ORDER OF CONSTRUCTOR CALLING WHEN A CLASS IS INHERITED VIRTUALLY
class Base1 { public:
Base1() { cout<<Base 1; }
};
class Base2 { public:
Base2(){ cout<<Base2; }
};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class Der:public Base1, virtual public Base2 { public:
Der() { cout<<Derived class; }
};
int main()
{
Der D; return 0; }

OUTPUT:
Base2
Base1
Derived Class
_______________________________________________________________

68. MISCELLANEOUS PROGRAMS


#include<iostream>
using namespace std;
class add
{private:
int a,b; //data members
public:
int sum;
void getdata() //member functions
{a=5;
b=9;
sum=a+b;
}
};
int main()
{add s; //creating objects
s.getdata();
cout<<s.sum; return0;
}
#include<iostream>
using namespace std;
class add
{private:
int a,b;
public:
int sum;
void getdata(); //prototyping the memberfunctions
};
void add:: getdata() //outside the class definition
{a=5;
b=9;
sum=a+b;
}
int main()
{add s; //creating objects
s.getdata();
cout<<s.sum;
}

#include<iostream>
using namespace std;
class abc

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{int a; //it is understood it is private even it is not mentioned so
protected:
int b;
public:
int c;
void getanddisp()
{cin>>a>>b>>c;
cout<<a;
cout<<b;
cout<<c; } };
int main()
{abc d;
cout<<d.a; //can't accesssinceit is a privatedata member
cout<<d.b; //can't access since it is declared in protected
cout<<d.c; //correct
d.getanddisp();
return 0;
}

69.#include<iostream>
using namespace std;
class abc
{int a,b;
public:
void setdata(int c,int d)
{a=c;
b=d;
}
void getdata()
{cin>>a>>b;
}
void display()
{cout<<"\n"<<a<<"\n"<<b;
} };
int main()
{abc x, v;
v.setdata(4,8);
cout<<"enter 2 values";
x.getdata();
v.display();
x.display();
}

70.#include<iostream>
using namespace std;
class abc
{int a,b;
public:
void setdata(int c,int d)
{a=c;
b=d;
display(); //nesting of member functions
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
void getdata()
{cout<<"\n enter 2 nos";
cin>>a>>b;
display();
}
void display()
{cout<<"\n"<<a<<"\n"<<b;
} };
int main()
{abc x, v;
v.setdata(4,8);
x.getdata();
return 0;
}

71.#include<iostream>
using namespace std;
class abc
{private:
int a,b;
void display() //member functions can also be private
{ cout<<a<<b;
}
public:
void setdata(int c,int d)
{a=c;
b=d;
display(); //calling private member functions
}
void getdata()
{cin>>a>>b;
display();
}
};
int main()
{abc x, v;
v.setdata(4,8);
v.display(); //error :display() is private can't be accessed from main()
x.getdata();
return 0; }

72. #include<iostream>
using namespace std;
class counter
{int a;
static int count;
public:
void getdata()
{cout<<enter a no;
cin>>a;
count++;
}
void display()

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{cout<<a=<<a;
}
static void show() //static member function can access only static data members
{cout<<no of object created<<count;}
};
int counter::count=0; //initialising a static data member
int main()
{counter a,b, c;
a.getdata();
a.display();
counter::show(); //count=1 accessing static member functions
b.getdata();
b.display();
counter::show(); //count==2
c.getdata();
c.display();
counter::show(); //count=3
return 0;
}

73.array of objects
#include<iostream>
using namespace std;
class abc
{int a,b;
public:
void getdata()
{cin>>a;
}
void display()
{cout<<"\n"<<a;
} };
int main()
{abc x[5]; //creating array of objects
cout<<"enter 5 no's";
for(int i=0;i<5;i++)
{ x[i].getdata();
}
for(int i=0;i<5;i++)
{ x[i].display();
}
return 0;
}

74. passing object for adding


#include<iostream>
using namespace std;
class addition
{int a;
public:
void getdata()
{cout<<"enter a value";
cin>>a;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}
void add(addition d)
{int s;
s=a+d.a;
cout<<"sum"<<s;
}};
int main()
{addition a,b;
a.getdata();
b.getdata();
a.add(b);
return 0;
}

75. static data member


#include<iostream>
using namespace std;
class counter
{int a;
static int count; //static variable
public:
counter() //default constructor
{
a=0;
count++;
}
counter(int b) //parametric constructor and it can't be written without a default
constructor
{a=b;
count++;
}
void getdata()
{cout<<"enter a no";
cin>>a;
}
void display()
{cout<<"\n a="<<a<<"\tno of objects created:"<<count;
}
};
int counter::count=0; //initialising static data member
int main()
{counter c;
c.getdata();
c.display();
counter d;
d.getdata();
d.display();
return 0;
}

76. copy constructor:


#include<iostream>
using namespace std;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
class abc
{int a;
public:
abc()
{a=0;
}
abc(int b)
{a=b;
}
void getdata()
{cin>>a;
}
void display()
{cout<<a;
}
~abc() //destructor
{
cout<<\n destructor called;
}
};
int main()
{abc d,f(d); //copy constructor
d.getdata();
abc e=d; //copy constructor
abc g=abc(3); //copy constructor
abc h;
h=d; //copy constructor 88888888
return 0; //destructor called and destructor called statement will be printed for 5 times
}

77. initializing default values using constructor


#include<iostream>
#include<conio.h>
using namespace std;
class Example {
// Variable Declaration
int a,b;
public:
//Constructor
Example() {
// Assign Values In Constructor
a=10;
b=20;
cout<<"Im Constructor\n";
}
void Display() {
cout<<"Values :"<<a<<"\t"<<b;
}
};

int main() {
Example Object;
// Constructor invoked.

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
Object.Display();
// Wait For Output Screen
getch();
return 0;
}

78. passing object to function


#include <iostream>
using namespace std;
class Complex
{ private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{ cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
void addComplexNumbers(Complex comp1, Complex comp2)
{ // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
real=comp1.real+comp2.real;
// imag represents the imag data of object c3 because this function is called using code
c3.add(c1,c2);
imag=comp1.imag+comp2.imag;
}
void displaySum()
{ cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main()
{ Complex c1,c2,c3;
c1.readData();
c2.readData();
c3.addComplexNumbers(c1, c2);
c3.displaySum();
return 0;
}

79. prime number or not


// parametric constructor
#include<iostream>
#include<conio.h>
using namespace std;
// Class Declaration
class prime
{ //Member Varibale Declaration
int a,k,i;
public:

prime(int x)

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{ a=x;
}
// Object Creation For Class
void calculate()
{ k=1;
{
for(i=2;i<=a/2;i++)
if(a%i==0)
{ k=0;
break;
}
else
{ k=1;
}
}
}
void show()
{ if(k==1)
cout<<"\n"<<a<<" is Prime Number.";
else
cout<<"\n"<<a<<" is Not Prime Numbers.";
}
};
int main()
{ int a , opt;
do{ cout<<"Enter the Number:";
cin>>a;
// Object Creation For Class
prime obj(a);
// Call Member Functions
obj.calculate();
obj.show();
cout<<"do u want to continue?";
cin>>opt;
}while(opt==1);
getch();
return 0;
}

80.area of rectangle
//constructors
#include <iostream>
using namespace std;
class Area
{ private:
int length;
int breadth;
public:
// Constructor
Area(): length(5), breadth(2){ }
void GetLength()
{ cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}
int AreaCalculation() { return (length * breadth); }
void DisplayArea(int temp)
{ cout << "Area: " << temp;
}
};
int main()
{ Area A1, A2;
int temp;
A1.GetLength();
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << endl << "Default Area when value is not taken from user" << endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
81. Source Code to demonstrate the working of overloaded constructors
//constructor with one default parameter
#include <iostream>
using namespace std;
class Area
{ private:
int length;
int breadth;
public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }
// Constructor with two arguments
Area(int l, int b): length(l), breadth(b){ }
void GetLength()
{ cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
int AreaCalculation() { return length * breadth; }
void DisplayArea(int temp)
{ cout << "Area: " << temp << endl;
}
};

int main()
{ Area A1, A2(2, 1);
int temp;
cout << "Default Area when no argument is passed." << endl;
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << "Area when (2,1) is passed as argument." << endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}

82. passing and returning an object

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{ cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
Complex addComplexNumbers(Complex comp2)
{ Complex temp;
// real represents the real data of object c3 because this function is called using code
c3.add(c1,c2);
temp.real = real+comp2.real;
// imag represents the imag data of object c3 because this function is called using code
c3.add(c1,c2);
temp.imag = imag+comp2.imag;
return temp;
}
void displayData()
{ cout << "Sum = " << real << "+" << imag << "i";
}
};
int main()
{ Complex c1, c2, c3;
c1.readData();
c2.readData();
c3 = c1.addComplexNumbers(c2);
c3.displayData();
return 0;
}

83. friend fun : average calculation


#include<iostream>
using namespace std;
#include<conio.h>
class base
{ int val1,val2;
public:
void get()
{ cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{ return float(ob.val1+ob.val2)/2;
}
int main()

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
{ base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
// copy constructors
#include<iostream>
using namespace std;
class integer
{ int n,m;
public:
integer()
{ m=0;n=0; }
integer(int a, int b)
{ m=a;n=b; }
integer(integer & i)
{ m=i.m; n=i.n; }
void disp()
{ cout<<m<<n<<"\n"; }
};
int main()
{ integer i1;
integer i2(20,40);
integer i3(i2);
integer i4=i3;
i1.disp();
i2.disp();
i3.disp();
i4.disp();
return 0;
}

84. friend function


#include<iostream.h>
#include<math.h>
//using namespace std;
class dm;
class db
{ float feet;
float inches;
public:
void get_data()
{ float n;
cout<<"\n Enter the distance in feets \n";
cin>>feet;
cout<<"\n Enter the distance in inches \n";
cin>>inches;
if(inches==12)
{ inches=0;
feet++;
}
if(inches>12)
{ n=inches/12;
inches=fmod(inches,12);
feet+=n;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}
}
friend void add(dm ,db );
};
class dm
{ float metres;
float cms;
public:
void getdata()
{ float n;
cout<<"\n Enter distance in metres \n";
cin>>metres;
cout<<"\n Enter distance in centimeters \n";
cin>>cms;
if(cms==100)
{ cms=0;
metres++;
}
if(cms>100)
{ n=cms/100;
cms=fmod(cms,100);
metres+=n;
}
}
friend void add(dm , db );
};
void add(dm m ,db f)
{ float met,cm;
met= m.metres+(f.feet)/3.2808;
cm= m.cms+(f.inches)*2.54;
cout<<"\n Sum of the distances is : \t"<<met<<"\n"<<cm<<endl;
}
int main()
{ dm a;
db b;
a.getdata();
b.get_data();
add(a,b);
return 0;
}

85. friend function


//This program adds two complex number by using member functions
#include <iostream.h>
#include <conio.h>

class Complex{
float real; // real part of the complex number
float imag; // imaginary part of the complex number

public:
Complex(float = 0.0, float = 0.0);
void print() {
cout << real << "+" << imag << "i" << endl; }

friend Complex add(Complex&, Complex&);


};

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
Complex::Complex(float r, float i){
real=r;
imag=i;
}
Complex add(Complex& c1, Complex& c2)
{
Complex c3;
c3.real=c1.real + c2.real;
c3.imag=c1.imag + c2.imag;
return(c3);
}

int
main(void)
{
Complex c1(1.1,2.2), c2(3.3, 4.4);
Complex c3 = add(c1, c2);
c3.print();
return(0);
}

86. friend function


#include <iostream.h>
#include <conio.h>
class Matrix;

class Vector{

int vec[3];

public:
void Init();
friend Vector multiply(Matrix &, Vector &);
void display();
};

class Matrix{

int mat[3][3];

public:
Matrix();
friend Vector multiply(Matrix &, Vector &);
};

Matrix::Matrix()
{
cout<<"\nEnter the data for the matrix:";
for(int r=0; r<3;r++)
for(int c=0; c<3;c++)
cin>>mat[r][c];
}

void Vector::display()
{
for(int i=0; i<3;i++)
cout<<vec[i]<<" ";
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
void Vector::Init()
{
cout<<"\nEnter the data for the vector:";
for(int i=0; i<3;i++)
cin>>vec[i];
}

Vector multiply(Matrix &m, Vector &v)


{
Vector r;
for (int i=0; i < 3; i++)
{
r.vec[i] = 0;
for (int j=0; j <3; j++)
r.vec[i] += (m.mat[i][j] * v.vec[j]);
}
return r;
}

int
main(void)
{
clrscr();
Vector V1,V2;
Matrix M1;

V1.Init();

V2=multiply(M1,V1);

V2.display();
return(0);
}

87. Friend and operator overload


#include <iostream.h>
class Coords {
int x, y;

public:
Coords(int xVal = 0, int yVal = 0) {
x = xVal;
y = yVal;
}
int retX() const {
return x;
}
int retY() const {
return y;
}
friend Coords operator+ (const Coords&, const Coords&);
friend Coords operator- (Coords&);
};
Coords operator+ (const Coords& left, const Coords& right) {
Coords result;
result.x = left.x + right.x;
result.y = left.y + right.y;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
return result;
}

Coords operator- (Coords &obj) {


Coords result;
result.x = -obj.x;
result.y = -obj.y;
return result;
}
int main(void) {
Coords a(1, 2);
Coords b(3, 4);
Coords v, z, w;
v = a + b;
// v = operator+(a, b); (same)
cout << v.retX() << "," << v.retY() << endl;
w = 3 + b; // ADT(Automatic Data Type) conversion
cout << w.retX() << "," << w.retY() << endl;
z = -b;
// z = operator-(b); (same)
cout << z.retX() << "," << z.retY() << endl;
return(0);
}

88.friend function
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
class ad1;
class ad
{int a,b;
public:
void get()
{cin>>a>>b;
}
friend void put(ad,ad1);
};
class ad1
{int c,d;
public:
void get()
{cin>>c>>d;
}
friend void put(ad,ad1);
};
void put(ad ob,ad1 ob1)
{cout<<ob.a<<ob.b<<ob1.c<<ob1.d;
}
void main()
{ad ob;
ad1 ob1;
ob.get(); ob1.get();
put(ob,ob1);
}

89.Virtual Functions
class A
{ int a;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
public:
A()
{ a = 1;
}
virtual void show()
{ cout <<a;
}
};

Class B: public A
{ int b;
public:
B()
{ b = 2;
}
virtual void show()
{ cout <<b;
}
};

int main()
{ A *pA;
B oB;
pA = &oB;
pAshow();
return 0;
}
90. virtual
#include<iostream>
using namespace std;
class shape
{ protected:
double base,height;
public:
void getdata(int i,int j)
{ base=i;
height=j;
}
virtual void area()
{ cout<<"\n\nTriangle Area "<<(0.5*base*height);
cout<<"\n\nRectangle Area "<<(base*height);
}
};

class triangle:public shape


{ double a;
public:
void area()
{ a=0.5*base*height;
cout<<"\n\nTriangle area "<<a;
}
};

class rectangle:public shape


{ double b;
public:
void area()
{

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
b=base*height;
cout<<"\n\nRectangle area "<<b;
}
};

int main()
{ shape *s;
triangle t;
rectangle r;
int k,l,ch;
cout<<"\n\nEnter base ";
cin>>k;
cout<<"\n\nEnter height ";
cin>>l;
cout<<"\n\n1. Triangle 2.Rectangle ";
cin>>ch;
if(ch==1)
{ s=&t;
s->getdata(k,l);
s->area();
}
if(ch==2)
{ s=&r;
s->getdata(k,l);
s->area();
}
return 0;
}

91.
#include <iostream.h>
class Bclass
{
public:
void disp()
{ cout << " BASE BASE\n" ; }
virtual void sh()
{ cout << "base base\n"; }
};
class Dclass : public Bclass
{
public:
void disp()
{ cout << "DERIVED DERIVED\n"; }
void sh()
{ cout << "derived derived\n"; }
};
int main()
{
Bclass B;
Dclass D;
Bclass *ptr;
cout << "ptr points to base class\n" ;
ptr = &B;
ptr->disp();
ptr->sh();
cout << "ptr points derived class\n";
ptr = &D;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
ptr->disp();
ptr->sh();
return 0;
}

Result
ptr points to base class
BASE BASE
base base
ptr points derived class
BASE BASE
derived derived

92. pure virtual function


# include<iostream.h>
# include<conio.h>
class shape
{protected:
double m1,m2;
public:
void getdata()
{ cout<<"enter the measurement 1 and 2 :";
cin>>m1>>m2;
}
virtual void display()=0;
};

class triangle: public shape


{protected:
double area;
public:
void display()
{ area=(m1*m2)/2;
cout<<"area of triangle:"<<area;
}
};

class rectangle:public shape


{protected:
double area;
public:
void display()
{ area=m1*m2;
cout<<"area of rectangle:"<<area;
}
};

class circle:public shape


{protected:
double area;
public:
void display()
{ area=3.14*m1*m1;
cout<<"the area of a circle:"<<area;
}
};
void main()
{

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
triangle t;
rectangle r;
circle c;
int n,opt;
shape *ptr;
cout<<"\nEnter the no of choices ";
cin>>n;
for(int i=1;i<=n;i++)
{ cout<<endl<<"\nenter choice:\n";
cout<<"1.triangle\n";
cout<<"2.rectanlge\n";
cout<<"3.Circle\n";
cin>>opt;
switch(opt)
{ case 1:
ptr=&t;
ptr->getdata();
ptr->display();
break;

case 2:
ptr=&r;
ptr->getdata();
ptr->display();
break;

case 3:
ptr=&c;
ptr->getdata();
ptr->display();
break;
}
}
}

93.class template
#include <iostream.h>
#include<conio.h>
template <class T>
T
max(T a, T b){
if (a > b)
return a;
else
return b;
}
int main(void)
{
clrscr();
cout << max(1,2)<<endl;

cout << max(5.62, 3.78)<<endl;

cout << max('A', 2)<<endl;


return(0);
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
94. class template
#include<iostream.h>
#include<conio.h>
template<class T>
class genericdata
{
T a[50];
int n;
public:
void getdata()
{
cout<<"no of elements";
cin>>n;
cout<<"enter elements";
for(int i=0;i<n;i++)
cin>>a[i];
}
void avg()
{ T tot=0;
for(int i=0;i<n;i++)
tot=tot+a[i];
cout<<"avg="<<(tot/n);
}
};
int main()
{ genericdata <float>obj1;
clrscr();
obj1.getdata();
obj1.avg();
return 0;
}

95. static member fun


#include<iostream>
using namespace std;
class test
{ static int count;
int code;
public:
void setcode()
{ code=++count;
}
void showcode()
{ cout<<"test paper code: "<<code<<"\n";
}
static void showcount()
{ cout<<"no of test papers: "<<count<<"\n";
}
};
int test ::count;
int main()
{ test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); //static member fun accessing
test t3;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
t3.setcode();
t2.showcount(); //static member fun accessing
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
96.class template
#include <iostream.h>
template <class T>
class Stack{
private:
T *bot; //bottom element
T *top; //top element
public:
Stack(int s){ top = bot = new T[s];
}
~Stack(){ delete [] bot;
}
void
push(T a){*top++=a;
}
T
pop(){ return(*--top);
}
};
int main(void)
{ Stack <int> st1(50);
st1.push(7);
st1.push(8);
cout << st1.pop()<<endl;
Stack <char> st2(20);
st2.push('A');
st2.push('B');
cout << st2.pop()<<endl;
Stack <float> st3(25);
st3.push(7.8);
cout << st3.pop()<<endl;
return(0);
}

97. class template


#include <iostream.h>
#include <stdlib.h>
template <class T>
class Anyarray{
private:
T *ia;
int size;
public:
Anyarray(int s=10){ //constructor 1
size=s;
ia=new T[s];
}
~Anyarray(){ delete[]ia; //destructor
}
T& operator[](int index);

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
friend istream& operator >>(istream&, Anyarray <T>&); //overloading input operator
friend ostream& operator <<(ostream&, Anyarray <T>&); //overloading output operator
};
template <class T>
T& Anyarray<T>::operator [] (int index){
if (index >=0 && index < size)
return ia[index];
else
//cout<<"index out of range";
exit(1);
}
template <class T>
istream& operator >> (istream& is, Anyarray<T> & a){
for(int i=0; i<a.size;i++)
is >> a.ia[i];
return is;
}
template <class T>
ostream& operator << (ostream& os, Anyarray<T> & a){
for(int i=0; i<a.size;i++)
os << a.ia[i];
return os;
}
int main(void)
{ Anyarray <int> ar1(5);
cin>>ar1;
cout<<ar1<<endl;
ar1[2]=8;
cout<<ar1[2]<<endl;
cout<<ar1<<endl;
Anyarray <float> ar2(3);
cin>>ar2;
cout<<ar2<<endl;
return(0);
}
____________________________________________________________________________________

C AND C++ STRINGS


98 Write a program to find the length of string?
#include<iostream>
using namespace std;
int main( )
{ char str[80];
cout<<"Enter string: ";
cin.getline(str, 80);
int i; //Hold length of string
for(i = 0; str[i] != '\0'; i++);
cout << "Length of string is: " << i;
return 0;
}
OTP:
Enterstring: Education
Length of string is: 9

99 Write a program to display string from backward?


#include<iostream>

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
using namespace std;
int main( )
{ char str[80];
cout<<"Enter string: ";
cin.getline(str, 80);
int l; //Hold length of string
//Find the length of the string
for(l = 0; str[l] != '\0'; l++);
//Display the string backwards
for(int i = l - 1; i >= 0; i--)
{ cout << str[i];
}
}

OTP:
Enter string: fate is not an eagle
elgae na ton si etaf

100. Write a program to count number of words in string?


#include<iostream>
using namespace std;
int main( )
{ char str[80];
cout << "Enter a string: ";
cin.getline(str,80);
int words = 0; // Holds number of words
for(int i = 0; str[i] != '\0'; i++)
{ if (str[i] == ' ') //Checking for spaces
{
words++;
}
}
cout << "The number of words = " << words+1 << endl;
}
Otp:
Enter a String: You can do anything, but not everything.
The number of words = 7

101. Write a program to concatenate one string contents to another?


#include<iostream>
using namespace std;
int main( )
{ char str1[80], str2[80];
cout<<"Enter first string: ";
cin.getline(str1, 80);
cout<<"Enter second string: ";
cin.getline(str2, 80);
int l = 0; //Hold length of first string
//Find length of first string.
for(l = 0; str1[l] != '\0'; l++);
//Adding second string content in first
for(int i = 0; str2[i] != '\0'; i++)
{ str1[l++] = str2[i];
}
str1[l] = '\0';
cout << "\nThe first string after adding second string content:\n\n" << str1;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
Otp:
Enter first string: Computer
Enter second string: Science

The first string after adding second string content:

ComputerScience

102. Write a program to compare two strings they are exact equal or not?
#include<iostream>
using namespace std;
int main( )
{ char str1[80], str2[80];
cout<<"Enter first string: ";
gets(str1);
cout<<"Enter second string: ";
gets(str2);
int i;
for (i = 0; str1[i] == str2[i] && str1[i]!= '\0' && str2[i] != '\0'; i++);

if(str1[i] - str2[i] == 0)
cout << "Strings are equal";
else
cout << "Strings are not equal";
return 0;
}

Otp:
Enter first string: Mango
Enter second string: Man
Strings are not equal

103.Write a program to check a string is palindrome or not?


#include<iostream>
using namespace std;
int main( )
{ char str[80];
cout<<"Enter string: ";
cin.getline(str, 80);
int l; //Hold length of string
//finding length of string
for(l = 0; str[l] != '\0'; l++);
//Comparing first element with last element till middle of string
int i;
for(i = 0; (i < l/2) && (str[i] == str[l - i - 1]); i++);

if(i == l/2)
cout << "Palindrome";
else
cout << "Not a palindrome";
}

Otp:
Enter string: radar
Palindrom

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
104. Write a program to find a substring within a string. If found display its starting position?
#include<iostream>
using namespace std;
int main( )
{ char str1[80], str2[80];
cout<<"Enter first string: ";
cin.getline(str1, 80);
cout<<"Enter second string: ";
cin.getline(str2, 80);
int l = 0; //Hold length of second string
//finding length of second string
for(l = 0; str2[l] != '\0'; l++);
int i, j;
for(i = 0, j = 0; str1[i] != '\0' && str2[j] != '\0'; i++)
{ if(str1[i] == str2[j])
{ j++;
}
else
{ j = 0;
}
}
if(j == l)
cout<<"Substring found at position "<< i - j + 1;
else
cout<<"Substring not found";
}

Otp:
Enter first string: Mango
Enter second string: go
Substring found at position 4

105. Write a program to reverse a string?


#include<iostream>
using namespace std;
int main( )
{ char str[80];
cout<<"Enter string: ";
cin.getline(str, 80);
int l; //Hold length of string
for(l = 0; str[l] != '\0'; l++); //finding length of string
int temp;
for(int i = 0, j = l - 1; i < l/2; i++, j--)
{ temp = str[i];
str[i] = str[j];
str[j] = temp;
}
cout << "Reverse string: " << str << endl;
}

Otp:
Enter string: spoon
Reverse string: noops

106. Write a program to convert a string in lowercase?


#include<iostream>

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
using namespace std;
int main( )
{ char str[80];

cout<<"Enter string: ";


cin.getline(str, 80);
for(int i=0;str[i]!='\0';i++)
{ str[i] = (str[i] >= 'A' && str[i] <= 'Z') ? (str[i] + 32) : str[i];
}
cout<<"Lowercase string: " << str << endl;
}

Otp:
Enter string: Hello World
Lowercase string: hello world

107. Write a program to convert a string in uppercase?


#include<iostream>
using namespace std;
int main( )
{ char str[80];
cout << "Enter a string: ";
cin.getline(str,80);
for(int i = 0; str[i] != '\0'; i++)
{str[i] = (str[i] >= 'a' && str[i] <= 'z') ? (str[i] - 32) : str[i];
}
cout << "\nConverted string: " << str;
}

Otp:
Enter a string: People always fear change.

Converted string: PEOPLE ALWAYS FEAR CHANGE.

108. Write the output of the following program. Assume that all necessary header files are included?
void Encrypt(char T[])
{
for (int i = 0; T[i] != '\0'; i += 2)
if (T[i] == 'A' || T[i] == 'E')
T[i] = '#';
else if (islower(T[i]))
T[i] = toupper(T[i]);
else
T[i] = '@';
}
int main()
{ char text[]="SaVE EArtH";
Encrypt(text);
cout << text << endl;
}
Otp:
@a@E@E#rTH
109. Write the output of the following program?
int main()
{ char name[] = "CoMPutER";
for (int x = 0; x < strlen(name); x++)

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
if (islower(name [x]))
name [x] = toupper(name[x]);
else
if (isupper(name[x]))
if (x % 2 == 0)
name[x] = tolower(name[x]);
else
name[x] = name[x-1];
cout << name;
}

Otp:
cOmmUTee

110.Write a program to write a program that reverses the given string using string class using a
re() function and displays the result.
Source code:
#include<iostream>
#include<string.h>
using namespace std;
void rev(string);
int main()
{ string s;
cout<<"Enter the string to be reversed:";
getline(cin,s);
rev(s);
}
void rev(string s)
{ char c;
for(int i=0,j=s.size();i<s.size()/2-1;i++,j--)
{ c=s[i];
s[i]=s[j];
s[j]=c;
}
cout<<"\nReversed string ="<<s;
}
Output:

111.Write a c++ program using string class which gets a string and a substring,The program
should replace the substring with new user given string.
#include<iostream>
#include<string.h>
using namespace std;
int main()
{ string s;
char c[20],h[20];
int b,flag=0;
cout<<"Enter the string:";
getline(cin,s);
cout<<"\nEnter the sub string:";
cin.getline(c,20);
cout<<"\nEnter the replacement string:";
cin.getline(h,10);

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
for(int i=0;i<s.size()/strlen(c);i++)
{ flag=0;
b=s.find(c);
if(b>=0)
{ s.replace(b,strlen(c),h);
flag=1;
}
}
if(flag=0)cout<<"no str";
cout<<'\n'<<s;
}
Output:

112.Write a c++ program that inserts a string as well as replaces it.


Source code:
#include <string>
#include <iostream>
using namespace std;
int main() {
string s = "Hai";
cout << s << endl;
s.insert(3, " I am Java");
cout << s << endl;
s.replace(3,10,"I am c++");
cout << s << endl;
return 0;
}
Output:

113.Write a program to concatenate two strings read from without using any pre defined
function.use string clss concept.
Source code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{string str1,str2;
string str3;
int len ;
cout<<"Enter the string1:";
getline(cin,str1);
cout<<"Enter the string2:";
getline(cin,str2);
str3 = str1 + str2;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout << "str1 + str2 : " << str3 << endl;
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
Output:

114.Write a program that counts Number of Vowels in a given sentence using string class
functions.
#include <iostream>
#include <string>
using namespace std;
int main ()
{string s,s1("aeiouAEIOU");
int f,i,count=0,len;
cout<<"Enter the string:";
getline(cin,s);
len = s.size();
f=s.find_first_of(s1,0);
if(f>=0)
count++;
i=f+1;
for(;i<len;)
{ f=s.find_first_of(s1,i);
count++;
i=f+1;
}
cout << "Number of vowels = " << count << endl;
return 0;
}

115.Write a cpp program that finds no. of words in a sentence.


Source code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s;
int i,count=0,len;
cout<<"Enter the string:";
getline(cin,s);
len = s.size();

while(i<len)
{
if(s.at(i)==' ')
count++;
i++;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}
cout << "Number of words = " << count+1 << endl;
return 0;
}
Output:

116.Write a c++program to Sort a given strings using selection sort


Program:
#include <iostream>
#include <string>
using namespace std;
string small(string s[],int n,int i)
{string smal=s[0];
for(;i<n+1;i++)
{ if(smal<s[i])
smal=s[i];
}
return smal;
}
int main ()
{string s[10],temp,smal;
int i,k,j;
cout<<"Enter no. of strings:";
cin>>k;
cout<<"\nEnter the strings:";
for(i=0;i<k+1;i++)
getline(cin,s[i]);
for(i=0;i<k+1;i++)
{ smal=small(s,k,i);
for(j=i;j<k+1;j++)
{ if(smal>s[j])
{ temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
cout<<endl;
for(i=0;i<k+1;i++)
cout<<s[i]<<" ";
return 0;
}
Output:

117 string reverse


#include<iostream.h>

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
#include<conio.h>
#include<string.h>
class str
{char st[50];
public:
void getdata()
{cin.getline(st,50,'\n');
}
void reverseIt()
{int l,i;char t;
l=strlen(st)-2;
for(i=0;i<=l/2;i++)
{t=st[i];
st[i]=st[l-i];
st[l-i]=t;
}}
void putdata()
{cout<<"reversed string is "<<st<<"\n";
}
};
main()
{ int i,l,t;
char st1[50];
str s;
cout<<"enter string1 ";
s.getdata();
s.reverseIt();
s.putdata();
return 0;
}

118. sort single string in alphabetical order


#include <stdlib.h>
#include<iostream.h>
#include<string.h>
int len;
class st
{char str[128];
public:
void getdata()
{cout<<"enter string with alphabets:\n";
cin.getline(str,128,'\n');
}
void stln()
{len=strlen(str);
}
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])
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
}

}
void putdata()
{cout<<"string is: "<<str;}
};
int main (void)
{ st s;
char temp;
s.getdata();
s.stln();
s.srt();
s.putdata();
return 0;
}

119. duplicate removal


#include <iostream>
using namespace std;
int main()
{ string t;
getline(cin,t);
cout<<"\n\nOriginal String: "<<t;
int i,j;
char c;
for(i=0;i<t.length();i++)
{
c = t.at(i);
for(j=i+1;j<t.length();j++)
{
if(c==t.at(j))
{
t.replace(j,1,"");
j--;
}
}
}
cout<<"\n\nRepeated Characters Removed String: "<<t;
return 0;
}

Files
Opening a file

Opening file using constructor

ofstreamfout(results.txt); //output only


ifstream fin(data.txt); //input only
Opening file using open()
ofstreamofile;
ofile.open(data1.txt);

ifstreamifile;
ifile.open(data2.txt);
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only

fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
file.close();//Closing file

Input and output operation

put() and get() and getline() function

file.get(ch);
file.put(ch);

write() and read() function

file.read((char *)&obj, sizeof(obj));


file.write((char *)&obj, sizeof(obj));

120. Program to write in a text file


#include<iostream>
#include<fstream>
using namespace std;
int main()
{ofstreamfout;
fout.open("out.txt");
charstr[300]="Time is a great teacher";
fout<<str;
fout.close();
cout<<"\ninfo written into file\n";
system("pause");
return 0;
}
OUTPUT:
info written into file

121. Program to read from text file and display it


#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
charch;
while(!fin.eof())//eof()----detecting end of file
{
fin.get(ch);
cout<<ch;
}
fin.close();
return 0;
system("pause");
}

OUTPUT:
Time is a great teacher

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
122.Program to count number of characters.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
charch;
int count=0;
while(!fin.eof())//eof()----detecting end of file
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<< count<<endl;
fin.close();
system("pause");
return 0;
}
OUTPUT:
Number of characters in file is 24

123.Program to count number of words


#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char word[30];
int count=0;
while(!fin.eof())//eof()----detecting end of file
{
fin>> word;
count++;
}
cout<<"Number of words in file is "<< count<<endl;
fin.close();
system("pause");
return 0;
}

OUTPUT:
Number of words in file is 5

124.Program to count number of line


#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
charstr[80];
int count=0;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<< count<<endl;
fin.close();
system("pause");
return 0;
}
OUTPUT:
Number of lines in file is 1
125.Program to copy contents of file to another file.
(dealing with more than one file at a time)
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
ofstreamfout;
fout.open("sample.txt");
charch;
while(!fin.eof())//eof()----detecting end of file
{
fin.get(ch); //note info is read from out.txt
fout<<ch; //note info is written into sample.txt
}
fin.close();
fout.close();
fin.open("sample.txt"); //note now sample.txt is linked with input stream
while(!fin.eof())//eof()----detecting end of file
{
fin.get(ch);
cout<<ch;
}
cout<<"\n";
fin.close();
fout.close();
system("pause"); return 0;}
OUTPUT:
Time is a great teacher
BASIC OPERATION ON BINARY FILE IN C++
126. (PROGRAM FOR READING, WRITING, SEARCH AND DISPLAY IN BINARY FILE)
#include<iostream>
#include<stdlib.h>
#include<fstream>
using namespace std;
class student
{
intadmno;
char name[20];
public:
void getdata()
{
cout<<"\nEnter The admission no. ";
cin>>admno;

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
cout<<"\nEnter The Name of The Student ";
cin>>(name);
}
void showdata()
{
cout<<"\nAdmission no. : "<<admno;
cout<<"\nStudent Name : ";
puts(name);
}
int retadmno()
{
return admno;
}
}obj;

voidwrite_data() //Function to write in a binary file


{
ofstreamoFile;
oFile.open("student.dat",ios::binary|ios::app);
obj.getdata();
oFile.write((char*)&obj,sizeof(obj));
oFile.close();
}
void display() //function to display records of binary file
{
ifstreamiFile;
iFile.open("student.dat",ios::binary);
while(iFile.read((char*)&obj,sizeof(obj)))
{
obj.showdata();
}
iFile.close();
}
void search() //Function to search and display from binary file
{
int n;
cout<<"\nenter the admn no:";
cin>>n;
ifstreamiFile;
iFile.open("student.dat",ios::binary);
while(iFile.read((char*)&obj,sizeof(obj)))
{
if(obj.retadmno()==n)
obj.showdata();
}
iFile.close();
}
int main()
{
intch,y=1;
write_data();
do{
cout<<"\nenter your choice\n1.enter details\n2.view all details\n3.view last
entry\n4.search\n5.exit";
cin>>ch;
switch(ch)
{
case 1:

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
write_data();
break;
case 2:
display();
break;
case 3:
obj.showdata();
break;
case 4:
search();
break;
case 5:
y=0;
break;
default :
cout<<"\nwrong choice";
}

}while(y==1);
return 0;
}

OUTPUT:
Enter The admission no. 1

Enter The Name of The Student a

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
2

Admission no. : 1
Student Name : a

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
1

Enter The admission no. 2

Enter The Name of The Student b

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
2

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
Admission no. : 1
Student Name : a

Admission no. : 2
Student Name : b

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
3

Admission no. : 2
Student Name : b

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
4

enter the admn no:1

Admission no. : 1
Student Name : a

enter your choice


1.enter details
2.view all details
3.view last entry
4.search
5.exit
5
--------------------------------
Process exited after 35.32 seconds with return value 0
Press any key to continue . . .

ERROR HANDLING FUNCTION


FUNCTION RETURN VALUE AND MEANING
eof():
True (non zero) if end of file is encountered while reading; otherwise return false(zero)
fail():
true when an input or output operation has failed
bad():
true if an invalid operation is attempted or any unrecoverable error has occurred.
good():
127. returns true if no error has occurred.
#include <fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream file;
file.open("a:test.dat");

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University
if(!file)
Cout<<"can't open group.dat";
else
Cout<<"file opened successfully";
Cout<<"\nfile"<<file;
Cout<<"error status :"<<file.rdstate();
Cout<<"good()"<<file.good();
Cout<<"eof()"<<file.eof();
Cout<<"fail()"<<file.fail();
Cout<<"bad()"<<file.bad();<<end;
file.close();
return 0;
}

File Pointers And Their Manipulation:

All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the
next input operation.

ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next
element has to be written.

Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from
both istream and ostream).

These internal stream pointers that point to the reading or writing locations within a stream can be
manipulated using the following member functions:

seekg() moves get pointer(input) to a specified location


seekp() moves put pointer (output) to a specified location
tellg() gives the current position of the get pointer
tellp() gives the current position of the put pointer

The other prototype for these functions is:

seekg(offset, refposition );
seekp(offset, refposition );

The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants defined
in the ios class.

ios::beg start of the file


ios::cur current position of the pointer
ios::end end of the file

example:
file.seekg(-10, ios::cur);

The seekp() and tellp() member functions are identical to the above two functions, but they are identified
with the put pointer. The seekg() and tellg() member functions are defined in the istream class. The
seekp() and tellp() member functions are defined in the ostream class.

Program tofinds out the number of records in the file billfile.dat by using the seekg() and tellg()
functions.
128.
Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section
& updated by G.R.Brindha, SoC, SASTRA University
#include<fstream.h>
#include<iostream.h>
class bill
{
private:
intiBill_no;
floatfBill_amt;
public:
void getdata()
{
cout<<Enter Bill number;
cin>>iBill_no;
cout<<Enter Bill amount;
cin>>fBill_amt;
}
void showdata()
{
cout<<Bill number <<iBill_no<<endl;
cout<<Bill amount <<fBill_amt<<endl;
}
};
void main()
{
fstream Fi1(billfile.dat,ios::in);
Fi1.seekg(0,ios::end);
ini iEnd;
iEnd=Fi1.tellg();
cout<<The size of the file is <<iEnd<<endl;
cout<<Size of one record is <<sizeof(bill)<<endl
ini iNorec=iEnd/sizeof(bill);
cout<<There are <<iNored<<records in the file<<endl;
}

Prepared by I Btech- I section 2016-17 Batch, Consolidated by Divya.V I Section


& updated by G.R.Brindha, SoC, SASTRA University

You might also like