Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Object oriented Programming (OOPS) practical file

Uploaded by

dinesh720618
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Object oriented Programming (OOPS) practical file

Uploaded by

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

Experiment – 1

Aim : Write a C++ program that performs basic mathema cal opera ons using
a switch statement.

Source code :
#include <iostream>
using namespace std;
int main() {
double num1, num2;
char opera on;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the opera on (+, -, *, /): ";
cin >> opera on;
switch (opera on) {
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;
} else {
cout << "Error: Division by zero is not allowed." << endl; }
break;
default:
cout << "Error: Invalid opera on entered. Please use +, -, *, or /." << endl;

}
return 0;
}

Output:
Experiment – 2a
Aim : Write a program to calculate the power of a number using the standard
power func on

Source code :
#include <iostream>
#include <cmath>
using namespace std;

int main() {
double base, exponent, result;
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;
result = pow(base, exponent);
cout << base << " raised to the power of " << exponent << " is: " << result << endl;
return 0;
}

Output:
Experiment – 2b
Aim : Write a program to calculate the power of a number without using the
standard power func on.

Source code :
#include <iostream>
using namespace std;
int main() {
double base, result = 1;
int exponent;
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;
if (exponent >= 0) {
for (int i = 0; i < exponent; ++i) {
result *= base;}
} else {
for (int i = 0; i < -exponent; ++i) {
result *= base; }
result = 1 / result;
}
cout << base << " raised to the power of " << exponent << " is: " << result << endl;
return 0;
}

Output:
Experiment – 3a
Aim : Write a program to store and display student informa on using a
structure.

Source code :
#include <iostream>
using namespace std;
struct Student {
string name;
int rollNumber;
float marks;
};
int main() {
Student student;
cout << "Enter student name: ";
getline(cin, student.name);
cout << "Enter roll number: ";
cin >> student.rollNumber;
cout << "Enter marks: ";
cin >> student.marks;
cout << "\nStudent Informa on:" << endl;
cout << "Name: " << student.name << endl;
cout << "Roll Number: " << student.rollNumber << endl;
cout << "Marks: " << student.marks << endl;
return 0;
}

Output:
Experiment – 3b
Aim : Write a program to store and display student informa on using a class.
Source code :
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
int rollNumber;
float marks;
public:
void setData(string n, int r, float m) {

name = n;
rollNumber = r;
marks = m;
}
void displayData() {
cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nMarks: " << marks
<< endl;
}
};
int main() {

Student s;
string name;
int rollNumber;
float marks;
cout << "Enter name: ";
getline(cin, name);
cout << "Enter roll number: ";
cin >> rollNumber;
cout << "Enter marks: ";
cin >> marks;
s.setData(name, rollNumber, marks);

s.displayData();
return 0;
}

Output:
Experiment – 4a
Aim : Illustrate the use of a default constructor in C++.
Source code :
#include <iostream>

using namespace std;

