OOPS Report

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

SIDDAGANGA INSTITUTE OF TECHNOLOGY

(An Autonomous Institution affiliated to Visvesvaraya Technological University, Belagavi, Approved by


AICTE, New Delhi, Accredited by NAAC and ISO 9001:2015 certified)

Object Oriented Programming


with C++ Laboratory Report

Submitted
in partial fulfilment of the requirements of IV semester

Bachelor of Engineering

In
Computer Science & Engineering

By

Dhimanth C 1SI20CS033

Department of Computer Science & Engineering


(Program Accredited by NBA)
Siddaganga Institute of Technology
B.H Road, Tumakuru-572103, Karnataka, India.
Web: www.sit.ac.in
Unit 1

1. Develop a C++ program to overload the function compute( ) to compute


the square root of an integer, square root of a floating point number and
square root of a double number.

Program:
#include <ios>
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;

int compute(int number) {


return sqrt(number);
}

float compute(float number) {


return sqrt(number);
}

double compute(double number) {


return sqrt(number);
}

int main()
{
int i;
float f;
double d;
cout << "Enter an integer: ";
cin >> i;
cout << "Square root of " << i << ": " << compute(i) << endl;
cout << "Enter a floating point number: ";
cin >> f;
cout << "Square root of " << f << ": " << setprecision(7) << compute(f) << endl;
cout << "Enter a double precision floating point number: ";
cin >> d;
cout << "Square root of " << d << ": " << setprecision(15) << compute(d) << endl;
return 0;
}
Output:

2. Define a class NUMBER with integer num as a data member and two
member functions getnum ( ) and product ( ). Use getnum ( ) to read an
integer into an object. Use product ( ) to receive an object as argument and
to compute product of the data stored in two objects and return object.
Develop a C++ program using the class NUMBER to compute the product
of the integers stored in two objects of NUMBER type.

Program:
#include <iostream>
#include <math.h>
using namespace std;

class Number {
int num;
public:
Number() { }

Number(int n) : num(n) { }

void getNum() {
cout << "Enter an integer: ";
cin >> num;
}

int getNumValue() const {


return num;
}

Number product(const Number& n) {


int product = this->num * n.getNumValue();
Number result(product);
return result;
}
};

int main()
{
Number n1, n2;
n1.getNum();
cout << "n1: " << n1.getNumValue() << endl;
n2.getNum();
cout << "n2: " << n2.getNumValue() << endl;
Number n3 = n1.product(n2);
cout << "n3: " << n3.getNumValue() << endl;
return 0;
}

Output:

3. Write a program to demonstrate function overloading to perform area of


geometry object like circle, rectangle and triangle (it should 3 side and find
area) using single function name called AREA ().

Program:
#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;

double area(double r) {
return PI * r * r;
}

double area(double l, double b) {


return l * b;
}

double area(double a, double b, double c) {


double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}

int main() {
double radius, length, breadth, a, b, c;
cout << "Enter the radius of a circle: ";
cin >> radius;
cout << "Area of circle with radius " << radius << ": " << area(radius) << endl;
cout << "Enter the dimensions of a rectangle: ";
cin >> length >> breadth;
cout << "Area of rectangle with length and breadth " << length << " " << breadth <<
": " << area(length, breadth) << endl;
cout << "Enter the sides of a triangle: ";
cin >> a >> b >> c;
cout << "Area of triangle with sides " << a << " " << b << " " << c << ": " << area(a,
b, c) << endl;
return 0;
}

Output:

4. Write a C++ program to define a class called cricket player with data
members player- id, player-name and runs-scored in five matches of a
tournament. Declare an array of 11 player objects. Using appropriate
function find the average runs scored by each player and to display
player_id, player_name and runs_scored by each player.

Program:
#include <iostream>
using namespace std;

class CricketPlayer {
string player_id, player_name;
int runs_scored[5];

public:
void setPlayerInfo() {
cout << "Enter player ID: ";
cin >> player_id;
cout << "Enter player name: ";
cin >> player_name;
cout << "Enter runs scored in past five matches: ";
for (int i = 0; i < 5; i++) {
cin >> runs_scored[i];
}
cout << "Player " << player_name << " successfully added" << endl;
}
void getPlayerInfo() {
cout << "Player name: " << player_name << endl;
cout << "Player ID: " << player_id << endl;
cout << "Player scores: ";
for (int i = 0; i < 5; i++) {
cout << runs_scored[i] << " ";
}
cout << endl;
}

void computeAverage() {
double avg = 0.0;
for (int i = 0; i < 5; i++) {
avg += runs_scored[i];
}
cout << "Average runs scored by player in past five matches: " << avg / 5.0
<< endl;
}
};

int main() {
CricketPlayer c[11];
cout << "Enter details of 11 players: " << endl;
for (int i = 0; i < 11; i++) {
c[i].setPlayerInfo();
}
cout << endl << endl;
cout << "Details of 11 players along with their averages in five matches: " << endl;
for (int i = 0; i < 11; i++) {
c[i].getPlayerInfo();
c[i].computeAverage();
}
return 0;
}
Output:

5. Explain the need of function overloading. Write a C++ program to find


area of a circle (PI*r^2), square (a^2), rectangle (a*b) using concept of
function overloading.

Program:
#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;

double area(double r) {
return PI * r * r;
}

double area(double l, double b) {


return l * b;
}

