0% found this document useful (0 votes)
31 views43 pages

OOPS FILE

Uploaded by

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

OOPS FILE

Uploaded by

Robins Kumar
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/ 43

Object Oriented Programming Name: Hemant

Roll No.: 2823298


INDEX
S. No Title of Practical Date Page Signature
No.
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
1 1-7
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.

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
2 8-9
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.
Create the equivalent of a four
function calculator. The program
should request the user to enter a
3 9-10
number, an operator, and another
number. It should then carry out the
specified arithmetical operation:

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’.

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
5 phone number separately. Call the 13-16
structure phone. Create two structure
variables of type phone. Initialize one,
and have the user input a number for
the other one.

Write a program in C++ that


overloads a function area to calculate
6 the area of a circle (given radius), a 17-19
rectangle (given width and height),
and a square (given side length).

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).

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 (
8 ), increments the car total but adds 21-24
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.
Create a C++ program that defines
a time class to represent time in
hours and minutes format. Use
9 objects of class as function 24-25
arguments to add two time objects
and display the result in hours and
minutes format.
A hospital wants to create a database
regarding its indoor patients. The
information to store include

10 a) Name of the patient 25-27


b) Date of admission

c) Disease

3
Object Oriented Programming Name: Hemant
Roll No.: 2823298
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).

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
11 and salary. Make a class Executive 27-30
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.
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
12 30-33
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:

4
Object Oriented Programming Name: Hemant
Roll No.: 2823298
a) Accept deposit from a customer and
update the balance.

b) Display the balance.

c) Compute and deposit interest.

d) Permit withdrawal and update the


balance.

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

Create a class rational which represents a


numerical value by two double values-
NUMERATOR and DENOMINATOR.
Include the following public member
Functions:

• constructor with no arguments


(default).

• constructor with two arguments.

• void reduce( ) that reduces the


rational number by eliminating the
highest common factor between the
13 numerator and denominator. 33-35

• Overload + operator to add two


rational number.

• Overload >> operator to enable input


through cin.

• Overload << operator to enable


output through cout.

Write a main ( ) to test all the functions in


the class.

Create a class rational which represents a


numerical value by two double values-
NUMERATOR and DENOMINATOR.
Include the following public member
14 Functions:
35-38

• constructor with no arguments


(default).

5
Object Oriented Programming Name: Hemant
Roll No.: 2823298
• constructor with two arguments.

• void reduce( ) that reduces the


rational number by eliminating the
highest common factor between the
numerator and denominator.

• Overload + operator to add two


rational number.

• Overload >> operator to enable input


through cin.

• Overload << operator to enable


output through cout.

Write a main ( ) to test all the functions in


the class.

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,
15 38-40
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

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>

using namespace std;

double power(double n, int p = 2) {

double result = 1;

for (int i = 1; i <= p; ++i) {

result *= n;}

return result; }