class Student {

string name;

int rollNumber;

float marks;

public:

Student() {

name = "Unknown";

rollNumber = 0;

marks = 0.0;

void displayData() {

cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nMarks: " << marks << endl;

};

int main() {

Student s;

s.displayData();

return 0;

Output:
Experiment – 4b
Aim : Illustrate the use of a parameterized constructor in C++.
Source code :
#include <iostream>

using namespace std;

class Student {

string name;

int rollNumber;

float marks;

public:

Student(string n, int r, float m) {

name = n;

rollNumber = r;

marks = m;

void displayData() {

cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nMarks: " << marks << endl;

};

int main() {

Student s("saurabh", 106, 95.5);

s.displayData();

return 0;

Output:
Experiment – 4c
Aim : Illustrate the use of a copy constructor in C++.
Source code :
#include <iostream>

using namespace std;

class Student {

string name;

int rollNumber;

float marks;

public:

Student(string n, int r, float m) {

name = n;

rollNumber = r;

marks = m;

Student(const Student& s) {

name = s.name;

rollNumber = s.rollNumber;

marks = s.marks;

void displayData() {

cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nMarks: " << marks << endl;

};

int main() {

Student s1("Ankit", 110, 88.5);

Student s2 = s1;

s1.displayData();

s2.displayData();
return 0;

Output:
Experiment – 5
Aim : Write a C++ program to demonstrate func on overloading.
Source code :
#include <iostream>

using namespace std;

class Calculator {

public:

int add(int a, int b) {

return a + b;

float add(float a, float b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

};

int main() {

Calculator calc;

cout << "Addi on of two integers: " << calc.add(15, 20) << endl;

cout << "Addi on of two floats: " << calc.add(5.5f, 3.5f) << endl;

cout << "Addi on of three integers: " << calc.add(1, 2, 4) << endl;

return 0;

Output:
Experiment – 6
Aim : Write a C++ program to demonstrate constructor overloading.
Source code :
#include <iostream>

#include <string>

using namespace std;

class Student {

string name;

int rollNumber;

float marks;

public:

Student() {

name = "Unknown";

rollNumber = 0;

marks = 0.0;

Student(string n) {

name = n;

rollNumber = 0;

marks = 0.0;

Student(string n, int r, float m) {

name = n;

rollNumber = r;

marks = m;

void displayData() {

cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nMarks: " << marks << endl;

};
int main() {

Student s1;

Student s2("Vikas");

Student s3("Akshay", 101, 95.5);

s1.displayData();

s2.displayData();

s3.displayData();

return 0;

Output:
Experiment – 7
Aim : Write a program to calculate the area of a square or rectangle using a
class.
Given condi ons: If only the length is provided, the program should calculate the area of a
square; if both length and breadth are provided, it should calculate the area of the rectangle.

Source code :
#include <iostream>

using namespace std;

class Shape {

int length, breadth;

public:

Shape(int l) {

length = l;

breadth = l;

Shape(int l, int b) {

length = l;

breadth = b;

int calculateArea() {

return length * breadth;

};

int main() {

Shape square(5);

Shape rectangle(5, 10);

cout << "Area of the square: " << square.calculateArea() << endl;

cout << "Area of the rectangle: " << rectangle.calculateArea() << endl;

return 0;

}
Output:
Experiment – 8
Aim : Write a program to overload operators (`+`, `-`, `*`, `/`, `+=`) for a class
represen ng complex numbers.

Source code :
#include <iostream>

using namespace std;

class Complex {

double real, imag;

public:

Complex() : real(0), imag(0) {}

Complex(double r, double i) : real(r), imag(i) {}

Complex operator + (const Complex& other) {

return Complex(real + other.real, imag + other.imag);

Complex operator - (const Complex& other) {

return Complex(real - other.real, imag - other.imag);

Complex operator * (const Complex& other) {

return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);

Complex operator / (const Complex& other) {

double denom = other.real * other.real + other.imag * other.imag;

return Complex((real * other.real + imag * other.imag) / denom, (imag * other.real - real *


other.imag) / denom);

}
Complex& operator += (const Complex& other) {

real += other.real;

imag += other.imag;

return *this;

void display() {

if (imag < 0)

cout << real << " - " << -imag << "i" << endl;

else

cout << real << " + " << imag << "i" << endl;

};

int main() {

Complex c1(3, 5), c2(1, 3);

Complex c3 = c1 + c2;

c3.display();

Complex c4 = c1 - c2;

c4.display();

Complex c5 = c1 * c2;

c5.display();

Complex c6 = c1 / c2;

c6.display();

c1 += c2;

c1.display();

return 0;}

Output:
Experiment – 9
Aim : Create a class `Ra onal` that represents a numerical value using a numerator and
denominator. Write a program to overload the `+` and `-` operators for this class.

Source code :
#include <iostream>

using namespace std;

class Ra onal {

int numerator, denominator;

public:

Ra onal() : numerator(0), denominator(1) {}

Ra onal(int num, int denom) : numerator(num), denominator(denom) {

if (denom == 0) {

cout << "Denominator cannot be zero!" << endl;

denominator = 1;

Ra onal operator + (const Ra onal& other) {

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

int denom = denominator * other.denominator;

return Ra onal(num, denom);

Ra onal operator - (const Ra onal& other) {

int num = numerator * other.denominator - other.numerator * denominator;

int denom = denominator * other.denominator;

return Ra onal(num, denom);

}
void display() {

cout << numerator << "/" << denominator << endl;

};

int main() {

Ra onal r1(1, 5), r2(1, 3);

Ra onal r3 = r1 + r2;

r3.display();

Ra onal r4 = r1 - r2;

r4.display();

return 0;

Output:
Experiment – 10
Aim : Write a program to overload operators `+` and `==` for a class represen ng
strings.

Source code :
#include <iostream>

#include <cstring>

using namespace std;

class String {

char* str;

public:

String() : str(nullptr) {}

String(const char* s) {

str = new char[strlen(s) + 1];

strcpy(str, s);

String(const String& other) {

str = new char[strlen(other.str) + 1];

strcpy(str, other.str);

~String() {

delete[] str;

String operator + (const String& other) {

int len = strlen(str) + strlen(other.str) + 1;

char* result = new char[len];

strcpy(result, str);

strcat(result, other.str);

return String(result);

}
bool operator == (const String& other) {

return strcmp(str, other.str) == 0;

void display() const {

cout << str << endl;

};

int main() {

String s1("Hello"), s2("World"), s3("Hello");

String s4 = s1 + s2;

s4.display();

if (s1 == s3)

cout << "s1 and s3 are equal" << endl;

else

cout << "s1 and s3 are not equal" << endl;

return 0;

Output:
Experiment – 11a
Aim : Single level Inheritance (Design a base class Employee with a ributes
name and salary. Derive a class Manager from Employee that adds an a ribute
department (type: string). Provide a toString method in Manager that returns
the manager's name, department, and salary.)

Source code :
#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

double salary;

public:

Employee(string n, double s) : name(n), salary(s) {}

};

class Manager : public Employee {

private:

string department;

public:

Manager(string n, double s, string dept) : Employee(n, s), department(dept) {}

string toString() {

return "Manager Name: " + name + "\nDepartment: " + department + "\nSalary: " +
to_string(salary);

};

int main() {
Manager mgr("Ankit Sharma", 75000.50, "Marke ng");

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

return 0;

Output:
Experiment – 11b
Aim : Mul -level Inheritance (Create a base class Employee with a ributes
name and salary. Derive a class Manager from Employee with an addi onal
department a ribute. Then, create a further derived class Execu ve that
inherits from Manager, overriding the toString method to prepend "Execu ve"
to the informa on provided by Manager's toString.)
Source code :
#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

double salary;

public:

Employee(string n, double s) : name(n), salary(s) {}

virtual ~Employee() {}

};

class Manager : public Employee {

string department;

public:

Manager(string n, double s, string d) : Employee(n, s), department(d) {}

string toString() {

return "Name: " + name + ", Department: " + department + ", Salary: " + to_string(salary);

};

int main() {
Manager mgr("Vikas Yadav", 80000, "IT");

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

return 0;

Output:
Experiment – 11c
Aim : Mul ple Inheritance (Design a class Employee with a ributes name and salary.
Create another class Manager with an a ribute department. Then, create a class Execu ve
that inherits from both Employee and Manager. The Execu ve class should override the
toString method to prepend "Execu ve" to the informa on displayed by combining Employee
and Manager details.)

Source code :
#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

double salary;

public:

Employee(string n, double s) : name(n), salary(s) {}

virtual ~Employee() {}

};

class Manager : public Employee {

protected:

string department;

public:

Manager(string n, double s, string d) : Employee(n, s), department(d) {}

virtual string toString() {

return "Name: " + name + ", Department: " + department + ", Salary: " + to_string(salary);

};
class Execu ve : public Manager {

public:

Execu ve(string n, double s, string d) : Manager(n, s, d) {}

string toString() override {

return "Execu ve " + Manager::toString();

};

int main() {

Execu ve exec("Akshay Sharma", 120000, "HR");

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

return 0;

Output:
Experiment – 12
Aim : Write a program to implement virtual func on.
Source code :
#include <iostream>

#include <cmath>

using namespace std;

class Shape {

public:

virtual double area() {

return 0.0;

};

class Circle : public Shape {

double radius;

public:

Circle(double r) : radius(r) {}

double area() override {

return M_PI * radius * radius;

};

class Rectangle : public Shape {

double length, width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

double area() override {


return length * width;

};

int main() {

Shape* shape1 = new Circle(5);

Shape* shape2 = new Rectangle(4, 6);

cout << "Area of Circle: " << shape1->area() << endl;

cout << "Area of Rectangle: " << shape2->area() << endl;

delete shape1;

delete shape2;

return 0;

Output:
Experiment – 13a
Aim : Create two classes, D1 and D2 which store the value of distances in both
meter and cen meter. Write a program that can read values for the class objects
and add one object of D1 with another object of D2. Use a friend func on to
carry out the addi on opera on.

Source code :
#include <iostream>

using namespace std;

class D2; // Forward declara on of D2 class

class D1 {

int meters;

int cen meters;

public:

D1() : meters(0), cen meters(0) {}

void input() {

cout << "Enter distance for D1 (meters and cen meters): ";

cin >> meters >> cen meters;

friend void addDistances(D1, D2); // Friend func on declara on

};

class D2 {

int meters;

int cen meters;

public:

D2() : meters(0), cen meters(0) {}

void input() {

cout << "Enter distance for D2 (meters and cen meters): ";

cin >> meters >> cen meters;

}
friend void addDistances(D1, D2); // Friend func on declara on

};

void addDistances(D1 d1, D2 d2) {

int totalMeters = d1.meters + d2.meters;

int totalCen meters = d1.cen meters + d2.cen meters;

if (totalCen meters >= 100) {

totalMeters += totalCen meters / 100;

totalCen meters = totalCen meters % 100;

cout << "Total Distance: " << totalMeters << " meters and " << totalCen meters << " cen meters" <<
endl;

int main() {

D1 distance1;

D2 distance2;

distance1.input();

distance2.input();

addDistances(distance1, distance2); // Adding distances using friend func on;

return 0;

Output:
Experiment – 13b
Aim : Create two classes DM and DB which store the value of distances. DM
stores distances in metres and cen meters and DB in feet and inches. Write a
program that can read values for the class objects and add one object of DM
with another object of DB. Use a friend func on to carry out the addi on
opera on. The object that stores the results maybe DM object or DB object.
depending on the units in which the results are required. The display should be
in the format of feet and inches or metres and cen metres depending on object
on display.

Source code :
#include <iostream>

using namespace std;

class DB;

class DM {

int meters;

int cen meters;

public:

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

void input() {

cout << "Enter distance for DM (meters and cen meters): ";

cin >> meters >> cen meters;

friend void addDistances(DM, DB, DM&);

friend void addDistances(DM, DB, DB&);

void display() {

cout << meters << " meters and " << cen meters << " cen meters" << endl;

};
class DB {

int feet;

int inches;

public:

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

void input() {

cout << "Enter distance for DB (feet and inches): ";

cin >> feet >> inches;

friend void addDistances(DM, DB, DM&);

friend void addDistances(DM, DB, DB&);

void display() {

cout << feet << " feet and " << inches << " inches" << endl;

};

void addDistances(DM d1, DB d2, DM &dResult) {

int totalCen meters = d1.meters * 100 + d1.cen meters + d2.feet * 30.48 + d2.inches * 2.54;

dResult.meters = totalCen meters / 100;

dResult.cen meters = totalCen meters % 100;

void addDistances(DM d1, DB d2, DB &dResult) {

int totalInches = d1.meters * 39.37 + d1.cen meters * 0.393701 + d2.feet * 12 + d2.inches;

dResult.feet = totalInches / 12;

dResult.inches = totalInches % 12;

int main() {

DM distance1;

DB distance2;
DM resultDM;

DB resultDB;

distance1.input();

distance2.input();

addDistances(distance1, distance2, resultDM);

cout << "Result in meters and cen meters: ";

resultDM.display();

addDistances(distance1, distance2, resultDB);

cout << "Result in feet and inches: ";

resultDB.display();

return 0;

Output:
Experiment – 14
Aim : Design a class `TollBooth` with the following a ributes and methods: Data
members: `unsigned int` to hold the total number of cars, and `double` to hold
the total amount of money collected. Constructor to ini alize both members to
0. `payingCar()` member func on to increment the car count and add $0.50 to
the total cash. `nopayCar()` member func on to increment only the car count.

Source code :
#include <iostream>

using namespace std;

class TollBooth {

private:

unsigned int carCount;

double totalMoney;

public:

TollBooth() : carCount(0), totalMoney(0.0) {}

void payingCar() {

carCount++;

totalMoney += 0.50;

void nopayCar() {

carCount++;

void display() const {

cout << "Total Cars: " << carCount << endl;

cout << "Total Money Collected: $" << totalMoney << endl;

};
int main() {

TollBooth booth;

booth.payingCar();

booth.payingCar();

booth.nopayCar();

booth.payingCar();

booth.display();

return 0;

Output:
Experiment – 15
Aim : Write a program to create a class template to implement stack opera ons.
Source code :
#include <iostream>

using namespace std;

template <typename T>

class Stack {

T* arr;

int top;

int capacity;

public:

Stack(int size) {

capacity = size;

arr = new T[capacity];

top = -1;

~Stack() {

delete[] arr;

bool isFull() {

return top == capacity - 1;

bool isEmpty() {

return top == -1;

}
void push(T value) {

if (isFull()) {

cout << "Stack overflow!" << endl;

return;

arr[++top] = value;

T pop() {

if (isEmpty()) {

cout << "Stack underflow!" << endl;

return T(); // Return default value of T

return arr[top--];

T peek() {

if (isEmpty()) {

cout << "Stack is empty!" << endl;

return T(); // Return default value of T

return arr[top];

void display() {

if (isEmpty()) {

cout << "Stack is empty!" << endl;

return;

for (int i = top; i >= 0; i--) {


cout << arr[i] << " ";

cout << endl;

};

int main() {

Stack<int> stackInt(5);

stackInt.push(10);

stackInt.push(20);

stackInt.push(30);

stackInt.display();

cout << "Popped value: " << stackInt.pop() << endl;

stackInt.display();

Stack<double> stackDouble(3);

stackDouble.push(1.1);

stackDouble.push(2.2);

stackDouble.push(3.3);

stackDouble.display();

cout << "Popped value: " << stackDouble.pop() << endl;

stackDouble.display();

return 0;

Output:
Experiment – 16
Aim : Write a program to demonstrate excep on handling.
Source code :
#include <iostream>

#include <stdexcept>

using namespace std;

class DivisionByZeroExcep on : public excep on {

public:

const char* what() const noexcept override {

return "Error: Division by zero!";

};

class Nega veValueExcep on : public excep on {

public:

const char* what() const noexcept override {

return "Error: Nega ve values are not allowed!";

};

double divide(int num, int den) {

if (den == 0) {

throw DivisionByZeroExcep on(); // Throw excep on for division by zero

return sta c_cast<double>(num) / den;

void checkValue(int value) {

if (value < 0) {
throw Nega veValueExcep on(); // Throw excep on for nega ve values

int main() {

try {

int num, den;

cout << "Enter numerator: ";

cin >> num;

cout << "Enter denominator: ";

cin >> den;

checkValue(num);

checkValue(den);

double result = divide(num, den);

cout << "Result: " << result << endl;

catch (const DivisionByZeroExcep on& e) {

cout << e.what() << endl;

catch (const Nega veValueExcep on& e) {

cout << e.what() << endl;

catch (const excep on& e) {

cout << "General Error: " << e.what() << endl;

return 0;

}
Output:

You might also like