int main() {
double r, a, l, b;
cout << "Enter the radius of a circle: ";
cin >> r;
cout << "Area of circle with radius " << r << ": " << area(r) << endl;
cout << "Enter the side of a square: ";
cin >> a;
cout << "Area of square with side " << a << ": " << area(a, a) << endl;
cout << "Enter the dimensions of a rectangle: ";
cin >> l >> b;
cout << "Area of rectangle with length and breadth " << l << " " << b << ": " << area(l, b)
<< endl;
return 0;
}
Output:

6. Write a program to find average of best two marks of N students using


object array. Display USN, Name. Mark1, Mark2, Mark3 and average
mark of each student
Program:

#include <iostream>
using namespace std;

class Student {
string name, usn;
int marks1, marks2, marks3;
public:

void setStudentInfo() {
cout << "Enter student name: ";
cin >> name;
cout << "Enter student usn: ";
cin >> usn;
cout << "Enter student marks: ";
cin >> marks1 >> marks2 >> marks3;
cout << "Student " << name << " successfully added" << endl;
}

void getStudentInfo() {
cout << "Student name: " << name << endl;
cout << "Student usn: " << usn << endl;
cout << "Student grades: " << marks1 << " " << marks2 << " " << marks3 <<
endl;
}

void computeAverage() {
float avg = 0.0;
if (marks1 < marks2 && marks1 < marks3) {
avg = (marks2 + marks3) / 2;
} else if (marks2 < marks1 && marks2 < marks3) {
avg = (marks1 + marks3) / 2;
} else {
avg = (marks1 + marks2) / 2;
}
cout << "Average marks obtained: " << avg << endl;
}
};
int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
Student* s = new Student[n];
cout << "Enter details of " << n << " students: " << endl;
for (int i = 0; i < n; i++) {
s[i].setStudentInfo();
}
cout << endl << endl;
cout << "Details of " << n << " students along with their averages: " << endl;
for (int i = 0; i < n; i++) {
s[i].getStudentInfo();
s[i].computeAverage();
}
delete [] s;
return 0;
}
Output:
7. Write a C++ program to read time in HH:MM:SS format and convert
into total seconds. (use the member function gettime() to read time,
convertintoseconds() for conversion of time to seconds and displaytime() to
display time in seconds)

Program:
#include <iostream>
using namespace std;

class Time {
int hours, minutes, seconds, timeInSeconds;

public:
void getTime() {
cout << "Enter hours: ";
cin >> hours;
cout << "Enter minutes: ";
cin >> minutes;
cout << "Enter seconds: ";
cin >> seconds;
}

void convertIntoSeconds() {
timeInSeconds = seconds + (minutes * 60) + (hours * 3600);
}

void displayTime() {
cout << "Time (in seconds): " << timeInSeconds << endl;
}
};

int main() {
Time t;
t.getTime();
t.convertIntoSeconds();
t.displayTime();
return 0;
}
Output:

8. Write a program to read two numbers and swap their contents using
reference variable

Program:

#include <iostream>
using namespace std;

void swapValues(int& x, int& y) {


x ^= y;
y = x ^ y;
x ^= y;
}

void displayValues(int& x, int& y) {


cout << "x = " << x << endl;
cout << "y = " << y << endl;
}

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "Values before swapping: " << endl;
displayValues(num1, num2);
swapValues(num1, num2);
cout << "Values after swapping: " << endl;
displayValues(num1, num2);
return 0;
}

Output:

9. Develop a C++ program to illustrate the use of scope resolution operator


to access global version of a variable.

Program:
#include <iostream>
using namespace std;

int number = 5;

int factorial(int number) {


if (number == 0) {
return 1;
}
return number * factorial(number - 1);
}

int main() {
int number = 10;
cout << "Factorial of global variable number: " << factorial(::number) << endl;
cout << "Factorial of local variable number: " << factorial(number) << endl;
return 0;
}

Output:

10. Write a program to demonstrate default arguments in function


prototyping declaration.

Program:
#include <iostream>
using namespace std;

int main() {
int computeBoxVolume(int length = 1, int breadth = 1, int height = 1);
cout << "The default box volume: " << computeBoxVolume() << endl << endl;
cout << "The volume of the box with length 10, breadth 1 and height 1: " <<
computeBoxVolume(10) << endl << endl;
cout << "The volume of the box with length 10, breadth 5 and height 1: " <<
computeBoxVolume(10, 5) << endl << endl;
cout << "The volume of the box with length 10, breadth 5 and height 2: " <<
computeBoxVolume(10, 5, 2) << endl;
return 0;
}

int computeBoxVolume(int length = 1, int breadth = 1, int height = 1) {


return length * breadth * height;
}

Output:

11. Develop a C++ program by creating an 'Employee' class having the


following functions and print the final salary.
i. 'getInfo()' which takes the ,empname, salary, number of hours of work
per day of employee as parameters
ii. 'AddSal()' which adds Rs.1000 to the salary of the employee if it is less
than Rs.25000.
iii. 'AddWork()' which adds Rs.500 to the salary of the employee if the
number of hours of work per day is more than 6 hours.

Program:
#include <iostream>
using namespace std;

class Employee {
string empname;
double salary;
double nHours;
public:
void getInfo(string empname, double salary, double nHours) {
this->empname = empname;
this->salary = salary;
this->nHours = nHours;
cout << "Employee " << empname << " added" << endl;
}

void addSal() {
if (salary < 25000) {
salary += 1000;
}
}

void addWork() {
if (nHours > 6) {
salary += 500;
}
}

void displaySalary() {
cout << "Employee salary: " << salary << endl;
}
};