int main() {

double number;

int exponent;

cout << "Enter a number: ";

cin >> number;

cout << "Enter an exponent (or press 0 to square the number): ";

cin >> exponent;

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>

using namespace std;

struct point{

int x;

int y; };

int main(){

point p1,p2,p3;

cout<<"enter the value for p1:";

cout<<"enter the value of x and y:";

cin>>p1.x>>p1.y;

cout<<"enter the value for p2:";

cout<<"enter the value of x and y:";

cin>>p2.x>>p2.y;

cout<"sum of p1 and p2 is:";

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>

using namespace std;

int main(){

double num1,num2;

double result;

char op,repeat;

do{

cout<<"enter the value of num1:";

cin>>num1;

cout<<"enter the operator:";

cin>>op;

cout<<"enter the value of num2:";

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;

cout<<"\n answer is : "<<result;

cout<<"\n do another : y/n:";

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>

using namespace std;

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);

cout<<"\nenter the number of units consumed:";

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<<"\ntotal units consumed:"<<units;

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>

using namespace std;

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(){

cout<<"\n enter area code,exhange and number:";

cin>>acode>>exhange>>number;

void putdata(){

cout<<"("<<acode<<")"<<exhange<<"-"<<number;

}};

int main(){

phone p1,p2;

p1.initialize();

p2.getdata();

cout<<"\n my number is:";

p1.putdata();

cout<<"\n your number is:";

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>

using namespace std;

double area(double radius) {

return 3.14159 * radius * radius;

double area(int side) {

return side * side;

double area(int length, int width) {

return length * width;

int main() {

double radius;

int side, length, width;

15
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout << "Enter the radius of the circle: ";

cin >> radius;

cout << "Area of the circle: " << area(radius) << endl;

cout << "Enter the side of the square: ";

cin >> side;

cout << "Area of the square: " << area(side) << endl;

cout << "Enter the length and width of the rectangle: ";

cin >> length >> width;

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>

using namespace std;

class DB;

class DM

float meters;

float centimeters;

public:

DM():meters(0),centimeters(0){}

void readDistance(){

cout<<"enter meters and centimeters:";

cin>>meters>>centimeters;

void display()const{

17
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout<<"distance:"<<meters<<"meters,"<<centimeters<<"centimeters";

friend DM addDistance(DM dm,DB db);

};

class DB{

float feet;

float inches;

public:

DB():feet(0),inches(0){}

void readDistance(){

cout<<"enter feet and inches:";

cin>>feet>>inches;

void display()const{

cout<<"distance:"<<feet<<"feet,"<<inches<<"inches";

friend DM addDistance(DM dm,DB db);

};

DM addDistance(DM dm,DB db){

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>

using namespace std;

class TollBooth {

private:

unsigned int totalCars;

double totalCash;

public:

TollBooth() : totalCars(0), totalCash(0.0) {}

void payingCar() {

totalCars++;

totalCash += 0.50;

void nopayCar() {

20
Object Oriented Programming Name: Hemant
Roll No.: 2823298
totalCars++;

void display() const {

cout << "\nTotal cars: " << totalCars << endl;

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;

else if (key == 'P' || key == 'p') {

tollBooth.payingCar();

cout << "Paying car counted.\n";

else if (key == 'N' || key == 'n') {

tollBooth.nopayCar();

cout << "Non-paying car counted.\n";

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>

using namespace std;

class time{

int hours;

int minutes;

public:

void getT(int h,int m){

hours=h;minutes=m;

void putT(void){

cout<<hours<<"hours and";

cout<<minutes<<"minutes"<<"\n";

void sum(time , time);

};

void time::sum(time t1,time t2){

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

a) Name of the patient

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>

using namespace std;

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() {

cout << "Enter patient's name: ";

cin.ignore();

getline(cin, name);

cout << "Enter admission date (year month day): ";

cin >> admissionDate.year >> admissionDate.month >> admissionDate.day;

cout << "Enter disease: ";

cin.ignore();

getline(cin, disease);

cout << "Enter discharge date (year month day): ";

cin >> dischargeDate.year >> dischargeDate.month >> dischargeDate.day;

void displayInfo() const {

cout << "Name: " << name << endl;

cout << "Admission Date: " << admissionDate.year << "-" << admissionDate.month << "-" << admissionDate.day ;

cout << "Disease: " << disease << endl;

cout << "Discharge Date: " << dischargeDate.year << "-" << dischargeDate.month << "-" << dischargeDate.day ;

}};

class PediatricPatient : public Patient {

private:

int age;

public:

void enterInfo() {

Patient::enterInfo();

cout << "Enter age: ";

cin >> age;

25
Object Oriented Programming Name: Hemant
Roll No.: 2823298
}

void displayPediatricInfo() const {

if (age < 12) {

displayInfo();

cout << "Age: " << age ;

cout << "---------------------" ;

}}};

int main() {

const int MAX_PATIENTS = 100;

PediatricPatient patients[MAX_PATIENTS];

int numPatients;

cout << "Enter number of patients: ";

cin >> numPatients;

if (numPatients > MAX_PATIENTS) {

cout << "Number of patients exceeds the maximum limit of " << MAX_PATIENTS << "." ;

numPatients = MAX_PATIENTS;

for (int i = 0; i < numPatients; ++i) {

cout << "\nEntering information for patient " << i + 1 << ":" ;

patients[i].enterInfo();

cout << "\nList of Pediatric Patients (under 12 years):";

for (int i = 0; i < numPatients; ++i) {

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>

using namespace std;

class Employee {

protected:

string name;

double salary;

public:

Employee(const string& name, double salary)

: name(name), salary(salary) {}

string getName() const {


27
Object Oriented Programming Name: Hemant
Roll No.: 2823298
return name;

double getSalary() const {

return salary;

virtual string toString() const {

stringstream ss;

ss << fixed << setprecision(2) << salary;

return "Name: " + name + ", Salary: " + ss.str();

};

class Manager : public Employee {

protected:

string department;

public:

Manager(const string& name, double salary, const string& department)

: Employee(name, salary), department(department) {}

string getDepartment() const {

return department;

string toString() const override {

stringstream ss;

ss << fixed << setprecision(2) << salary;

return "Manager: " + getName() + ", Department: " + department + ", Salary: " + ss.str();

};

class Executive : public Manager {

public:

Executive(const string& name, double salary, const string& department)


28
Object Oriented Programming Name: Hemant
Roll No.: 2823298
: Manager(name, salary, department) {}

string toString() const override {

return "Executive: " + Manager::toString();

};

int main() {

Employee employee("Taniya", 50000);

Manager manager("Rajat", 75000, "Sales");

Executive executive("Vansh", 100000, "Marketing");

cout << employee.toString() << endl;

cout << manager.toString() << endl;

cout << executive.toString() << endl;

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:

a) Accept deposit from a customer and update the balance.

b) Display the balance.

c) Compute and deposit interest.

d) Permit withdrawal and update the balance.

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>

using namespace std;

class Account {

protected:

string customerName;

int accountNumber;

float balance;

string accountType;

public:

void initializeAccount(string name, int accNum, string type, float initialBalance) {

customerName = name;

accountNumber = accNum;

accountType = type;

balance = initialBalance;

void deposit(float amount) {

balance += amount;

cout << "Deposited: " << amount << endl;

cout << "\nUpdated Balance: " << balance ;

void displayBalance() {

cout << "\nBalance for Account " << accountNumber << ": " << balance ;

void withdraw(float amount) {

if (amount <= balance) {

balance -= amount;

cout << "\nWithdrew: " << amount << endl;


31
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout << "\nUpdated Balance: " << balance ;

} else {

cout << "\nInsufficient funds for withdrawal." ;

virtual void applyCharges() = 0;

};

class Cur_Acct : public Account {

private:

float minBalance;

float penaltyCharge;

public:

void initializeCurrentAccount(string name, int accNum, float initialBalance, float minBal, float penalty) {

initializeAccount(name, accNum, "Current", initialBalance);

minBalance = minBal;

penaltyCharge = penalty;

void applyCharges() override {

if (balance < minBalance) {

balance -= penaltyCharge;

cout << "\nBalance below minimum. Penalty charged: " << penaltyCharge ;

cout << "\nUpdated Balance: " << balance ;

} else {

cout << "\nNo penalty. Balance is above minimum." ;

};

class Sav_Acct : public Account {


32
Object Oriented Programming Name: Hemant
Roll No.: 2823298
private:

float interestRate;

public:

void initializeSavingsAccount(string name, int accNum, float initialBalance, float interest) {

initializeAccount(name, accNum, "Savings", initialBalance);

interestRate = interest;

void applyCharges() override {

float interest = (balance * interestRate) / 100;

balance += interest;

cout << "\nInterest added: " << interest << endl;

cout << "\nUpdated Balance: " << balance ;

};

int main() {

Cur_Acct currentAccount;

currentAccount.initializeCurrentAccount("Meenu", 12345, 1000.0f, 500.0f, 50.0f);

currentAccount.deposit(200.0f);

currentAccount.withdraw(300.0f);

currentAccount.applyCharges();

currentAccount.displayBalance();

cout ;

Sav_Acct savingsAccount;

savingsAccount.initializeSavingsAccount("Taniya", 67890, 1000.0f, 5.0f);

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:

• constructor with no arguments (default).

• constructor with two arguments.

• void reduce( ) that reduces the rational number by eliminating the highest common factor between the numerator and
denominator.

• Overload + operator to add two rational number.

• Overload >> operator to enable input through cin.

• Overload << operator to enable output through cout.

Write a main ( ) to test all the functions in the class.

Code:

#include <iostream>

using namespace std;

class Rational {
34
Object Oriented Programming Name: Hemant
Roll No.: 2823298
private:

int numerator;

int denominator;

public:

Rational() : numerator(0), denominator(1) {}

Rational(int num, int denom) : numerator(num), denominator(denom) {

if (denominator == 0) {

cerr << "Error: Denominator cannot be zero. Setting denominator to 1." << endl;

denominator = 1;

reduce();

void reduce() {

int gcd = findGCD(numerator, denominator);

numerator /= gcd;

denominator /= gcd;

int findGCD(int a, int b) {

return b == 0 ? a : findGCD(b, a % b);

Rational operator+(const Rational& other) const {

int num = (numerator * other.denominator) + (other.numerator * denominator);

int denom = denominator * other.denominator;

return Rational(num, denom);

friend istream& operator>>(istream& input, Rational& r) {

cout << "Enter numerator: ";

input >> r.numerator;


35
Object Oriented Programming Name: Hemant
Roll No.: 2823298
cout << "Enter denominator: ";

input >> r.denominator;

if (r.denominator == 0) {

cerr << "Error: Denominator cannot be zero. Setting denominator to 1." << endl;

r.denominator = 1;

r.reduce();

return input;

friend ostream& operator<<(ostream& output, const Rational& r) {

output << r.numerator << "/" << r.denominator;

return output;

};

int main() {

Rational r1, r2;

cout << "Enter first rational number:"l;

cin >> r1;

cout << "Enter second rational number:" ;

cin >> r2;

Rational sum = r1 + r2;

cout << "First rational number: " << r1 ;

cout << "Second rational number: " << r2 ;

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:

• constructor with no arguments (default).

• constructor with two arguments.

• void reduce( ) that reduces the rational number by eliminating the highest common factor between the numerator and
denominator.

• Overload + operator to add two rational number.

• Overload >> operator to enable input through cin.

• Overload << operator to enable output through cout.

Write a main ( ) to test all the functions in the class.

Code:

#include <iostream>

using namespace std;

37
Object Oriented Programming Name: Hemant
Roll No.: 2823298
class Father {

protected:

int age;

public:

Father(int x) {

age = x;

virtual void iam() {

cout << "I AM THE FATHER, my age is: " << age ;

};

class Son : public Father {

public:

Son(int x) : Father(x) {}

void iam() override {

cout << "I AM THE SON, my father's age is: " << age ;

};

class Daughter : public Father {

public:

Daughter(int x) : Father(x) {}

void iam() override {

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>

using namespace std;

class Shape {

protected:

double value1, value2;

public:

void get_data(double v1, double v2) {


40
Object Oriented Programming Name: Hemant
Roll No.: 2823298
value1 = v1;

value2 = v2;

virtual void display_area() {

cout << "Area not defined for this shape." ;

};

class Triangle : public Shape {

public:

void display_area() override {

double area = 0.5 * value1 * value2;

cout << "Area of the Triangle: " << area;

};

class Rectangle : public Shape {

public:

void display_area() override {

double area = value1 * value2;

cout << "Area of the Rectangle: " << area ;

};

int main() {

Shape *shape;

int choice;

cout << "Enter 1 for Triangle or 2 for Rectangle: ";

cin >> choice;

if (choice == 1) {

Triangle triangle;
41
Object Oriented Programming Name: Hemant
Roll No.: 2823298
double base, height;

cout << "Enter base and height of the Triangle: ";

cin >> base >> height;

triangle.get_data(base, height);

shape = &triangle;

else if (choice == 2) {

Rectangle rectangle;

double length, width;

cout << "Enter length and width of the Rectangle: ";

cin >> length >> width;

rectangle.get_data(length, width);

shape = &rectangle;

else {

cout << "Invalid choice!";

return 0;

shape->display_area();

return 0;

Output:

42
Object Oriented Programming Name: Hemant
Roll No.: 2823298

43

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy