100% found this document useful (1 vote)
151 views

OOPs Complete Filepdf

The document contains 11 coding problems related to C++ concepts like classes, objects, constructors, friend functions, etc. and their solutions. Some key problems include: 1. Defining a Person class with name, address, age, salary data members and a constructor to set their values and display them. 2. Overloading the area() function to calculate area of triangle, circle, rectangle by passing different parameters. 3. Using default arguments in a power() function to calculate squares when the power is omitted. 4. Multiplying two matrices by taking input, initializing result matrix and using nested for loops to calculate product. 5. Creating a Time class to take time input as

Uploaded by

Mayank Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
151 views

OOPs Complete Filepdf

The document contains 11 coding problems related to C++ concepts like classes, objects, constructors, friend functions, etc. and their solutions. Some key problems include: 1. Defining a Person class with name, address, age, salary data members and a constructor to set their values and display them. 2. Overloading the area() function to calculate area of triangle, circle, rectangle by passing different parameters. 3. Using default arguments in a power() function to calculate squares when the power is omitted. 4. Multiplying two matrices by taking input, initializing result matrix and using nested for loops to calculate product. 5. Creating a Time class to take time input as

Uploaded by

Mayank Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

1.

Write a program to take name, address as a character array, age as int ,


salary as float and contains inline functions to set the values and display it in
class named person.
#include <iostream>

using namespace std;

class person{
private:
string name;
string address;
int age;
float salary;

public:
person (string n, string a, int aa, float s){
name = n;
address = a;
age = aa;
salary = s;
}

void get(){
cout<<name<< endl;
cout<<address<< endl;
cout<<age<<endl;
cout<<salary<<endl;
}
};
int main() {
string n, a;
int aa;
float s;

cout<<"Enter name"<<endl;
getline(cin,n);
cout<<"Enter address"<<endl;
getline(cin,a);
cout<<"Enter age"<<endl;
cin>>aa;
cout<<"Enter salary"<<endl;
cin>>s;
printf("\n\n");

person p1(n, a, aa, s);


p1.get();

return 0;
}
>>OUTPUT
2. Using the concept of function overloading.Write function for calculating the
area of triangle ,circle and rectangle.
#include <iostream>
#include <cmath>

using namespace std;

void area (int r);


void area (float a, float b, float c);
void area (int l, int b);

int main(){
int x;
cout<<"Enter whose area is to be found"<<endl;
cout<<"1-> Circle"<<endl;
cout<<"2-> Triangle"<<endl;
cout<<"3-> Rectangle"<<endl;
cin>>x;
switch(x){
case 1:
int r;
cout<<"Enter radius"<<endl;
cin>>r;
area(r);
break;

case 2:
float a, b, c;
cout<<"Enter three sides of triangle"<<endl;
cin>>a>>b>>c;
area(a, b, c);
break;

case 3:
int l, br;
cout<<"Enter length and breadth"<<endl;
cin>>l>>br;
area(l,br);
break;
}
return 0;
}

void area(int r){


cout<<"Area of circle is:"<<r*r*3.14<<endl;
}

void area(float a, float b, float c){


float s = (a+b+c)*0.5;
float ar = sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"Area of triangle is:"<< ar <<endl;
}

void area(int l, int b){


cout<<"Area of rectangle is:"<<l*b<<endl;
}

>>OUTPUT
3. Write a program to find number m to power n. The function power takes a
double value for m and int value for n. Use default value for n to make the
function to calculate squares when this argument is omitted.
#include <iostream>
#include <cmath>

using namespace std;

int main(){
int p;
double b;
cout<<"Enter the base value:"<<endl;
cin>>b;
cout<<"Enter the power value:"<< endl;
cin>>p;
auto ans = pow(b,p);
cout<<"The answer is: "<<ans<<endl;

double b2;
int p2=2;
cout<<"\n\n Now by using default power value as 2:"<<endl;
cout<<"Enter base value"<<endl;
cin>>b2;
cout<<"The answer is: "<<pow(b2,p2)<<endl;

return 0;
}

>>OUTPUT
4. Write a program for multiplication of two matrices using OOPs.

#include <iostream>

using namespace std;