int main() {
int n;
cout << "Enter number of employees: ";
cin >> n;
Employee* employees = new Employee[n];
cout << "Enter details of " << n << " employees: " << endl;
for (int i = 0; i < n; i++) {
string empname;
double salary, nHours;
cout << "Enter employee name: ";
cin >> empname;
cout << "Enter employee salary: ";
cin >> salary;
cout << "Enter employee hours of work per day: ";
cin >> nHours;
employees[i].getInfo(empname, salary, nHours);
employees[i].addSal();
employees[i].addWork();
}
cout << "\nFinal salary of " << n << " employees: " << endl;
for (int i = 0; i < n; i++) {
employees[i].displaySalary();
}
delete [] employees;
return 0;
}
Output:

12. Develop a C++ program to create a class FLOWER with following


characteristics: Name, Colour, and Price. A member functions to read data
members and display data members. Method to display the details of all
flower costing more than 50 rupee each.

Program:
#include <iostream>
using namespace std;

class Flower {
string name;
string colour;
double price;
public:
void setFlowerInfo() {
cout << "Enter flower name: ";
cin >> name;
cout << "Enter flower colour: ";
cin >> colour;
cout << "Enter flower price: ";
cin >> price;
cout << "Flower " << name << " added" << endl;
}

void getFlowerInfo() {
cout << "Flower name: " << name << endl;
cout << "Flower colour: " << colour << endl;
cout << "Flower price: " << price << endl;
}

double getPrice() {
return price;
}
};
void displayFlowers(Flower* flowers, int n) {
cout << "\nDetails of flowers costing more than 50 rupees: " << endl;
for (int i = 0; i < n; i++) {
if (flowers[i].getPrice() > 50) {
flowers[i].getFlowerInfo();
}
}
}

int main() {
int n;
cout << "Enter number of flowers: ";
cin >> n;
Flower* flowers = new Flower[n];
cout << "Enter details of " << n << " flowers: " << endl;
for (int i = 0; i < n; i++) {
flowers[i].setFlowerInfo();
}
cout << "\nDetails of " << n << " flowers: " << endl;
for (int i = 0; i < n; i++) {
flowers[i].getFlowerInfo();
}
displayFlowers(flowers, n);
delete [] flowers;
return 0;
}

Output:
13. Define a class called BANK. Include the following data members: i)
Name of the depositor ii) Account number iii) Balance amount in the
account.
With the following member functions:
1. OpenAccount() – It will take input account number, name and opening
balance.
2. ShowAccount() – It will display the account details.
3. Deposit() –The amount to be added in available balance, and deposit the
amount.
4. Withdrawal()- The amount to be withdrawn from the available, will also
check the available balance, if balance is available, it will deduct the
amount from the available balance.

Write a main() to test the program

Program:
#include <iostream>
using namespace std;

class Bank {
string name;
string accountNumber;
double balance;
public:
void openAccount(string name, string accountNumber, double initialBalance) {
this->name = name;
this->accountNumber = accountNumber;
balance = initialBalance;
}

void showAccount() {
cout << "\nAccount details: " << endl;
cout << "Account holder name: " << name << endl;
cout << "Account number: " << accountNumber << endl;
cout << "Account balance: " << balance << endl << endl;
}

void deposit(double amount) {


balance += amount;
cout << "Amount " << amount << " deposited into the account" << endl;
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
cout << "Amount " << amount << " withdrawn from the account" << endl;
} else {
cout << "Insufficient balance" << endl;
}
}
};

int main() {
Bank b;
string name, accountNumber;
double initialBalance = 0;
cout << "Enter account holder name: ";
cin >> name;
cout << "Enter account number: ";
cin >> accountNumber;
cout << "Enter account balance: ";
cin >> initialBalance;
b.openAccount(name, accountNumber, initialBalance);
b.showAccount();
b.deposit(10000);
b.showAccount();
b.withdraw(20000);
b.showAccount();
b.withdraw(5000);
b.showAccount();
}
Output:
14. Develop a C++ program using a member function to get the student
details (rollno, name and marks of five subjects). Introduce a friend
function to calculate and print the percentage of marks.

Program:
#include <iostream>
using namespace std;

class Student {
string name;
string rollNo;
int marks[5];

public:
void setStudentDetails() {
cout << "Enter student name: ";
cin >> name;
cout << "Enter student roll number: ";
cin >> rollNo;
cout << "Enter marks scored in 5 subjects: ";
for (int i = 0; i < 5; i++) {
cin >> marks[i];
}
cout << "Student " << name << " added" << endl;
}

void getStudentDetails() {
cout << "Student name: " << name << endl;
cout << "Student roll number: " << rollNo << endl;
cout << "Marks scored in 5 subjects: ";
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
}

friend void computePercentage(const Student&);

};

void computePercentage(const Student& s) {


double percentage = 0.0;
for (int i = 0; i < 5; i++) {
percentage += s.marks[i];
}
cout << "Student percentage: " << percentage / 5 << endl << endl;
}
int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
Student* students = new Student[n];
cout << "Enter details of " << n << " students: " << endl;
for (int i = 0; i < n; i++) {
students[i].setStudentDetails();
}
cout << "\nDetails of " << n << " students along with their percentage: " << endl;
for (int i = 0; i < n; i++) {
students[i].getStudentDetails();
computePercentage(students[i]);
}
delete [] students;
return 0;
}

