CPP All Programs-2019 SASTRA University
CPP All Programs-2019 SASTRA University
CPP Programs
Concepts Page.No
INLINE FUNCTIONS 2
FUNCTION OVERLOADING 2
DEFAULT PARAMETERS 3
CLASSES, CONSTRUCTORS AND DESTRUCTORS 5
OPERATOR OVERLOADING 8
DATA CONVERSION 17
POINTERS 21
INHERITANCE 24
MISCELLANEOUS PROGRAMS 30
FRIEND FUNCTION 36
VIRTUAL FUNCTIONS 38
C AND C++ STRINGS 40
FILES 46
MISCELLANEOUS PROGRAMS – II 50
} }
The Class Destructor 14.A class and object(having an int array
13. A destructor is a special member function of a data member) program to sort an array and
class that is executed whenever an object of it's class search any array number‘s location.
goes out of scope or whenever the delete expression #include<iostream.h>
is applied to a pointer to the object of that class.A class sort_search
destructor will have exact same name as the class {public:
prefixed with a symbol tilde (~) and it can neither
int a[10],n,t;
return a value nor can it take any parameters, unlike
void sort();
contructors which can have parameters only.
void search();
Destructor can be very useful for releasing resources
before coming out of the program like closing files, };
releasing memories etc. void sort_search::sort()
Following example explains the concept of destructor: {cout<<"enter the size"<<endl;
#include <iostream> cin>>n;
using namespace std; cout<<"enter the array elements"<<endl;
class Line { for(int i=0;i<n;i++)
public: cin>>a[i];
void setLength( double len ); for(i=0;i<n;i++)
double getLength( void ); {for(int j=0;j<(n-i-1);j++)
Line(); // This is the constructor {if(a[j]>a[j+1])
declaration {t=a[j];
~Line(); // This is the destructor: a[j]=a[j+1];
declaration a[j+1]=t;}}
private: }
double length; cout<<"the sorted array is "<<endl;
}; for(i=0;i<n;i++)
Line::Line(void) cout<<a[i]<<" ";
{ cout << "Object is being created" << endl; }
} void sort_search::search()
Line::~Line(void) {int n,a[10],data,flag=0;
{ cout << "Object is being deleted" << endl; cout<<"enter the size"<<endl;
} cin>>n;
void Line::setLength( double len ) cout<<"enter the array elements"<<endl;
{ length = len; for(int i=0;i<n;i++)
} cin>>a[i];
double Line::getLength( void ) cout<<"enter the number to be
{ return length; searched"<<endl;
} cin>>data;
// Main function for the program for(i=0;i<n;i++)
int main( ) {if(a[i]==data)
{ Line line; { flag=1;break;}
// set line length }
line.setLength(6.0); if(flag==1)
cout << "Length of line : " << line.getLength() cout<<"the given data"<<" "<<data<<"
<<endl; "<<"present in the location"<<" "<<i+1<<endl;
else
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
6
); } height = hei;
Int checkit(long double answer) //check results }
{if( answer > 2147483647.0L || answer < - // Overload + operator to add two Box
2147483647.0L ) objects.
{ cout << “\nOverflow Error\n”; exit(1); } Box operator+(const Box& b) {
return Int( int(answer) ); Box box;
} box.length = this->length + b.length;
}; box.breadth = this->breadth + b.breadth;
int main() box.height = this->height + b.height;
{Int alpha = 20; return box;
Int beta = 7; }
Int delta, gamma; };
gamma = alpha + beta; //27 int main( )
cout << “\ngamma=”; gamma.putInt(); { Box Box1; // Declare Box1 of type Box
gamma = alpha - beta; //13 Box Box2; // Declare Box2 of type Box
cout << “\ngamma=”; gamma.putInt(); Box Box3; // Declare Box3 of type Box
gamma = alpha * beta; //140 double volume = 0.0; // Store the volume of
cout << “\ngamma=”; gamma.putInt(); a box here
gamma = alpha / beta; //2 // box 1 specification
cout << “\ngamma=”; gamma.putInt(); Box1.setLength(6.0);
delta = 2147483647; Box1.setBreadth(7.0);
gamma = delta + alpha; //overflow error Box1.setHeight(5.0);
delta = -2147483647; // box 2 specification
gamma = delta - alpha; //overflow error Box2.setLength(12.0);
cout << endl; Box2.setBreadth(13.0);
return 0;} Box2.setHeight(10.0);
31.Overloading '+' operator to add // volume of box 1
dimensions of two box objects: volume = Box1.getVolume();
#include <iostream> cout << "Volume of Box1 : " << volume
using namespace std; <<endl;
class Box { // volume of box 2
private: volume = Box2.getVolume();
double length; // Length of a box cout << "Volume of Box2 : " << volume
double breadth; // Breadth of a box <<endl;
double height; // Height of a box // Add two object as follows:
public: Box3 = Box1 + Box2;
double getVolume(void) { // volume of box 3
return length * breadth * height; volume = Box3.getVolume();
} cout << "Volume of Box3 : " << volume
void setLength( double len ) { <<endl;
length = len; }
} 32.Overloading '<' operator to compare two
void setBreadth( double bre ) { distance objects:
breadth = bre; #include <iostream>
} using namespace std;
void setHeight( double hei ) { class Distance //English Distance class
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
14
void operator += ( Distance ); cout << “Element “ << j << “ is “ << temp <<
}; endl;
//add distance to this one }
void Distance::operator += (Distance d2) return 0;}
{feet += d2.feet; //add the feet 36.Example program for both left and right
inches += d2.inches; //add the inches hand side calling of a function:
if(inches >= 12.0) //if total exceeds 12.0, #include <iostream>
{ //then decrease inches using namespace std;
inches -= 12.0; //by 12.0 and #include <process.h> //for exit()
feet++; //increase feet const int LIMIT = 100; //array size
} //by 1 class safearay
} {private:
int main() int arr[LIMIT];
{Distance dist1; //define dist1 public:
dist1.getdist(); //get dist1 from user int& access(int n) //note: return by reference
cout << “\ndist1 = “; dist1.showdist(); {if( n< 0 || n>=LIMIT )
Distance dist2(11, 6.25); //define, initialize { cout << “\nIndex out of bounds”; exit(1); }
dist2 return arr[n];
cout << “\ndist2 = “; dist2.showdist(); }
dist1 += dist2; //dist1 = dist1 + dist2 };
cout << “\nAfter addition,”; int main()
cout << “\ndist1 = “; dist1.showdist(); {safearay sa1;
cout << endl; for(int j=0; j<LIMIT; j++) //insert elements
return 0;} sa1.access(j) = j*10; //*left* side of equal sign
35.Overloading subscript operator ‗[]‘ : for(j=0; j<LIMIT; j++) //display elements
#include <iostream> {int temp = sa1.access(j); //*right* side of equal
using namespace std; sign
#include <process.h> //for exit() cout << “Element “ << j << “ is “ << temp <<
const int LIMIT = 100; //array size endl;}
class safearay return 0;}
{private: 37.Overloading '<<' Operator to print time
int arr[LIMIT]; object:
public: #include<iostream.h>
int& operator [](int n) //note: return by class time
reference { int hr,min,sec;
{if( n< 0 || n>=LIMIT ) public:
{ cout << “\nIndex out of bounds”; exit(1); } time()
return arr[n]; { hr=0, min=0; sec=0; }
} time(int h,int m, int s)
}; { hr=h, min=m; sec=s; }
int main() friend ostream& operator << (ostream&out,
{safearay sa1; time &tm); //overloading '<<' operator
for(int j=0; j<LIMIT; j++) //insert elements };
sa1[j] = j*10; //*left* side of equal sign ostream& operator<< (ostream&out, time &tm)
for(j=0; j<LIMIT; j++) //display elements //operator function
{int temp = sa1[j]; //*right* side of equal sign { out << "Time is " << tm.hr << "hour : "
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
16
<<tm.min<< "min : " <<tm.sec<< "sec"; cout <<" multiplication value : " << endl;
return out;} for (i=0 ; i<m; i++)
int main() { for (j=0 ; j<n ; j++)
{ time tm(3,15,45); { f. a [i] [j]= 0;
cout<< tm; } for (int k=0; k<u.m ; k++)
38. Overloading operations on a matrix. { f. a[i] [j]= f.a[i] [j]+(a [i] [k]*u.a[k][j]);
#include<iostream.h> }
int i,j,k,t,u,c; cout<<f.a[i] [j]<<"\t";o
class mat }
{int m,n; cout<< endl;}
int a [3] [3]; }
public: iInt main()
mat() {} { mat p,q;
void getdata (); p.getdata();
void operator +(mat); q.getdata();
void operator -(mat); p+q;
void operator *(mat); p-q;
}; p*q;
void mat :: getdata() }
{cout<<"enter row and col"; PROGRAMS BASED ON DATA
cin>>m>>n; CONVERSION:
cout <<" enter the elements of matnx a"; 39.Program to show how compiler implicitly
for (i=0; i<m; i++) converts basic data types.
{for ( j=0; j<n; j++) #include <iostream>
{cin >>a[i][j];} using namespace std;
}} int main()
void mat :: operator +(mat c) { int num1;
{mat d; float num2 = 5.615;
cout <<" addition value" <<endl; num1=num2;//float convertion to int
for (i=0; i<m; i++) cout<<num1;
{for (j=0; j<n; j++) }
{d.a[i] [j] =a[i] [j]+c.a[i] [j]; 40.Program to show how a compiler
cout <<d. a[i] [j] <<"\t"; explicitly converts basic data types.
}cout << endl; #include <iostream>
}} using namespace std;
void mat :: operator -(mat c) int main()
{mat d; { int num1;
cout <<" subtracted value" <<endl; float num2 = 5.615;
for (i=0; i<m; i++) num1=static_cast<int>(num2); //float
{for (j=0; j<n; j++) convertion to int
{d.a[i] [j] =a[i] [j]-c.a[i] [j]; cout<<num1;
cout <<d. a[i] [j] <<"\t"; }
}cout << endl; 41.Conversion from basic to user defined
}} data type.
void mat :: operator *(mat u) #include <iostream>
{mat f; using namespace std;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
17
{ cout<<"Metre= break;
"<<metre<<endl<<"Centimetre= case 2:
"<<centimetre<<endl;} cout<<"Enter feet of int value ";
}; cin>>a;
class distancefeet cout<<"Enter inches of float or int value ";
{ private: cin>>b;
int feet; distancefeet df1(a,b);
float inch; df1.display();
public: distancemetre dm1;
distancefeet():feet(0),inch(0) dm1=df1;
{} dm1.display();
distancefeet(int f,float i) break;
{ feet=f; }
inch=i; } }
distancefeet(distancemetre d) 44. Conversion between C strings and string
{ float objects:
in=(d.getmetre()*100+d.getcentimetre())/2.54; #include<iostream>
feet=in/12; #include<string.h>
inch=fmod(in,12); } using namespace std;
operator distancemetre() class String
{ float a=feet*12+inch; { private:
int m=(a*2.54)/100; enum{sz=80};
float cm=(a*2.54)-(m*100); char str[sz]
return distancemetre(m,cm); } public:
void display() String()
{ cout<<"Feet= "<<feet<<endl<<"inches= { str[0]='\0'; }
"<<inch<<endl; } String(char a[])
}; { strcpy(str,a); }
int main() void get()
{ int n; { cin.getline(str,80); }
int a; void display()
float b; { cout<<"string that you entered is
cout<<"Enter 1 to convert metre to feet type or "<<endl<<str<<endl; }
2 to convert feet to metre type"; operator char*()//conversion operator
cin>>n; { return str; }
switch(n) };
{ case 1: int main()
cout<<"Enter metre of int value "; { char a[30];//normal c string
cin>>a; cout<<"Enter the string";
cout<<"Enter centimetre of float or int value "; cin.getline(a,30);/*gets the input as char array
cin>>b; and stores them in a*/
distancemetre dm(a,b); String s=a;//uses parametric construtor
dm.display(); s.display();
distancefeet df(dm);/*conversion takes place String s1="bonne annee!!!";
in constructor char b[30];
df.display(); strcpy(b,static_cast<char*>(s1));/*convrsion
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
19
{ h=hour24-12; sec=i%60;
strcpy(a,"pm"); } }
if(hour24==0) disp()
{cout<<hrs<<":"<<min<<":"<<sec;
{ strcpy(a,"am");
}
h=12; } };
m=min24; int main()
s=seconds24; {long int l;
return time12(a,h,m,s);} cin>>l;
} tim m(l);
void display24() m.disp();
return 0;}
{cout<<"Time in 24 format is"<<endl;
POINTERS
cout<<hour24<<"-"<<min24<<"- 47. GENERIC POINTER
"<<seconds24<<endl; } Program to show the usage of generic(void)
}; pointers.
int main() #include <iostream>
{ int n; using namespace std;
cout<<"Enter 1 to convert 12 to 24 or 2 for int main()
{ int *a,a1=5;
vice verse";
float* b,b1=10;
cin>>n; void *c;
switch(n) b=&b1;
{ case 1: a=&a1;
time12 t12; cout<<"\nThe value of the integer pointer is:
t12.get12(); "<<*a;
cout<<"\nThe value of the float pointer is:
t12.display12();
"<<*b;
time24 t24(t12); c=&a1;
t24.display24(); cout<<"The value of the generic pointer can be
break; ( pointing to an integer
case 2: ):"<<*static_cast<int*>(c);
time24 t24a; c=&b1;
t24a.gettime24(); cout<<" and (pointing to a float ):
"<<*static_cast<float*>(c);
t24a.display24();
a=reinterpret_cast<int*>(b);
time12 t12a=t24a; cout<<"\nThe value of a float pointer pointing
t12a.display12(); to an integer is: "<<*b;
break; }
} The value of the integer pointer is: 5
} The value of the float pointer is: 10
46. Conversion of basic to user defined data The value of the generic pointer can be (
type: pointing to an integer ): 5 and (pointing to a
#include<iostream.h> float ): 10
class tim The value of a float pointer pointing to an
{int hrs,min,sec; integer is: 10
public: 48. POINTERS AND ARRAYS
tim() {hrs=0;min=0;sec=0;} Program to assign an int array and a
tim(long int i) character array to an int pointer and
{min=i/60; character pointer respectively and
min=min%60; manipulating them using unary operator
hrs=i/3600; ‗++‖ :
23 enter n value
45 5
34 m=6
Roll No:34 n=5
name: sneha 59. Progam to get the details of an employee
subject 1 : 23 and student and display their details using
subject 2 : 45 ‗Multiple inheritance‘:
subject 3 : 34 #include<iostream.h>
total =102 class emp
{protected:
per = 34
char name[10],gen;
int no,sal,age;
58. Simple program to show how ‗Multiple public:
inheritance‘ works: int g;
#include<iostream> void getdata()
using namespace std; {cout<<"enter the no,name,gen,age and sal";
class base1 cin>>no>>name>>gen>>age>>sal;
cout<<"research interest?";
{ protected: cin>>g; }
int m; void display()
public: {cout<<"empno:"<<no<<"\nname:"<<name<<"
void get_m() \ngen:"<<gen<<"\nage:"<<age<<"\nsal:"<<sal;
{ cout<<"enter m value"<<endl; }
cin>>m; } };
class student
};
{ protected:
class base2 char name[10],dept[10];
{protected: int regno,yr;
int n; float cgpa;
public: public:
void get_n() int g;
{ cout<<"enter n vakue"<<endl; void getdata()
{cout<<"enter name , no,dept,yr,cgpa and
cin>>n; }
research interest:";
}; cin>>name>>regno>>dept>>yr>>cgpa>>g;}
class derived: public base1,public base2 void display()
{ public: {cout<<"name:"<<name<<"\nregno:"<<regno<
void display() <"\ndept"<<dept<<"\nyr:"<<yr<<"\ncgpa"<<cg
{cout<<"m ="<<m<<endl; pa; }
cout<<"n ="<<n<<endl; } };
class research : public emp,public student
}; { public:
int main() void display()
{ derived d1; {emp::display(); }
d1.get_m(); void display1()
d1.get_n(); {student::display(); }
d1.display(); };
void main()
}
{ research q[25];
Output: int i,j,u,v;
enter a value cout<<"no of employees";
6
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
26
switch(ch) public:
{ case 1: void getdata()
{ Book B; {cout<<"enter the score in sports
B.getdata();
quota"<<endl;
B.putdata();
break; cin>>score; }
} void displays()
case 2: {cout<<"score in sports quota"<<endl;
{ Tape T; cout<<score<<endl; }
T.getdata(); };
T.putdata(); class result: public marks ,public sports
break;
{private:
} }
cout<<"\nDo you want to continue y/n"; float total;
cin>>op; public:
}while(op=='y'||op=='Y') ; void ans()
} {total=mark1+mark2+score; }
63. Program explaining ‗Hybrid void display()
Inheritance‘. {cout<<"the total score of the student"<<endl;
#include<iostream> cout<<total<<endl;}
using namespace std; };
class student int main()
{ protected: {result r1;
int rollno; r1.getd();
public: r1.getm();
void getd() r1.getdata();
{ cout<<"enter the rollnumber"; r1.ans();
cin>>rollno; } r1.putd();
void putd() r1.displaym();
{ cout<<"rollnumber of the student is"; r1.displays();
cout<<rollno<<endl; } r1.display();}
}; Output:
class marks: public student
{protected:
float mark1,mark2;
public:
void getm()
{cout<<"enter the marks of two
subjects"<<endl;
cin>>mark1>>mark2; }
void displaym()
{cout<<"marks obtained"<<endl;
cout<<mark1<<endl;
cout<<mark2<<endl; } 64. Ambiguity Resolution
}; //over riding in simple inheritance
class sports 64.#include<iostream>
{ protected: using namespace std;
int score; class A
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
29
{ public: n
void display() 66.Program to execrise Inheritance of
{cout<<"A"<<endl;} constructors.
}; #include<iostream>
class B:public A using namespace std;
{ public: class A
void display() { public:
{ cout<<"b"<<endl; } A()
}; {cout<<"a"<<endl; }
int main() A(int a)
{ B a; {cout<<"a(int)"<<endl;}
a.display(); };
a.A::display(); class B:public A
a.B::display(); } { public:
Output: B()
b {cout<<"b"<<endl;}
a B(int a)
b {cout<<"b(int)"<<endl;}
65.Over riding example 2. };
#include<iostream> class C:public B
using namespace std; {public:
class m C()
{public: { cout<<"c"<<endl;}
void display() C(int a)
{cout<<"m"<<endl;} {cout<<"c(int)"<<endl; }
}; };
class n int main()
{ public: {C obj1;
void display() C obj2(5);}
{cout<<"n"<<endl;} Output:
}; a
class p: public m,public n b
{ public: c
void display() a
{cout<<"p"<<endl; b(int)
m::display(); 67. Program to show the order of
n::display();d constructor calling
} When a class is inherited virtually.
}; class Base1
int main() { public:
{p p1; Base1() { cout<<”Base 1”; }
p1.display(); };
} class Base2
Output: { public:
p Base2(){ cout<<”Base2”; }
m };
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
30
x.getdata(); display();
v.display(); }
x.display(); };
} int main()
72. Basic program- 5 {abc x, v;
#include<iostream> v.setdata(4,8);
using namespace std; v.display(); //error :display() is private can't
class abc be accessed from main()
{int a,b; x.getdata();
public: return 0; }
void setdata(int c,int d) 74. Basic program- 7.
{a=c; #include<iostream>
b=d; using namespace std;
display();//nesting of member functions class counter
} {int a;
void getdata() static int count;
{cout<<"\n enter 2 nos"; public:
cin>>a>>b; void getdata()
display(); {cout<<”enter a no”;
} cin>>a;
void display() count++;
{cout<<"\n"<<a<<"\n"<<b; }
} }; void display()
int main() {cout<<”a=”<<a;
{abc x, v; }
v.setdata(4,8); static void show() //static member
x.getdata(); function can access only static data
return 0; members
} {cout<<”no of object created”<<count;}
73. Basic program- 6. };
#include<iostream> int counter::count=0; //initialising a static data
using namespace std; member
class abc int main()
{private: {counter a,b, c;
int a,b; a.getdata();
void display() //member a.display();
functions can also be private counter::show();
{ cout<<a<<b; //count=1 accessing static member functions
} b.getdata();
public: b.display();
void setdata(int c,int d) counter::show();
{a=c; //count==2
b=d; c.getdata();
display(); //calling private member c.display();
functions counter::show(); //count=3
} return 0;
void getdata() }
{cin>>a>>b; 75.Program to create Array of objects.
for(j=i;j<k+1;j++) #include<iostream.h>
{ if(smal>s[j]) #include<string.h>
{ temp=s[i]; int len;
s[i]=s[j]; class st
s[j]=temp;} {char str[128];
} public:
void getdata()
}
{cout<<"enter string with alphabets:\n";
cout<<endl; cin.getline(str,128,'\n');
for(i=0;i<k+1;i++) }
cout<<s[i]<<" "; void stln()
return 0;} {len=strlen(str);
Output: }
void srt()
{int i,j;
char temp;
for (i=0; i<len-2; i++)
{for (j=i+1; j<len-1; j++)
{if (str[i] > str[j])
115. Program to reverse a given string {temp = str[i];
belonging to class str and display the str[i] = str[j];
reversed string. str[j] = temp; }
#include<iostream.h> }
#include<string.h> }
class str }
{char st[50]; void putdata()
public: {cout<<"string is: "<<str;}
void getdata() };
{cin.getline(st,50,'\n');} int main (void)
void reverseIt() { st s;
{int l,i;char t; char temp;
l=strlen(st)-2; s.getdata();
for(i=0;i<=l/2;i++) s.stln();
{t=st[i]; s.srt();
st[i]=st[l-i]; s.putdata();
st[l-i]=t; return 0;}
}} 117. Program to remove any repeated
void putdata() characters of a string and display the edited
{cout<<"reversed string is "<<st<<"\n";} string.
}; #include <iostream>
main() using namespace std;
{ int i,l,t; int main()
char st1[50]; { string t;
str s; getline(cin,t);
cout<<"enter string1 "; cout<<"\n\nOriginal String: "<<t;
s.getdata(); int i,j;
s.reverseIt(); char c;
s.putdata(); for(i=0;i<t.length();i++)
return 0;} { c = t.at(i);
116.Program to sort a given string for(j=i+1;j<t.length();j++)
characters in alphabetical order. { if(c==t.at(j))
#include <stdlib.h> { t.replace(j,1,"");
{ifstream fin; }
fin.open("out.txt"); fin.close();
char word[30]; fout.close();
int count=0; //note now sample.txt is linked with input
while(!fin.eof()) //eof()----detecting end of stream
file fin.open("sample.txt");
{fin>> word; while(!fin.eof()) //eof()----detecting end of
count++; } file
cout<<"Number of words in file is "<< {fin.get(ch);
count<<endl; cout<<ch;
fin.close(); }
system("pause"); cout<<"\n";
return 0;} fin.close();
OUTPUT: fout.close();
Number of words in file is 5 system("pause"); return 0;}
122.Program to count number of lines. OUTPUT:
#include<iostream> Time is a great teacher
#include<fstream> BASIC OPERATION ON BINARY FILE IN
using namespace std; C++
int main() 124. (PROGRAM FOR READING,
{ifstream fin; WRITING, SEARCH AND DISPLAY IN
fin.open("out.txt"); BINARY FILE)
charstr[80]; #include<iostream>
int count=0; #include<stdlib.h>
while(!fin.eof()) #include<fstream>
{fin.getline(str,80); using namespace std;
count++; class student
} {intadmno;
cout<<"Number of lines in file is "<< char name[20];
count<<endl; public:
fin.close(); void getdata()
system("pause"); {cout<<"\nEnter The admission no. ";
return 0; cin>>admno;
} cout<<"\nEnter The Name of The Student ";
OUTPUT: cin>>(name); }
Number of lines in file is 1 void showdata()
123. Program to copy contents of one file to {cout<<"\nAdmission no. : "<<admno;
another file (store as char). cout<<"\nStudent Name : ";
(dealing with more than one file at a time) puts(name); }
#include<iostream> int retadmno()
#include<fstream> {return admno; }
using namespace std; }obj;
int main() voidwrite_data()//Function to write in a binary
{ifstream fin; file
fin.open("out.txt"); {ofstreamoFile;
ofstreamfout; oFile.open("student.dat",ios::binary|ios::app);
fout.open("sample.txt"); obj.getdata();
charch; oFile.write((char*)&obj,sizeof(obj));
while(!fin.eof()) //eof()----detecting end of oFile.close();
file }
{fin.get(ch); //note info is read from out.txt //function to display records of binary file
fout<<ch;//note info is written into sample.txt void display() {
ifstreamiFile; 5.exit
iFile.open("student.dat",ios::binary); 2
while(iFile.read((char*)&obj,sizeof(obj)))
{obj.showdata(); } Admission no. : 1
iFile.close(); Student Name : a
}
void search() //Function to search and display enter your choice
from binary file 1.enter details
{ int n; 2.view all details
cout<<"\nenter the admn no:"; 3.view last entry
cin>>n; 4.search
ifstreamiFile; 5.exit
iFile.open("student.dat",ios::binary); 1
while(iFile.read((char*)&obj,sizeof(obj)))
{if(obj.retadmno()==n) Enter The admission no. 2
obj.showdata();
} Enter The Name of The Student b
iFile.close();}
int main() enter your choice
{ intch,y=1; 1.enter details
write_data(); 2.view all details
do{ 3.view last entry
cout<<"\nenter your choice\n1.enter 4.search
details\n2.view all details\n3.view last 5.exit
entry\n4.search\n5.exit"; 2
cin>>ch;
switch(ch) Admission no. : 1
{case 1: write_data(); Student Name : a
break;
case 2: display(); Admission no. : 2
break; Student Name : b
case 3: obj.showdata();
break; enter your choice
case 4: search(); 1.enter details
break; 2.view all details
case 5: y=0; 3.view last entry
break; 4.search
default : 5.exit
cout<<"\nwrong choice"; 3
}
}while(y==1); Admission no. : 2
return 0;} Student Name : b
OUTPUT:
Enter The admission no. 1 enter your choice
1.enter details
Enter The Name of The Student a 2.view all details
3.view last entry
enter your choice 4.search
1.enter details 5.exit
2.view all details 4
3.view last entry
4.search enter the admn no:1
}
126. Program to find out the number of sri(float in,float ft)
records in the file billfile.dat by using the { i=in;
inbuilt seekg() and tellg() functions. f=ft;
#include<fstream.h> f=f+in/12;
#include<iostream.h> cout<<"f is"<<f<<endl;
class bill //cout<<"metres is"<<f/mtf<<endl;
{private: cout<<"meters"<<int(f/mtf);
intiBill_no; cout<<"cm"<<((f/mtf)-int(f/mtf))*100;
floatfBill_amt; }
public: };
void getdata() int main()
{cout<<”Enter Bill number”; { float ft,in;
cin>>iBill_no; cout<<"enter feet and inches"<<endl;
cout<<”Enter Bill amount”; cin>>ft>>in;
cin>>fBill_amt; sri s1(in,ft);
} }
void showdata() 128. Program to convert dollar to rupees.
{cout<<”Bill number ”<<iBill_no<<endl; #include<iostream>
cout<<”Bill amount ”<<fBill_amt<<endl; using namespace std;
} float dtr=65.005;
}; class doll //dollar to
void main() rupees(basic to object)//
{fstream Fi1(“billfile.dat”,ios::in); { private:
Fi1.seekg(0,ios::end); float d;
int iEnd; public:
iEnd=Fi1.tellg(); doll()
cout<<”The size of the file is “<<iEnd<<endl; { d=0.0;
cout<<”Size of one record is }
”<<sizeof(bill)<<endl‟ doll(float dollar)
ini iNorec=iEnd/sizeof(bill); { d=dollar;
cout<<”There are “<<iNorec<<”records in the cout<<"rupees is"<<d*dtr<<endl;
file”<<endl; }
}
};
MISCELLANEOUS PROGRAMS – II int main()
127. Program to convert object of class foot { float doller;
to object of class meter. cout<<"enter a dollars"<<endl;
#include<iostream> //basic to object from cin>>doller;
foot and inches to m and cm// doll d1(doller);
using namespace std; }
float mtf=3.280833; 129. Program to convert temperature
class sri centigrade to kelvin.
{ #include<iostream>
private: using namespace std;
float i; class conv
float f; {private: //convert temperature
public: crntigrade to kelvin(basic to
sri() object)//**********//
{ float d;
i=0.0; public:
f=0.0; conv()
{ d=0.0; } rate=0.0;}
conv(float deg) road(int c,int n,float r)
{d=deg; { code=c;
cout<<"temprature in Kelvin no=n;
is"<<d+273.15<<endl; rate=r;
} }
}; int retcode()
int main() { return code;
{ float d; }
cout<<"enter temp in degrees"<<endl; int retno()
cin>>d; { return no;
conv c1(d); }
} float retrate()
130. Program to conert rupees to dollars. { return rate;
#include<iostream> }
using namespace std; };
float dtr=65.005; class wide
class rup { private:
{ // convert rupee to dollar by object to basic// int code;
private: float fv;
float rup; public:
public: wide()
void get(float r) { code=0;
{ rup=r; fv=0.0;
} }
operator float() wide(road k)
{ cout<<"dollars { code=k.retcode();
is"<<rup/dtr<<endl; cout<<"hi"<<k.retcode()<<endl;
} fv=k.retno()*k.retrate();
}; }
int main() void show()
{ float rupee; {cout<<"code is"<<code<<endl;
cout<<"enter dollar"<<endl; cout<<"total rate"<<fv<<endl;
cin>>rupee; }
rup r1; };
r1.get(rupee); int main()
rupee=r1; { int x,y;
} float z;
131. Program to pass an object of one class cout<<"enter code"<<endl;
as a parameter to another class‘s cin>>x;
constructor. cout<<"enter no"<<endl;
#include<iostream> cin>>y;
using namespace std; cout<<"enter rate"<<endl;
class road cin>>z;
{ private: road r1(x,y,z);
int code; wide w1(r1);
int no; w1.show();
float rate; }
public: 132. Program to display the radius or area of
road() a circle from the given area or radius
{ code=0; respectively.
no=0; #include<iostream>
b=b/10; m2.get();
k++; m3=dammi.add(m1,m2);
} m3.show();
for(i=0;c!=0;i++) }
{ t=c%10; 136. class and object
sum=sum+pow(t,k); #include<iostream>
c=c/10; #include<cstring>
} using namespace std;
if(sum==a) class bank
{cout<<"armstrong number"<<endl; { private:
} int cid;
else char name[30];
{cout<<"not a Armstrong no"<<endl; float balance;
} //bank deposite and withdrawl
} public:
}; bank()
int main() {cid=11111;
{ armstrong k; strcpy(name,"sastra");
k.get(); balance=100000;
k.check(); }
} void deposite()
135.Program to overload ‗+‘ operator using {float m;
classes and objects. cout<<"enter money to bedepositd"<<endl;
include<iostream> cin>>m;
using namespace std; balance=balance+m;
class metre }
{ private: void withdraw()
int m; {float m;
int cm; cout<<"enter money to be withdraw"<<endl;
public: cin>>m;
void get() //returning an object balance=balance-m;
using data members meter and }
centimeter//********************// void display()
{ cout<<"enetr m"<<endl; {cout<<"cid:"<<cid<<endl;
cin>>m; cout<<"name:"<<name<<endl;
cout<<"enter cm"<<endl; cout<<"remaining balance"<<balance<<endl;
cin>>cm; }
} };
metre add(metre mm1,metre mm2) int main()
{ metre m3; { bank b1;
m3.m=mm1.m+mm2.m; int n;
m3.cm=mm1.cm+mm2.cm; cout<<"enter n"<<endl;
return m3; cin>>n;
} if(n==1)
void show() {b1.deposite(); }
{cout<<"metre is"<<m<<endl; else
cout<<"centimetre is"<<cm<<endl; {b1.withdraw(); }
} b1.display();
}; }
int main() 137. Overloading +
{ metre m1,m2,dammi,m3; #include<iostream>
m1.get(); using namespace std;
Prepared by I-Btech, II sem- I Sec,2017, Consolidated by Divya.V –I Section
& updated (additional) by Rengarajan.P- I B.tech, II sem- Q sec 2019 &
G.R.Brindha, SoC, SASTRA University
53
total. Provide values for the breakfast, lunch, cout<<"\nTotal details: ";
and dinner objects. Include the statement cout<<"THE TOTAL FOOD";
total = breakfast + lunch + dinner; in your total.disp();
program, then display values for the four if((breakfast==dinner))
Meal objects. d) Include statements in main cout<<"\nbreakfast and dinner same
to find the objects that have same calorie calories\n";
count. else if((breakfast==lunch))
#include <iostream> cout<<"\nbreakfsat and lunch same calories\n";
using namespace std; else if((lunch==dinner))
class meal cout<<"\nlunch and dinner same calories\n";
{ else
int cal; cout<<"\nNo calories are same\n";
char food[30]; }
public:
meal()
{ cal=0; } 146. Create a class named STUDENT with
meal(int c) the following private data members -
{ c=cal; } Name(string), RegNo(long) and Dept(string).
void getd() Include member functions - getStudInfo() to
{ cout<<"\nEnter the food item and the take input for its data members and
calories: "; dispStudInfo() to output the details. Derive a
cin>>food>>cal; class named ACADEMIC from STUDENT
} with the following additional data members -
void disp() YearOfStudy(int) and CGPA(float). Derive
{ cout<<"\nThe food item is: "<<food; another class named COCURRICULAR
cout<<"\nCalories for the food are: "<<cal; from STUDENT with a data member -
} SkillSet(2-dimensional char array of
meal operator+(meal a) dimension 5 X 10). Override the base class
{ meal b; member functions in both the derived classes
b.cal=cal+a.cal; to get information for their data members,
return meal(b); apart from invoking the base class member
} function. In main method, demonstrate the
bool operator==(meal d) functioning of the above hierarchy by
{ return((cal==d.cal)?true:false); creating 2 array of objects, one each for
} ACADEMIC and COCURRICULAR. From
}; ACADEMIC array of objects, display the
int main() details of the students with CGPA > 7.5
{ (Hint : Include appropriate member function
meal breakfast,dinner,lunch,total; to do this). Also display the details of all the
cout<<"\nEnter the details of breakfast : "; objects in COCURRICULAR array of
breakfast.getd(); objects.*/
cout<<"\nEnter the details of dinner : "; #include<iostream>
dinner.getd(); #include<string>
cout<<"\nEnter the details of lunch : "; #include<string.h>
lunch.getd(); using namespace std;
total=breakfast+lunch+dinner; class STUDENT
cout<<"\nBreakfast details: "; {
breakfast.disp(); string name,dept;
cout<<"\nDinner details: "; long rno;
dinner.disp(); public:
cout<<"\nLunch details: "; void getst()
lunch.disp(); {cout<<"Enter name,dept,rno:"<<endl;
double t=0;
t=height*height;
bmi2=((k*703)/(t));
if(bmi2>=18.5 && bmi2<=25)
{cout<<"\n Optimal wight.";}
else if(bmi2<18.5)
{cout<<"\n Underweight!!";}
else if(bmi2>25)
{cout<<"\n Overwight!!!";}
return bmi2;
}
};
int main()
{ float bmi1,bmi2;
float wt1;
int ht1;
cout<<"\n Enter the wight and height of person 1:";
cin>>wt1>>ht1;
bmi p1(wt1,ht1);
bmi p2;
p2.getmeasure();
float t;
t=p2.weight;
bmi1=p1.calbmi();
cout<<"\n The BMI of 1st person:"<<bmi1;
bmi2=p2.calbmi(t);
cout<<"\n The BMI of 2nd person:"<<bmi2;
}