int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;

cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;

// If column of first matrix in not equal to row of second matrix,


// ask the user to enter the size of matrix again.
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";

cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;

cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
}

// Storing elements of first matrix.


cout << endl << "Enter elements of matrix 1:" << endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}

// Storing elements of second matrix.


cout << endl << "Enter elements of matrix 2:" << endl;
for(i = 0; i < r2; ++i)
for(j = 0; j < c2; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}

// Initializing elements of matrix mult to 0.


for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
mult[i][j]=0;
}

// Multiplying matrix a and b and storing in array mult.


for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
for(k = 0; k < c1; ++k)
{
mult[i][j] += a[i][k] * b[k][j];
}

// Displaying the multiplication of two matrix.


cout << endl << "Output Matrix: " << endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
cout << " " << mult[i][j];
if(j == c2-1)
cout << endl;
}
return 0;
}

>>OUTPUT
5. Create a class TIME with members hours, minutes, seconds. Take input and
add two time objects, passing objects to function and display results.
#include <iostream>
using namespace std;
class time
{
int hr,minute,sec;
public:
void get()
{
cin>>hr>>minute>>sec;
}
void disp()
{
cout<<hr<<":"<<minute<<":"<<sec;
}
void sum(time,time);

};
void time::sum(time t1,time t2)
{
sec=t1.sec+t2.sec;
minute=sec/60;
sec=sec%60;
minute =minute +t1.minute +t2.minute;
hr=minute /60;
minute =minute %60;
hr=hr+t1.hr+t2.hr;
}
int main()
{
time t1,t2,t3;
cout<<"Enter 1st time:";
t1.get();
cout<<"Enter 2nd time:";
t2.get();
cout<<"The 1st time is";
t1.disp();
cout<<"\nThe 2nd time is";
t2.disp();
t3.sum(t1,t2);
cout<<"\nThe resultant time is ";
t3.disp();
}
>>OUTPUT
Q6. Create a class student which has data members as name, branch, roll no.,
age, gender, marks in five subjects. Display the name of the student and his
percentage who has more than 70%. Use an array of objects.

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

using namespace std;