Output:

15. Develop a C++ program to illustrate the implementation of static


members function in class.

Program:
#include <iostream>
using namespace std;

class Employee {
string name;
int uniqueId;
static int totalEmployees;

public:
Employee(string name) {
this->name = name;
uniqueId = totalEmployees++;
cout << "Employee " << name << " added" << endl;
}

void printEmployeeDetails() {
cout << "Employee name: " << name << endl;
cout << "Employee unique ID: " << uniqueId << endl << endl;
}

static void displayTotalEmployees() {


cout << "Total employees: " << totalEmployees << endl;
}
};

int Employee::totalEmployees = 0;

int main() {
Employee* e1 = new Employee("empA");
Employee* e2 = new Employee("empB");
cout << endl;
Employee::displayTotalEmployees();
cout << "\nEmployee details: " << endl;
e1->printEmployeeDetails();
e2->printEmployeeDetails();
delete e1;
delete e2;
return 0;
}

Output:
16. Develop a C++ a program using inline function to find the product of
two numbers.

Program:
#include <iostream>
using namespace std;

inline int findProduct(int num1, int num2) {


return num1 * num2;
}

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "Product: " << findProduct(num1, num2);
return 0;
}

Output:
Unit 2

17. Create a class FLOAT that contains one float data member. Overload
all the four arithmetic operators so that they operate on the objects of
FLOAT.

Program:
#include <iostream>
using namespace std;

class Float {
float value;

public:
Float(float v) : value(v) { }

float getValue() const {


return value;
}

Float operator+(const Float& f) {


Float result(value + f.getValue());
return result;
}

Float operator-(const Float& f) {


Float result(value - f.getValue());
return result;
}

Float operator*(const Float& f) {


Float result(value * f.getValue());
return result;
}

Float operator/(const Float& f) {


Float result(value / f.getValue());
return result;
}
};

int main() {
Float f1(10.20);
Float f2(30.40);
Float f3 = f2 + f1;
Float f4 = f2.operator-(f1);
Float f5 = f3 * f4;
Float f6 = f3.operator/(f4);
cout << "Float f1 = " << f1.getValue() << endl;
cout << "Float f2 = " << f2.getValue() << endl;
cout << "Float f3 (f2 + f1) = " << f3.getValue() << endl;
cout << "Float f4 (f2 - f1) = " << f4.getValue() << endl;
cout << "Float f5 (f3 * f4) = " << f5.getValue() << endl;
cout << "Float f6 (f3 / f4) = " << f6.getValue() << endl;
return 0;
}

Output:

18. 19. Design a class Polar which describes a point in the plane using polar
coordinates radius and angle. Use the overloaded + operator to add two
objects of Polar.
Program:
#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;

class Polar {
double radius, angle;

public:
Polar() : radius(0), angle(0) { }

Polar(double r, double a) : radius(r), angle(a) { }

double getR() const { return radius; }

double getA() const { return angle; }

void get_polar() {
cout << "Enter polar coordinates: " << endl;
cout << "Enter radius: ";
cin >> radius;
cout << "Enter angle: ";
cin >> angle;
}

void show_polar() {
cout << "Polar coordinates: " << endl;
cout << "Radius: " << radius << endl;
cout << "Angle: " << angle << endl;
}

Polar operator+(const Polar& p) {


double x1 = radius * cos(PI * angle / 180);
double y1 = radius * sin(PI * angle / 180);
double x2 = p.getR() * cos(PI * p.getA() / 180);
double y2 = p.getR() * sin(PI * p.getA() / 180);
double x = x1 + x2;
double y = y1 + y2;
return Polar(sqrt(x * x + y * y), 180 * atan(y / x) / PI);
}
};

int main() {
Polar p1, p2, p3;
cout << "Enter polar p1: " << endl;
p1.get_polar();
cout << endl << "Enter polar p2: " << endl;
p2.get_polar();
p3 = p1 + p2;
cout << endl << "Polar p3(p1 + p1): " << endl;
p3.show_polar();
return 0;
}

Output:
20. Create a class MAT of size m*n. Define all possible matrix operations
for MAT type objects.

Program:

#include <iostream>
#define MAX 100
using namespace std;

class Matrix {
int grid[MAX][MAX];
int r;
int c;

public:
Matrix() { }

Matrix(int rows, int cols) : r(rows), c(cols) { }

int getR() const { return r; }

int getC() const { return c; }

void setGridData(int i, int j, int data) { grid[i][j] = data; }

void accumulateGridData(int i, int j, int data) { grid[i][j] += data; }

int getGridData(int i, int j) const { return grid[i][j]; }

void readGrid() {
cout << "Enter number of rows and columns: ";
cin >> r >> c;
cout << "Enter " << r * c << " elements into the matrix: " << endl;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> grid[i][j];
}
}
}

void displayGrid() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cout << '\t' << grid[i][j];
}
cout << endl;
}
}

Matrix operator+(const Matrix& m) {


Matrix result(r, c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
result.setGridData(i, j, grid[i][j] + m.getGridData(i, j));
}
}
return result;
}

Matrix operator-(const Matrix& m) {


Matrix result(r, c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
result.setGridData(i, j, grid[i][j] - m.getGridData(i, j));
}
}
return result;
}

Matrix operator*(const Matrix& m) {


Matrix result(r, c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < m.getC() ; j++) {
result.setGridData(i, j, 0);
for (int k = 0; k < m.getR(); k++) {
result.accumulateGridData(i, j, grid[i][k] * m.getGridData(k, j));
}
}
}
return result;
}
};

int main() {
Matrix m1, m2;
cout << "Enter matrix m1: " << endl;
m1.readGrid();
cout << "Enter matrix m2: " << endl;
m2.readGrid();
Matrix m3 = m1 + m2;
Matrix m4 = m1.operator-(m2);
Matrix m5 = m1 * m2;
cout << "Matrix m3 (m1 + m2): " << endl;
m3.displayGrid();
cout << "Matrix m4 (m1 - m2): " << endl;
m4.displayGrid();
cout << "Matrix m5 (m1 * m2): " << endl;
m5.displayGrid();
return 0;
}
Output:

21. Define a class String. Use overloaded == operator to compare two


strings.

Program:
#include <iostream>
#include <string.h>
using namespace std;

class String {
char* data;
int size;

public:
String() : data(NULL), size(0) { }

String(char* data) {
size = strlen(data);
this->data = new char[size + 1];
strcpy(this->data, data);
}

void readData() {
cout << "Enter the size of the string: ";
cin >> size;
data = new char[size + 1];
cout << "Enter the string: ";
cin >> data;
}

char* getData() const { return data; }

void accumulateData(char* data) {


size += strlen(data);
char* tempData = this->data;
this->data = new char[size + 1];
strcpy(this->data, tempData);
strcat(this->data, data);
delete [] tempData;
}

String operator+(const String& s) {


String result(this->data);
result.accumulateData(s.getData());
return result;
}

bool operator==(const String& s) {


return strcmp(data, s.getData()) == 0;
}

~String() {
delete [] data;
}
};

int main() {
String s1, s2, s3("wxyz"), s4("abcd");
cout << "Enter string s1: " << endl;
s1.readData();
cout << "Enter string s2: " << endl;
s2.readData();
cout << "String s1 + s3: " << (s1 + s3).getData() << endl;
cout << "String s4 + s2: " << (s4 + s2).getData() << endl;
if ((s1 + s3) == (s4 + s2)) {
cout << "String s1 + s3 and s4 + s2 are equal" << endl;
} else {
cout << "String s1 + s3 and s4 + s2 are not equal" << endl;
}
return 0;
}
Output:

22. Define two classes POLAR and Rectangle to represent points in the
polar and rectangle systems. Use conversion routines to convert from one
system to the other.
Program:

#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;

class Rectangle {
double x, y;

public:
Rectangle() : x(0), y(0) { }

Rectangle(double a, double b) : x(a), y(b) { }

double getX() const { return x; }

double getY() const { return y; }

void setData() {
cout << "Enter rectangle coordinates: " << endl;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
}

void getData() {
cout << "Rectangle coordinates: " << endl;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}
};

class Polar {
double radius, angle;

public:
Polar() : radius(0), angle(0) { }

Polar(double r, double a) : radius(r), angle(a) { }

// polar(rectangle)
Polar(const Rectangle& r) {
radius = sqrt(r.getX() * r.getX() + r.getY() * r.getY());
angle = atan(r.getY() / r.getX());
angle = (angle * 180) / PI;
}

double getR() { return radius; }

double getA() { return angle; }


void setData() {
cout << "Enter polar coordinates: " << endl;
cout << "Enter radius: ";
cin >> radius;
cout << "Enter angle: ";
cin >> angle;
}

void getData() {
cout << "Polar coordinates: " << endl;
cout << "Radius: " << radius << endl;
cout << "Angle: " << angle << endl;
}

// polar = rectangle
void operator=(const Rectangle& r) {
radius = sqrt(r.getX() * r.getX() + r.getY() * r.getY());
angle = atan(r.getY() / r.getX());
angle = (angle * 180) / PI;
}

// rectangle = polar
operator Rectangle() {
double x, y;
double theta = angle * PI / 180;
x = radius * cos(theta);
y = radius * sin(theta);
return Rectangle(x,y);
}
};

int main() {
Polar p1, p2;
Rectangle r1, r2;
cout << "Enter polar p1: " << endl;
p1.setData();
r1 = p1;
cout << endl << "Rectangle r1(p1): " << endl;
r1.getData();
cout << endl << "Enter rectangle r2: " << endl;
r2.setData();
p2 = r2;
cout << endl << "Polar p1(r2): " << endl;
p2.getData();
return 0;
}

Output:
Unit 3
1. Define a person class with suitable data members and functions. Derive
student and professor classes from person. Create an array of pointer to
person class. Determine whether the person is outstanding. For a student
to be outstanding his/her CGPA > 9.0 and for professor his/her
publications in referred journals must be > 10.

Program

#include <iostream>
#include <vector>
using namespace std;

class Person {
private:
char gender;
int age;
protected:
string name;
public:
virtual void setDetails() {
cout << "Enter name: "; cin >> name;
cout << "Enter gender: "; cin >> gender;
cout << "Enter age: "; cin >> age;
}

virtual void getDetails() {


cout << "Person name: " << name << endl;
cout << "Person gender: " << gender << endl;
cout << "Person age: " << age << endl;
}

virtual void isOutstanding() = 0;


};

