OOPS FILE
OOPS FILE
1
Object Oriented Programming Name: Hemant
Roll No.: 2823298
adding, subtracting, multiplying, or
dividing the two numbers. (It should
use a switch statement to select the
operation). Finally it should display
the result. When it finishes the
calculation, the program should ask if
the user wants to do another
calculation. The response can be ‘Y’
or ‘N’.
Create the equivalent of a four
function calculator. The program
should request the user to enter a
number, an operator, and another
number. It should then carry out the
specified arithmetical operation:
adding, subtracting, multiplying, or
4 dividing the two numbers. (It should 11-13
use a switch statement to select the
operation). Finally it should display
the result. When it finishes the
calculation, the program should ask if
the user wants to do another
calculation. The response can be ‘Y’
or ‘N’.
2
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Write a program in C++ that overloads
a function area to calculate the area of
a circle (given radius), a rectangle
7 (given width and height), and a square 20-21
(given side length).
c) Disease
3
Object Oriented Programming Name: Hemant
Roll No.: 2823298
d) Date of discharge
4
Object Oriented Programming Name: Hemant
Roll No.: 2823298
a) Accept deposit from a customer and
update the balance.
5
Object Oriented Programming Name: Hemant
Roll No.: 2823298
• constructor with two arguments.
Area of rectangle = x * y
Area of triangle = ½ * x * y
6
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #1
Aim: Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called
power ( ) that takes a double value for n and an int value for p, and returns the result as double value. Use a
default argument of 2 for p, so that if this argument is omitted, the number will be squared. Write a main ( )
function that gets values from the user to test this function.
Code:
#include<iostream>
double result = 1;
result *= n;}
return result; }
int main() {
double number;
int exponent;
cout << "Enter an exponent (or press 0 to square the number): ";
if (exponent == 0) {
cout << number << " squared is: " << power(number) << endl;
} else {
7
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout << number << " raised to the power of " << exponent << " is: " << power(number, exponent) << endl; }
return 0; }
Output:
Program #2
Aim: A point on the two dimensional plane can be represented by two numbers: an X coordinate and a Y
coordinate. For example, (4,5) represents a point 4 units to the right of the origin along the X axis and 5 units up
the Y axis. The sum of two points can be defined as a new point whose X coordinate is the sum of the X
coordinates of the points and whose Y coordinate is the sum of their Y coordinates. Write a program that uses a
structure called point to model a point. Define three points, and have the user input values to two of them. Then
set the third point equal to the sum of the other two, and display the value of the new point .
Code:
#include<istream>
struct point{
int x;
int y; };
int main(){
point p1,p2,p3;
cin>>p1.x>>p1.y;
cin>>p2.x>>p2.y;
8
Object Oriented Programming Name: Hemant
Roll No.: 2823298
p3.x=p1.x+ p2.x;
p3.y=p1.y+p2.y;
cout<<p3.x<<","<<p3.y;
return 0;}
Output:
Program #3
Aim: Create the equivalent of a four function calculator. The program should request the user to enter a
number, an operator, and another number. It should then carry out the specified arithmetical operation: adding,
subtracting, multiplying, or dividing the two numbers. (It should use a switch statement to select the operation).
Finally it should display the result. When it finishes the calculation, the program should ask if the user wants to
do another calculation. The response can be ‘Y’ or ‘N’.
Code:
#include<iostream>
int main(){
double num1,num2;
double result;
char op,repeat;
do{
cin>>num1;
cin>>op;
cin>>num2;
switch (op){
case '+':
result=num1+num2;
9
Object Oriented Programming Name: Hemant
Roll No.: 2823298
break;
case'-':
result=num1-num2;
break;
case'*':
result=num1*num2;
break;
case'/':
if(num2!=0)
result=num1/num2;
else
cout<<"invalid";
break;
cin>>repeat;
while(repeat=='Y'||repeat=='y');
return 0;
Output:
10
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #4
Aim: Create the equivalent of a four function calculator. The program should request the user to enter a
number, an operator, and another number. It should then carry out the specified arithmetical operation: adding,
subtracting, multiplying, or dividing the two numbers. (It should use a switch statement to select the operation).
Finally it should display the result. When it finishes the calculation, the program should ask if the user wants to
do another calculation. The response can be ‘Y’ or ‘N’.
Code:
#include<iostream>
#include<string>
int main(){
float totalcharge=0.0;
string name;
int units;
11
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout<<"enter your name:";
getline(cin,name);
cin>>units;
if(units<=100){
totalcharge=units*0.60;
else if(units<=300){
totalcharge=(100*0.60)+((units-100)*0.80);
else {
totalcharge=(100*0.60)+(200*0.80)+((units-300)*0.90);
if(totalcharge<50){
totalcharge=50;
if(totalcharge>300){
totalcharge=totalcharge+0.15;
cout<<"\nname:"<<name;
cout<<"\ntotalcharges:"<<totalcharge;
return 0;
Output:
12
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #5
Aim: A phone number, such as (212) 767-8900, can be thought of as having three parts: the area code (212),
the exchange (767) and the number (8900). Write a program that uses a structure to store these three parts of a
phone number separately. Call the structure phone. Create two structure variables of type phone. Initialize one,
and have the user input a number for the other one.
Code:
#include<iostream>
class phone
private:
int acode;
int exhange;
int number;
public:
void initialize(){
acode=212;
exhange=767;
number=8100;
}
13
Object Oriented Programming Name: Hemant
Roll No.: 2823298
void getdata(){
cin>>acode>>exhange>>number;
void putdata(){
cout<<"("<<acode<<")"<<exhange<<"-"<<number;
}};
int main(){
phone p1,p2;
p1.initialize();
p2.getdata();
p1.putdata();
p2.putdata();
return 0;
Output:
14
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #6
Aim: Write a program in C++ that overloads a function area to calculate the area of a circle (given radius), a
rectangle (given width and height), and a square (given side length).
Code:
#include<iostream>
int main() {
double radius;
15
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout << "Enter the radius of the circle: ";
cout << "Area of the circle: " << area(radius) << endl;
cout << "Area of the square: " << area(side) << endl;
cout << "Enter the length and width of the rectangle: ";
cout << "Area of the rectangle: " << area(length, width) << endl;
return 0;
Output:
16
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #7
Aim: Write a program in C++ that overloads a function area to calculate the area of a circle (given radius), a
rectangle (given width and height), and a square (given side length).
Code:
#include<iostream>
class DB;
class DM
float meters;
float centimeters;
public:
DM():meters(0),centimeters(0){}
void readDistance(){
cin>>meters>>centimeters;
void display()const{
17
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout<<"distance:"<<meters<<"meters,"<<centimeters<<"centimeters";
};
class DB{
float feet;
float inches;
public:
DB():feet(0),inches(0){}
void readDistance(){
cin>>feet>>inches;
void display()const{
cout<<"distance:"<<feet<<"feet,"<<inches<<"inches";
};
float totalmeters=db.feet*0.3048+db.inches*0.0254;
float totalcentimeters=(totalmeters-static_cast<int>(totalmeters))*100;
DM result;
result.meters=dm.meters+static_cast<int>(totalmeters);
result.centimeters=dm.centimeters+totalcentimeters;
if(result.centimeters>=100){
result.meters+=static_cast<int>(result.centimeters/100);
result.centimeters+=static_cast<int>(result.centimeters)%100;
18
Object Oriented Programming Name: Hemant
Roll No.: 2823298
}
return result;
int main(){
DM distanceM;
DB distanceF;
distanceM.readDistance();
distanceF.readDistance();
DM result=addDistance(distanceM,distanceF);
result.display();
return 0;
Output:
19
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #8
Aim: Imagine a tollbooth with a class called toll Booth. 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 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 displays the two totals. 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 kay should cause the program to print out the total cars and total cash and then exit.
Code:
#include <iostream>
#include <conio.h>
class TollBooth {
private:
double totalCash;
public:
void payingCar() {
totalCars++;
totalCash += 0.50;
void nopayCar() {
20
Object Oriented Programming Name: Hemant
Roll No.: 2823298
totalCars++;
cout << "Total cash collected: $" << totalCash << endl;
}};
int main() {
TollBooth tollBooth;
char key;
cout << "Press 'P' for a paying car, 'N' for a non-paying car, and 'ESC' to exit and display totals.\n";
while (true) {
key = _getch();
if (key == 27) {
tollBooth.display();
break;
tollBooth.payingCar();
tollBooth.nopayCar();
else {
cout << "Invalid key. Press 'P' for paying car, 'N' for non-paying car, or ESC to exit.\n";
}}
return 0;
}
21
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Output:
Program #9
Aim: Create a C++ program that defines a time class to represent time in hours and minutes format.
Use objects of class as function arguments to add two time objects and display the result in hours and
minutes format.
Code:
#include<iostream>
class time{
int hours;
int minutes;
public:
hours=h;minutes=m;
void putT(void){
cout<<hours<<"hours and";
cout<<minutes<<"minutes"<<"\n";
};
22
Object Oriented Programming Name: Hemant
Roll No.: 2823298
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
int main(){
time T1,T2,T3;
T1.getT(4,44);
T2.getT(9,20);
T3.sum(T1,T2);
cout<<"T1= ";
T1.putT();
cout<<"T2= ";
T2.putT();
cout<<"T3= ";
T3.putT();
return 0;
Output:
23
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #10
Aim:A hospital wants to create a database regarding its indoor patients. The information to store include
b) Date of admission
c) Disease
d) Date of discharge
Create a structure to store the date (year, month and date as its members). Create a base class to store the above information.
The member function should include functions to enter information and display a list of all the patients in the database. Create
a derived class to store the age of the patients. List the information about all the to store the age of the patients. List the
information about all the pediatric patients (less than twelve years in age).
Code:
#include <iostream>
#include <string>
struct Date {
int year;
int month;
int day;
};
class Patient {
protected:
string name;
Date admissionDate;
24
Object Oriented Programming Name: Hemant
Roll No.: 2823298
string disease;
Date dischargeDate;
public:
void enterInfo() {
cin.ignore();
getline(cin, name);
cin.ignore();
getline(cin, disease);
cout << "Admission Date: " << admissionDate.year << "-" << admissionDate.month << "-" << admissionDate.day ;
cout << "Discharge Date: " << dischargeDate.year << "-" << dischargeDate.month << "-" << dischargeDate.day ;
}};
private:
int age;
public:
void enterInfo() {
Patient::enterInfo();
25
Object Oriented Programming Name: Hemant
Roll No.: 2823298
}
displayInfo();
}}};
int main() {
PediatricPatient patients[MAX_PATIENTS];
int numPatients;
cout << "Number of patients exceeds the maximum limit of " << MAX_PATIENTS << "." ;
numPatients = MAX_PATIENTS;
cout << "\nEntering information for patient " << i + 1 << ":" ;
patients[i].enterInfo();
patients[i].displayPediatricInfo();
return 0;
Output:
26
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #11
Aim: . Make a class Employee with a name and salary. Make a class Manager inherit from Employee. Add an instance
variable, named department, of type string. Supply a method to to String that prints the manager’s name, department and
salary. Make a class Executive inherits from Manager. Supply a method to String that prints the string “Executive”
followed by the information stored in the Manager superclass object. Supply a test program that tests these classes and
methods.
Code:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
class Employee {
protected:
string name;
double salary;
public:
: name(name), salary(salary) {}
return salary;
stringstream ss;
};
protected:
string department;
public:
return department;
stringstream ss;
return "Manager: " + getName() + ", Department: " + department + ", Salary: " + ss.str();
};
public:
};
int main() {
return 0;
Output:
29
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #12
Aim: Assume that a bank maintains two kinds of accounts for customers, one called as savings account and the other as
current account. The savings account provides compound interest and withdrawal facilities but no cheque book facility. The
current account provides cheque book facility but no interest. Current account holders should also maintain a minimum
balance and if the balance falls below this level, a service charge is imposed.
Create a class account that stores customer name, account number and type of account. From this derive the classes
cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to
achieve the following tasks:
e) Check for the minimum balance, impose penalty, necessary and update the balance.
f) Do not use any constructors. Use member functions to initialize the class members
Code:
#include <iostream>
30
Object Oriented Programming Name: Hemant
Roll No.: 2823298
#include <string>
class Account {
protected:
string customerName;
int accountNumber;
float balance;
string accountType;
public:
customerName = name;
accountNumber = accNum;
accountType = type;
balance = initialBalance;
balance += amount;
void displayBalance() {
cout << "\nBalance for Account " << accountNumber << ": " << balance ;
balance -= amount;
} else {
};
private:
float minBalance;
float penaltyCharge;
public:
void initializeCurrentAccount(string name, int accNum, float initialBalance, float minBal, float penalty) {
minBalance = minBal;
penaltyCharge = penalty;
balance -= penaltyCharge;
cout << "\nBalance below minimum. Penalty charged: " << penaltyCharge ;
} else {
};
float interestRate;
public:
interestRate = interest;
balance += interest;
};
int main() {
Cur_Acct currentAccount;
currentAccount.deposit(200.0f);
currentAccount.withdraw(300.0f);
currentAccount.applyCharges();
currentAccount.displayBalance();
cout ;
Sav_Acct savingsAccount;
savingsAccount.deposit(500.0f);
savingsAccount.withdraw(200.0f);
savingsAccount.applyCharges();
savingsAccount.displayBalance();
return 0;
33
Object Oriented Programming Name: Hemant
Roll No.: 2823298
}
Output:
Program #13
Aim: Create a class rational which represents a numerical value by two double values- NUMERATOR and
DENOMINATOR. Include the following public member Functions:
• void reduce( ) that reduces the rational number by eliminating the highest common factor between the numerator and
denominator.
Code:
#include <iostream>
class Rational {
34
Object Oriented Programming Name: Hemant
Roll No.: 2823298
private:
int numerator;
int denominator;
public:
if (denominator == 0) {
cerr << "Error: Denominator cannot be zero. Setting denominator to 1." << endl;
denominator = 1;
reduce();
void reduce() {
numerator /= gcd;
denominator /= gcd;
if (r.denominator == 0) {
cerr << "Error: Denominator cannot be zero. Setting denominator to 1." << endl;
r.denominator = 1;
r.reduce();
return input;
return output;
};
int main() {
cout << "Sum of the two rational numbers: " << sum ;
return 0;
Output:
36
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #14
Aim: Create a class rational which represents a numerical value by two double values- NUMERATOR and
DENOMINATOR. Include the following public member Functions:
• void reduce( ) that reduces the rational number by eliminating the highest common factor between the numerator and
denominator.
Code:
#include <iostream>
37
Object Oriented Programming Name: Hemant
Roll No.: 2823298
class Father {
protected:
int age;
public:
Father(int x) {
age = x;
cout << "I AM THE FATHER, my age is: " << age ;
};
public:
Son(int x) : Father(x) {}
cout << "I AM THE SON, my father's age is: " << age ;
};
public:
Daughter(int x) : Father(x) {}
cout << "I AM THE DAUGHTER, my father's age is: " << age ;
};
int main() {
Father fatherObj(50);
Son sonObj(50);
Daughter daughterObj(50);
38
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Father* ptr;
ptr = &fatherObj;
ptr->iam();
ptr = &sonObj;
ptr->iam();
ptr = &daughterObj;
ptr->iam();
return 0;
Output:
39
Object Oriented Programming Name: Hemant
Roll No.: 2823298
Program #15
Aim: Create a base class called shape. Use this class to store two double type values that could be used to compute the area
of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to the base class, a member
function get_data( ) to initialize baseclass data members and another member function display_area( ) to compute and display
the area of figures. Make display_area ( ) as 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 dimensions of a triangle or a rectangle interactively
and display the area.
Remember the two values given as input will be treated as lengths of two sides in the case of rectangles and as base and
height in the case of triangles and used as follows:
Area of rectangle = x * y
Area of triangle = ½ * x * y
Code:
#include <iostream>
class Shape {
protected:
public:
value2 = v2;
};
public:
};
public:
};
int main() {
Shape *shape;
int choice;
if (choice == 1) {
Triangle triangle;
41
Object Oriented Programming Name: Hemant
Roll No.: 2823298
double base, height;
triangle.get_data(base, height);
shape = ▵
else if (choice == 2) {
Rectangle rectangle;
rectangle.get_data(length, width);
shape = &rectangle;
else {
return 0;
shape->display_area();
return 0;
Output:
42
Object Oriented Programming Name: Hemant
Roll No.: 2823298
43