class student{
private:
char firstName[20], lastName[20],gender[10],branch[10];
int rollNo,age,marks[5],total;
public:
int percentage;
void getDetails();
void putDetails();
};//end of class
void student::getDetails()
{
cout<<"Enter First Name: ";
cin>> firstName;
cout<<"Enter Last Name: ";
cin>> lastName;
cout<<"Enter gender(Male/Female): ";
cin>> gender;
cout<<"Enter course(CSE/IT/MAE/ECE/EEE): ";
cin>> branch;
cout<<"Enter Roll Number: ";
cin>> rollNo;
total=0;
for(int i=0;i<5;i++)
{ cout<<"Enter Subject"<<i+1<<" marks ";
cin>>marks[i];
total+=marks[i];
}
percentage=total/5;
}
void student::putDetails()
{
cout<<"First Name:"<<firstName<<endl;
cout<<"Last Name:"<<lastName<<endl;
cout<<"Gender:"<<gender<<endl;
cout<<"Course:"<<branch<<endl;
cout<<"Roll Number"<<rollNo<<endl;
cout<<"Result(in %)"<<percentage<<endl;
}
int main()
{
student s[5];
s[0].getDetails();
s[1].getDetails();
s[2].getDetails();
s[3].getDetails();
s[4].getDetails();
for(int i=0;i<5;i++)
{
if(s[i].percentage >= 70){
cout <<" "<<endl;
s[i].putDetails();
cout <<" "<<endl;
}
}
>>OUTPUT
7. Write a program to enter a number and find its factorial using constructor
#include <iostream>

using namespace std;

class factorial{
private:
long int fact;
public:
factorial(int n){
fact = 1;
for (int i = 1; i <= n; i++)
{
fact*=i;
}
cout<<n<<"!= "<<fact<<endl;

}
};

int main(){
int n;
cout<<"Enter the number whose factorial is to be found"<<endl;
cin>>n;

factorial f(n);
return 0;
}

>>OUTPUT
8. Write a program to perform addition of two complex numbers constructor
overloading. The first constructor which takes no arguments is used to create
new objects which are not initialized, second which takes one argument is
used to initialize real and imaginary parts to equal values and third which
takes two arguments is used to initialize real and imaginary parts to two
different values.
#include <iostream>

using namespace std;

class complex{
private:
int real,img;

public:
complex() { real=0; img=0; }

complex(int r){ real=r; img=r; }

complex(int r, int i){ real=r; img=i; }

void print(){
cout<<"\n The sum of two complex numbers is
"<<real<<"+"<<img<<"i."<<endl;
}

complex sum(complex obj1, complex obj2)


{
complex obj3;

obj3.real=obj1.real+obj2.real;
obj3.img=obj1.img+obj2.img;
return obj3;
}
};

int main()
{
int a,b,c;
cout << "PROGRAM TO PERFORM ADDITION OF TWO COMPLEX NUMBERS
USING CONSTRUCTOR OVERLOADING"<<endl;
cout<<"For equal values :"<<endl;
cout<< "Enter the equal value of real and imaginary part of number 1: "<<endl;
cin>>a;
complex c1(a);
cout<<"For different values :"<<endl;
cout<<"Enter the real and imaginary part of number 2:"<<endl;
cin>>b>>c;
complex c2(b,c);
complex c3 = c3.sum(c1, c2);
c3.print();
return 0;
}

>>OUTPUT
9. Write a program to generate fibonacci series using a copy constructor
#include <iostream>

using namespace std;

class fibonacci
{
private:
unsigned long int f0,f1,fib;
public:
fibonacci()
{
f0=0;
f1=1;
fib=f0+f1;
}
fibonacci (fibonacci &ptr)
{
f0=ptr.f0;
f1=ptr.f1;
fib=ptr.fib;
}
void increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
}
void display()
{
cout << fib <<endl;;
}
}; //end of class construction
int main ()
{
fibonacci number;
int n;
cout <<"Enter the number of iterations you want to be performed in fabinocci
series: ";
cin>>n;
for (int i=0; i<=n;i++)
{
number.display();
number.increment();
}
return 0;
}
>>OUTPUT
10. Write a program to find the biggest of three numbers using friend
function.
#include <iostream>

using namespace std;

class largest{
int x,y,z;
public:
void getdata(){
cout<<"Enter the 3 numbers : ";
cin>>x>>y>>z;
}
friend int max(largest);

};

int max(largest obj){


int max=obj.x;
if(obj.y>max){
max=obj.y;
}
if(obj.z>max){
max=obj.z;
}
return max;
}

int main(){
largest obj;
obj.getdata();
int maxed;
maxed=max(obj);
cout<<"The greatest number is : "<<maxed;

return 0;
}

>>OUTPUT
11. Write a program to demonstrate the use of friend function with
Inline assignment.
#include <iostream>

using namespace std;

class assign{
int var1,var2;
public:
friend void assignment(assign);
};