class Student : public Person {


char semister;
float cgpa;

public:
void setDetails() {
cout << "Enter student details: " << endl;
Person::setDetails();
cout << "Enter student semister: "; cin >> semister;
cout << "Enter student cgpa: "; cin >> cgpa;
}

void getDetails() {
cout << "Student details: " << endl;
Person::getDetails();
cout << "Student semister: " << semister << endl;
cout << "Student cgpa: " << cgpa << endl;
}

void isOutstanding() {
if (cgpa > 9.0) {
cout << "Person " << name << " is outstanding" << endl;
} else {
cout << "Person " << name << " is not outstanding" << endl;
}
}
};

class Professor : public Person {


vector<string> subjects;
int publications;

public:
void setDetails() {
cout << "Enter professor details: " << endl;
Person::setDetails();
cout << "Enter professor subjects, type \"end\" to terminate: ";
string input;
cin >> input;
while (input != "end") {
subjects.push_back(input);
cin >> input;
}
cout << "Enter professor publications: "; cin >> publications;
}

void getDetails() {
cout << "Professor details: " << endl;
Person::getDetails();
cout << "Professor subjects: ";
for (int i = 0; i < subjects.size(); i++) {
cout << subjects[i] << " ";
}
cout << endl << "Professor publications: " << publications << endl;
}

void isOutstanding() {
if (publications > 10) {
cout << "Person " << name << " is outstanding" << endl;
} else {
cout << "Person " << name << " is not outstanding" << endl;
}
}
};

int main() {
Student s;
Professor p;
Person* pArr[] = {&s, &p};
pArr[0]->setDetails();
cout << endl;
pArr[0]->getDetails();
pArr[0]->isOutstanding();
cout << endl;
pArr[1]->setDetails();
cout << endl;
pArr[1]->getDetails();
pArr[1]->isOutstanding();
return 0;
}

Output:

2. Write a C++ program to show single inheritance which is privately


inherited. Display all the data members of base class and derived class
using derived class object.

Program:
#include <iostream>
#include <vector>
using namespace std;

class Person {
private:
string name;
char gender;
int age;

public:
void setDetails() {
cout << "Enter person name: "; cin >> name;
cout << "Enter person gender: "; cin >> gender;
cout << "Enter person age: "; cin >> age;
}

void getDetails() {
cout << "Person name: " << name << endl;
cout << "Person gender: " << gender << endl;
cout << "Person age: " << age << endl;
}
};

class Employee : private Person {


int salary;
float experience;
vector<string> skills;

public:
void setDetails() {
cout << "Enter employee details: " << endl;
Person::setDetails();
cout << "Enter employee salary: "; cin >> salary;
cout << "Enter employee experience: "; cin >> experience;
cout << "Enter employee skills, type \"end\" to terminate: ";
string input;
cin >> input;
while (input != "end") {
skills.push_back(input);
cin >> input;
}
}

void getDetails() {
cout << "Employee details: " << endl;
Person::getDetails();
cout << "Employee salary: " << salary << endl;
cout << "Employee experience: " << experience << endl;
cout << "Employee skills: ";
for (int i = 0; i < skills.size(); i++) {
cout << skills[i] << " ";
}
cout << endl;
}
};

int main() {
Employee e;
e.setDetails();
cout << endl;
e.getDetails();
return 0;
}

Output:

3. Write a C++ program to create a class to represent entities of type


Circle, specificed by its attribute’s radius and coordinates of its center.
Include appropriate Constructors and display methods. Also write a friend
function that determines whether two circles intersect one another or they
touch each other or they are disjoint.

Program:
#include <iostream>
#include <math.h>
using namespace std;

class Circle {
int radius;
int centerX;
int centerY;

public:
Circle(): radius(0), centerX(0), centerY(0) { }

Circle(int r) : radius(r), centerX(0), centerY(0) { }

Circle(int r, int x, int y) : radius(r), centerX(x), centerY(y) { }

void displayCircle() {
cout << "Circle details: " << endl;
cout << "Circle radius: " << radius << endl;
cout << "Circle center x coordinate: " << centerX << endl;
cout << "Circle center y coordinate: " << centerY << endl;
}

friend void computeType(Circle&, Circle&);


};

void computeType(Circle& a, Circle& b) {


double d = sqrt(pow(a.centerX - b.centerX, 2) + pow(a.centerY - b.centerY, 2));
if (d <= a.radius - b.radius) {
cout << "Circle B is inside A" << endl;
} else if (d <= b.radius - a.radius) {
cout << "Circle A is inside B" << endl;
} else if (d < a.radius + b.radius) {
cout << "Circle A and B intersect to each other" << endl;
} else if (d > a.radius + b.radius) {
cout << "Circle A and B are disjoint" << endl;
} else {
cout << "Circle A and B touch to each other" << endl;
}
}

int main() {
Circle a(30, -10, 8), b(10, 14, -24);
a.displayCircle();
cout << endl;
b.displayCircle();
cout << endl;
computeType(a, b);
return 0;
}

Output:
4. Write a C++ program that stores the time duration in hh:mm:ss format
in a class called Duration having the members’ hh, mm and ss.
Include the following constructors
 zero parameter constructor that sets all data members to zero
 three parameter constructor that sets values of hh, mm and ss
respectively if the values are valid
Implement the following methods
 getDuration method that reads and validates a time duration
 showDuration method that displays the time duration
 addDuration method that adds two durations
Illustrate the addition of two-time durations.
Program:

#include <iostream>
#include <math.h>
using namespace std;