inline void assignment(assign var){


cout<<"Enter 2 variables :";
cin>>var.var1>>var.var2;
cout<<"Variable 1="<<var.var1<<endl;
cout<<"Variable 2="<<var.var2<<endl;

int main(){
assign var;
assignment(var);

return 0;
}

>>OUTPUT
12. Write a program to find the greatest of two given numbers in two different
classes using friend function.

#include <iostream>
using namespace std;
class second;
class first{

public:
int one;
first(int n){
one=n;
}
friend int big(first,second);
};

class second{
public:
int two;
second(int n){
two=n;
}
friend int big(first,second);

};

int big(first f,second s){


if(f.one>s.two){
return f.one;
}
else{
return s.two;
}

}
int main(){
int a,b;
cout<<"Enter two numbers :";
cin>>a>>b;
first f(a);
second s(b);
int max=big(f,s);
cout<<"Bigger number is : "<<max;
return 0;
}

>>OUTPUT
13. Imagine a publishing company that markets both book and audiocassette
versions of its works. Create a class publication that stores the title (a string)
and price (type float) of a publication. From this class derive two classes: book,
which adds a page count (type int), and tape, which adds a playing time in
minutes (type float). Each of these three classes should have a getdata()
function to get its data from the user at the keyboard, and a putdata()
function to display its data. (Simple inheritance &amp; method overriding)
#include <iostream>

using namespace std;


class publication{
public:
string title;
float price;
void getdata(){
cout<<"Enter title and price :";
cin>>title>>price;

}
void putdata(){
cout<<"Title :"<<title<<endl<<"Price"<<price<<endl;
}
};

class book:private publication{


int pagecount;
public:
void getdata(){
cout<<"Enter title,price and pagecount :";
cin>>title>>price>>pagecount;
}
void putdata(){
cout<<"Title :"<<title<<endl<<"Price :"<<price<<endl<<"Pagecount
:"<<pagecount<<endl;

}
};
class tape:public publication{
float time;
public:
void getdata(){
cout<<"Enter title,price and Playtime :";
cin>>title>>price>>time;
}
void putdata(){
cout<<"Title :"<<title<<endl<<"Price :"<<price<<endl<<"Playtime
:"<<time<<endl;
}
};

int main(){
book b;
tape t;
b.getdata();
b.putdata();
t.getdata();
t.putdata();

return 0;
}

>>OUTPUT
14. C++ program to read and print employee information using multiple
inheritance. The program has following classes:
1. basicInfo
a. Data: name[char,30],empId[int], gender[char]
b. Functions: getData(), putData();
2. deptInfo
a. Data: deptName[char,30], assignWork[char,30], timeToComplete(int)
b. Functions: getData(), putData();
3. employeeInfo
a. Data: salary[int], age[int]
b. Functions: getData(), putData();

#include <iostream>

using namespace std;


class basicinfo{
public:
char name[30];
char gender[10];
int empID;

void getb(){
cout<<"Enter name,gender and empID :";
cin>>name>>gender>>empID;

}
void putb(){
cout<<"Name :"<<name<<endl<<"Gender :"<<gender<<endl<<"empID
:"<<empID<<endl;
}
};
class deptinfo:public basicinfo{
char deptName[30] ,assignWork[30];
int timeToComplete;
public:
void getdata(){
getb();
cout<<"Enter deptname,assignwork and timetocomplete :";
cin>>deptName>>assignWork>>timeToComplete;
}
void putdata(){
putb();
cout<<"deptname:"<<deptName<<endl<<"assignwork
:"<<assignWork<<endl<<"timetocomplete :"<<timeToComplete<<endl;

}
};
class employeeinfo:public basicinfo{
int salary, age;
public:
void getdata(){
getb();
cout<<"Enter salary and age :";
cin>>salary>>age;
}
void putdata(){
putb();
cout<<"salary :"<<salary<<endl<<"age :"<<age<<endl;
}
};
int main(){
deptinfo dept;
dept.getdata();
dept.putdata();

return 0;
}

>>OUTPUT
15. Design three classes STUDENT ,EXAM and RESULT. The STUDENT class has
data members such as rollno, name. create a class EXAM by inheriting the
STUDENT class. The EXAM class adds data members representing the marks
scored in six subjects. Derive the RESULT from the EXAM class and has its own
data members such as total marks. Write a program to model this
Relationship.

#include <iostream>

using namespace std;


class student{
public:
char name[30];
int roll;

void getb(){
cout<<"Enter name and rollno :";
cin>>name>>roll;

}
void putb(){
cout<<"Name :"<<name<<endl<<"Rollno :"<<roll<<endl;
}
};

class exam:public student{


public:
int marks[6];

void getdata(){
getb();
cout<<"Enter marks for 6 subjects :";
for(int i=0;i<6;i++){
cin>>marks[i];
}
}
void putdata(){
putb();
cout<<"Marks scored :"<<endl;
for(int i=0;i<6;i++){
cout<<marks[i];
}

};
class result:public exam{
int total=0;
public:
void getdata(){
getb();
cout<<"Enter marks for 6 subjects :";
for(int i=0;i<6;i++){
cin>>marks[i];
}

}
void putdata(){
putb();
for(int i=0;i<6;i++){
total+=marks[i];
}
cout<<"Total marks :"<<total<<endl;

}
};

int main(){
result r;
r.getdata();
r.putdata();

return 0;
}

>>OUTPUT
16. Create class first with data members book no, book name and member
function getdata and putdata. Create a class second with data members
author name, publisher and members getdata and showdata. Derive a class
third from first and second with data member no of pages and year of
publication. Display all this information using an array of objects of third class.
#include <iostream>
using namespace std;

class First
{
int book_no;
string book_name;
public:
void getData()
{
cout<<"Enter Book No: ";
cin>>book_no;
cout<<"Enter Book Name: ";
cin>>book_name;
}
void putData()
{
cout<<"Book No: "<<book_no<<endl;
cout<<"Book Name: "<<book_name<<endl;
}
};

class Second
{
string author_name;
string publisher;
public:
void getData()
{
cout<<"Enter Author Name: ";
cin>>author_name;
cout<<"Enter Publisher: ";
cin>>publisher;
}
void showData()
{
cout<<"Author Name: "<<author_name<<endl;
cout<<"Publisher: "<<publisher<<endl;
}
};
class Third: public First, public Second
{
int no_of_pages;
int year_of_publication;
public:
void getData()
{
First::getData();
Second::getData();
cout<<"Enter No. of Pages: ";
cin>>no_of_pages;
cout<<"Enter Year of Publication: ";
cin>>year_of_publication;
}
void showData()
{
First::putData();
Second::showData();
cout<<"No. of Pages: "<<no_of_pages<<endl;
cout<<"Year of Publication: "<<year_of_publication<<endl;
}
};

int main()
{
int n;
cout<<"Enter number of books: ";
cin>>n;
Third book[n];
for(int i=0;i<n;i++)
{
cout<<"\nBook "<<i+1<<endl;
book[i].getData();
}
for(int i=0;i<n;i++)
{
cout<<"\nBook "<<i+1<<endl;
book[i].showData();
}
return 0;
}

>>OUTPUT
17. Create a base class called SHAPE. Use this class to store two double type
values. Derive two specific classes called TRIANGLE and RECTANGLE from the
base class. Add to the base class, a member function getdata to initialize base
class data members and another member function display to compute and
display the area of figures. Make display a virtual function and redefine this
function in the derived classes to suit their requirements. Using these three
classes, design a program that will accept driven of a TRIANGLE or
RECTANGLE interactively and display the area.

#include<iostream>
using namespace std;

class Shape
{
protected:
double width, height;

public:
Shape(double width, double height)
{
this->width = width;
this->height = height;
}

void getData()
{
cout << "Enter width and height respectively: ";
cin >> width >> height;
}

virtual void displayArea()


{
cout << "Area = " << width * height << endl;
}
};

class Triangle: public Shape


{
public:
Triangle(double width, double height): Shape(width, height)
{
}
void displayArea()
{
cout << "Area of Triangle = " << 0.5 * width * height << endl;
}
};
class Rectangle: public Shape
{
public:
Rectangle(double width, double height): Shape(width, height)
{
}
void displayArea()
{
cout << "Area of Rectangle = " << width * height << endl;
}
};

int main()
{
double width, height;

cout << "Enter width and height of Triangle: ";


cin >> width >> height;

Triangle triangle(width, height);


triangle.getData();
triangle.displayArea();

cout << "Enter width and height of Rectangle: ";


cin >> width >> height;

Rectangle rectangle(width, height);


rectangle.getData();
rectangle.displayArea();

return 0;
}
>>OUTPUT
18 . Create a base class basic_info with data members name ,roll no, gender
and two member functions getdata and display. Derive a class physical_fit
from basic_info which has data members height and weight and member
functions getdata and display. Display all the information using the object of
the derived class.
#include<iostream>
using namespace std;

class basic_info
{
string name;
int roll_no;
char gender;

public:
void getdata()
{
cout << "Enter Name: ";
cin >> name;
cout << "Enter Roll No.: ";
cin >> roll_no;
cout << "Enter Gender: ";
cin >> gender;
}
void display()
{
cout << "Name: " << name << "\n";
cout << "Roll No.: " << roll_no << "\n";
cout << "Gender: " << gender << "\n";
}
};

class physical_fit: public basic_info


{
float height, weight;

public:
void getdata()
{
basic_info::getdata();
cout << "Enter Height: ";
cin >> height;
cout << "Enter Weight: ";
cin >> weight;
}
void display()
{
basic_info::display();
cout << "Height: " << height << "\n";
cout << "Weight: " << weight << "\n";
}
};

int main()
{
physical_fit p;
p.getdata();
p.display();
return 0;
}

>>OUTPUT
19. Write a program to overload less than (<) operators.

#include <iostream>
using namespace std;

class A
{
private:
int x;

public:
A() : x(0) { }
A(int x) : x(x) { }

friend bool operator<(A, A);


};

bool operator<(A a1, A a2)


{
return a1.x < a2.x;
}

int main()
{
A a1(10), a2(20);

if (a1 < a2)


cout << "a1 is smaller than a2";
else
cout << "a1 is not smaller than a2";

return 0;
}

>>OUTPUT
20. Write a program to overload binary + operator.

#include<iostream>
using namespace std;

class Sum
{
private:
int num1;
public:
Sum(int n1) { num1 = n1; }
void display() { cout << "Number = " << num1 << endl; }
Sum operator + (Sum const &obj)
{
Sum g(0);
g.num1 = this->num1 + obj.num1;
return g;
}
};

int main()
{
Sum g1(10);
Sum g2(20);
Sum g3(30);
g1.display();
g2.display();
g3.display();
Sum g4 = g1 + g2 + g3;
g4.display();
return 0;
}

>>OUTPUT
21. Write a program to overload binary [ * ] operator.
#include <iostream>

using namespace std;

class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }

// Overloading binary * operator


Complex operator * (Complex const &obj)
{
Complex result ;
result.real = (real * obj.real)-(imag * obj.imag);
result.imag = (imag * obj.real) + (real * obj.imag);
return result;
}
void print()
{
cout << real << " + i" << imag << endl;
}
};
int main()
{
Complex c1(10, 5), c2(2, 2);
Complex c3 = c1 * c2; // An example call to "*" operator
cout << "The result of c1 * c2 is : ";
c3.print();
return 0;
}

>>OUTPUT
22. Write a program to define the function template for swapping two items
of the various data types such as integer, float, and characters.

#include <iostream>
using namespace std;

template <class T> // Template declaration

void swaps(T &a, T &b)


{
T t = a; a =
b; b = t;
}

// Main function
int main()
{
int a = 5, b = 7;
cout << "Before swapping: a = " << a << ", b = " << b << endl; swaps(a, b);
cout << "After swapping: a = " << a << ", b = " << b << endl;

float c = 5.5, d = 7.7;


cout << "Before swapping: c = " << c << ", d = " << d << endl; swaps(c, d);
cout << "After swapping: c = " << c << ", d = " << d << endl;

char e = 'a', f = 'b';


cout << "Before swapping: e = " << e << ", f = " << f << endl; swaps(e, f);
cout << "After swapping: e = " << e << ", f = " << f << endl;

return 0;
}

>>OUTPUT
23. Write a program to define the function template for calculating the
square of given numbers with different data types.

#include <iostream>
using namespace std;

template <class T>


T square(T x)
{
T result; result = x *
x; return result;
}

int main()
{
int a = 5; float b =
5.5;
cout << "Square of integer " << a << " is " << square(a)
<< endl;
cout << "Square of float " << b << " is " << square(b) << endl;
return 0;
}
>>OUTPUT
24. Write a program to illustrate how template functions can be overloaded