class Duration {
int hh;
int mm;
int ss;

public:
Duration() : hh(0), mm(0), ss(0) { }

Duration(int hh, int mm, int ss) {


this->ss = ss % 60;
this->mm = (mm + (ss / 60)) % 60;
this->hh = hh + (mm + (ss / 60)) / 60;
}

void getDuration() {
int hh, mm, ss;
cout << "Enter hours: "; cin >> hh;
cout << "Enter minutes: "; cin >> mm;
cout << "Enter seconds: "; cin >> ss;
this->ss = ss % 60;
this->mm = (mm + (ss / 60)) % 60;
this->hh = hh + (mm + (ss / 60)) / 60;
}

void showDuration() {
cout << "Duration hours: " << hh << endl;
cout << "Duration minutes: " << mm << endl;
cout << "Duration seconds: " << ss << endl;
}
Duration addDuration(const Duration& d) {
return Duration(hh + d.hh, mm + d.mm, ss + d.ss);
}
};

int main() {
Duration d1, d2(1, 90, 30); // 2.30.30
cout << "Enter d1 duration details: " << endl;
d1.getDuration(); // 2.70.130 --> 3.12.10
cout << endl;
cout << "Duration d1 details: " << endl;
d1.showDuration();
cout << endl;
cout << "Duration d2 details: " << endl;
d2.showDuration();
cout << endl;
Duration d3 = d1.addDuration(d2); // 5.42.40
cout << "Duration d3(d1 + d2) details: " << endl;
d3.showDuration();
return 0;
}

Output:

5. Create a RainGauge class that store rainfallincm information and city


name. Include a zero-parameter constructor. Implement the following
methods: fnReadMeasurement that generates a random decimal value in
the range 0-20cms and reads the name of the city. fnDispReading that
display city name and rainfall received. Write a friend function that takes
an array of RainGauge objects and the number of cities as parameters and
calculates the average rainfall received Create an array of RainGauge
objects in main and display the results.
Program:
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;

class Raingauge {
int rainfall;
string city;

public:
Raingauge() : rainfall(0), city("") { }

void fnReadMeasurement() {
srand(time(0));
rainfall = rand() % 21;
cout << "Enter city name: "; cin >> city;
}

void fnDispReading() {
cout << "Rainfall received: " << rainfall << endl;
cout << "City: " << city << endl;
}

friend float computeAverage(Raingauge* Rarr, int nCities);


};

float computeAverage(Raingauge* Rarr, int nCities) {


float total = 0;
for (int i = 0; i < nCities; i++) {
total += Rarr[i].rainfall;
}
return total / nCities;
}

int main() {
int nCities;
cout << "Enter number of cities: ";
cin >> nCities;
cout << endl;
cout << "Enter measurement details of " << nCities << " cities: " << endl;
Raingauge* Rarr = new Raingauge[nCities];
for (int i = 0; i < nCities; i++) {
Rarr[i].fnReadMeasurement();
}
cout << endl << "Measurement details of " << nCities << " cities: " << endl;
for (int i = 0; i < nCities; i++) {
Rarr[i].fnDispReading();
}
cout << endl << "Average rainfall of " << nCities << " cities: " << computeAverage(Rarr,
nCities);
delete [] Rarr;
return 0;
}
Output:

6. 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. Write a main() program to test the
book and tape classes by creating instances of them, asking the user to fill
in data with getdata(), and then displaying the data with putdata().
Program:
#include <iostream>
using namespace std;

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

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

class Book : public Publication {


int pageCount;

public:
void getdata() {
Publication::getdata();
cout << "Enter book page count: ";
cin >> pageCount;
}

void putdata() {
Publication::putdata();
cout << "Book page count: " << pageCount << endl;
}
};

class Tape : public Publication {


float playingTime;

public:
void getdata() {
Publication::getdata();
cout << "Enter tape playing time: ";
cin >> playingTime;
}

void putdata() {
Publication::putdata();
cout << "Tape playing time: " << playingTime << endl;
}
};

int main() {
Book b;
cout << "Enter book details: " << endl;
b.getdata();
cout << endl;
cout << "Book details: " << endl;
b.putdata();
cout << endl;
Tape t;
cout << "Enter tape details: " << endl;
t.getdata();
cout << endl;
cout << "Tape details: " << endl;
t.putdata();
return 0;
}

Output:

7. Start with the publication, book, and tape classes of Exercise 1. Add a
base class sale that holds an array of three floats so that it can record the
dollar sales of a particular publication for the last three months. Include a
getdata() function to get three sales amounts from the user, and a putdata()
function to display the sales figures. Alter the book and tape classes so they
are derived from both publication and sales. An object of class book or tape
should input and output sales data along with its other data. Write a main()
function to create a book object and a tape object and exercise their
input/output capabilities.

Program:
#include <iostream>
using namespace std;

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

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

class Sale {
float sales[3];

public:
void getdata(void) {
for (int i = 0; i < 3; i++) {
cout << "Enter month " << i + 1 << " sale: $";
cin >> sales[i];
}
}

void putdata(void) {
for (int i = 0; i < 3; i++) {
cout << "Month " << i + 1 << " sale: $" << sales[i] << endl;
}
}
};

class Book : public Publication, public Sale {


int pageCount;

public:
void getdata() {
Publication::getdata();
Sale::getdata();
cout << "Enter book page count: ";
cin >> pageCount;
}

void putdata() {
Publication::putdata();
Sale::putdata();
cout << "Book page count: " << pageCount << endl;
}
};