#include <iostream>
using namespace std;

template <typename T> T


add(T a, T b)
{
return a + b;
}
template <typename T> T
add(T a, T b, T c)
{
return a + b + c;
}
int main()
{
int a = 10, b = 20, c = 30;
float d = 10.5, e = 20.5, f = 30.5;

cout << "Integer sum: " << add(a, b) << endl; cout << "Integer
sum: " << add(a, b, c) << endl; cout << "Float sum: " << add(d, e)
<< endl; cout << "Float sum: " << add(d, e, f) << endl;

return 0;
}
>>OUTPUT
25. Write a program to illustrate how to define and declare a class template
for reading two data items from the keyboard and to find their sum.

#include <iostream>
using namespace std;

template <class T> class


Sum
{
T num1, num2;

public: void
getData()
{
cout << "Enter two numbers: "; cin >> num1
>> num2;
}
T add() {
return (num1 + num2);
} }; int
main()
{
Sum <int> s1; s1.getData();
cout << "Sum of two numbers: " << s1.add() << endl;

Sum <float> s2; s2.getData();


cout << "Sum of two numbers: " << s2.add() << endl;

return 0;
}
>>OUTPUT
26. Write a program to demonstrate the use of special functions, constructor
and destructor in the class template. The program is used to find the biggest
of two entered numbers.

#include<iostream>
using namespace std;

template <class Type>


class FindBig
{
Type a,b; public:

FindBig(Type x, Type y)
{ a=x;
b=y;
}

~FindBig()
{
cout<<"Object Destructed"<<endl;
}

Type findBig()
{
Type z;
if(a>b)
z=a; else
z=b;
return z;
}
};

int main()
{
int a,b;
cout<<"Enter two numbers: "; cin>>a>>b;

FindBig<int> obj(a,b);
cout<<"The bigger of two numbers is "<<obj.findBig()<<endl;

return 0;
}
>>OUTPUT
27. Write a program to read a set of lines from the keyboard and to store it
on a specified file.

#include <iostream> #include


<fstream> #include <string>

using namespace std;

int main()
{
string line; ofstream outfile;
//open the file for writing
outfile.open("output.txt"); //read lines from
keyboard
cout << "Enter the lines you want to write in the file(enter 'end' to
stop):\n"; getline(cin, line); while (line != "end")
{ outfile << line << "\n";
getline(cin, line);
}
//close the file outfile.close();
cout << "The lines have been written to the file"; return 0;
}
>>OUTPUT
28. Write a program to read a text file and display its contents on the screen.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
string line;
ifstream myfile ("example.txt"); //opening the file if (myfile.is_open())
{
while (getline (myfile,line)) //reading line by line
{
cout << line << '\n';
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}
>>OUTPUT
29. Write a program to copy the contents of a file into another.

#include <iostream> #include


<fstream> #include <string>

using namespace std;

int main()
{
ifstream inputFile; ofstream outputFile;

inputFile.open("abc.txt"); outputFile.open("aaa.txt");

// Check if the files are open


if (inputFile.is_open() && outputFile.is_open())
{
string line;
while (getline(inputFile, line))
{
outputFile << line << "\n";
}

inputFile.close();
outputFile.close();

cout << "The contents of the file were successfully copied to another file"
<< endl;
} else
{
cout << "Error opening the files" << endl;
}
return 0;
}

>>OUTPUT
30. Write a program to read the class object of student info such as name,
age, sex, height and weight from the keyboard and to store them on a
specified file using read () and write () functions. Again, the same file is
opened for reading and displaying the contents of the file on the screen.

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

class student_info
{
public: string name;
int age; char sex;
double height; double
weight;
};

int main()
{
student_info student;
string fileName;

cout << "Enter Name: "; cin >>


student.name; cout << "Enter Age:
"; cin >> student.age; cout <<
"Enter Sex: "; cin >> student.sex;
cout << "Enter Height: "; cin >>
student.height; cout << "Enter
Weight: ";
cin >> student.weight;

cout << "Enter filename to store the data: "; cin >> fileName;

ofstream outFile;
outFile.open(fileName, ios::out | ios::binary); if
(outFile.is_open())
{
outFile.write((char*)&student, sizeof(student)); outFile.close();
} else
{ cout
<< "Unable
to open
file" <<
endl;
}

ifstream inFile;
inFile.open(fileName, ios::in | ios::binary); if (inFile.is_open())
{ inFile.read((char*)&student, sizeof(student)); cout <<
"Name: " << student.name << endl; cout << "Age: " <<
student.age << endl; cout << "Sex: " << student.sex << endl;
cout << "Height: " << student.height << endl; cout << "Weight: "
<< student.weight << endl; inFile.close();
} else
{
cout << "Unable to open file" << endl;
}

return 0;
}
>>OUTPUT

You might also like