class Tape : public Publication, public Sale {


float playingTime;

public:
void getdata() {
Publication::getdata();
Sale::getdata();
cout << "Enter tape playing time: ";
cin >> playingTime;
}
void putdata() {
Publication::putdata();
Sale::putdata();
cout << "Tape playing time: " << playingTime << endl;
}
};

int main() {
Book b;
cout << "Enter book details: " << endl;
b.getdata();
cout << endl;
cout << "Book details: " << endl;
b.putdata();
cout << endl;
Tape t;
cout << "Enter tape details: " << endl;
t.getdata();
cout << endl;
cout << "Tape details: " << endl;
t.putdata();
return 0;
}

Output:
8. Assume that the publisher in Exercises 1 and 3 decides to add a third
way to distribute books: on computer disk, for those who like to do their
reading on their laptop. Add a disk class that, like book and tape, is derived
from publication. The disk class should incorporate the same member
functions as the other classes. The data item unique to this class is the disk
type: either CD or DVD. You can use an enum type to store this item. The
user could select the appropriate type by typing c or d.

Program:
#include <iostream>
using namespace std;

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

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

enum diskType { cd, dvd };

class Disk : public Publication {


diskType type;
public:
void getdata() {
char choice;
Publication::getdata();
cout << "Enter disk type (c or d) for CD and DVD: ";
cin >> choice;
type = choice == 'c' ? cd : dvd;
}

void putdata() {
Publication::putdata();
switch(type) {
case cd:
cout << "Disk type: CD" << endl; break;
case dvd:
cout << "Disk type: DVD" << endl; break;
}
}
};

int main() {
Disk d;
cout << "Enter disk details: " << endl;
d.getdata();
cout << endl;
cout << "Disk details: " << endl;
d.putdata();
return 0;
}
Output:

9. Derive a class called employee2 from the employee class in the EMPLOY
program in this chapter. This new class should add a type double data item
called compensation, and also an enum type called period to indicate
whether the employee is paid hourly, weekly, or monthly. For simplicity
you can change the manager, scientist, and laborer classes so they are
derived from employee2 instead of employee. However, note that in many
circumstances it might be more in the spirit of OOP to create a separate
base class called compensation and three new classes manager2, scientist2,
and laborer2, and use multiple inheritance to derive these three classes
from the original manager, scientist, and laborer classes and from
compensation. This way none of the original classes needs to be modified.
Program:
#include <iostream>
#include <math.h>
using namespace std;

class Employee {
string name;
unsigned long ID;

public:
void getdata() {
cout << "Enter employee name: "; cin >> name;
cout << "Enter employee ID: "; cin >> ID;
}

void putdata() {
cout << "Employee name: " << name << endl;
cout << "Employee ID: " << ID << endl;
}
};

enum Paytype { hourly, weekly, monthly };

class Employee2 : public Employee {


double compensation;
Paytype period;

public:
void getdata() {
Employee::getdata();
cout << "Enter employee compensation: $"; cin >> compensation;
char choice;
cout << "Enter employee pay type: "; cin >> choice;
if (choice == 'h') {
period = hourly;
} else if (choice == 'w') {
period = weekly;
} else {
period = monthly;
}
}

void putdata() {
Employee::putdata();
cout << "Employee compensation: $" << compensation << endl;
cout << "Employee pay type: ";
switch (period) {
case hourly: cout << "hourly\n"; break;
case weekly: cout << "weekly\n"; break;
case monthly: cout << "monthly\n"; break;
}
}
};

class Manager : public Employee2 {


string title;

public:
void getdata() {
Employee2::getdata();
cout << "Enter manager title: ";
cin >> title;
}

void putdata() {
Employee2::putdata();
cout << "Manager title: " << title << endl;
}
};

class Scientist : public Employee2 {


int nPublications;

public:
void getdata() {
Employee2::getdata();
cout << "Enter scientist number of publications: ";
cin >> nPublications;
}

void putdata() {
Employee2::putdata();
cout << "Scientist number of publications: " << nPublications << endl;
}
};

class Laborer : public Employee2 {


int nHours;

public:
void getdata() {
Employee2::getdata();
cout << "Enter laborer number of working hours: ";
cin >> nHours;
}

void putdata() {
Employee2::putdata();
cout << "Laborer number of working hours: " << nHours << endl;
}
};

int main() {
Manager m;
cout << "Enter details of a manager: " << endl;
m.getdata();
cout << endl << "Manager details: " << endl;
m.putdata();
Scientist s;
cout << endl << "Enter details of a scientist: " << endl;
s.getdata();
cout << endl << "Scientist details: " << endl;
s.putdata();
Laborer l;
cout << endl << "Enter details of a laborer: " << endl;
l.getdata();
cout << endl << "Laborer details: " << endl;
l.putdata();
return 0;
}

Output:

10. Write a C++ program to compute square and cube of a number using
hierarchical inheritance.

Program:
#include <iostream>
using namespace std;

class Number {
protected:
int n;
public:
void getnum() {
cout << "Enter a number: ";
cin >> n;
}

void display() {
cout << "Number: " << n << endl;
}
};

class Square : public Number {


public:
void display() {
cout << "Square of " << n << ": " << n * n << endl;
}
};

class Cube : public Number {


public:
void display() {
cout << "Cube of " << n << ": " << n * n * n << endl;
}
};

int main() {
Square s;
s.getnum();
s.Number::display();
s.display();
cout << endl;
Cube c;
c.getnum();
c.Number::display();
c.display();
return 0;
}

Output:

You might also like