0% found this document useful (0 votes)
3 views

OOPS_Lab_Programs_2024-25

Gwiaox d qkxoqp

Uploaded by

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

OOPS_Lab_Programs_2024-25

Gwiaox d qkxoqp

Uploaded by

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

B.M.S.

COLLEGE OF ENGINEERING, BANGALORE-19


(Autonomous Institute, Affiliated to VTU)
Department of Information Science and Engineering
Academic Year: 2024-2025(Odd Sem)

OOPS WITH C++ LAB PROGRAMS

1. Simple Classes and Objects: Create an EMPLOYEE class with following members:
Employee Number, Employee Name, Basic, DA, IT, Net Salary. Member functions: to
read the data, to calculate Net Salary and to print data members. Develop C++
program to demonstrate reading N employees information and compute Net Salary of
each employee. (Consider Dearness Allowance (DA) = 52% of Basic and Income Tax
(IT) = 30% of the gross salary. Net Salary = Basic + DA - IT).

#include<iostream>
using namespace std;

class Employee
{
char emp_name[30];
int emp_number;
float basic, da, it, gross_salary, net_salary;

public:
void read_emp_details(int count)
{
cout<<"\n\n*** Enter Employee "<<count<<" Details ***";
cout<<"\nEmployee Number: ";
cin>>emp_number;
cout<<"Employee Name: ";
cin>>emp_name;
cout<<"Basic Salary: ";
cin>>basic;
cout<<"\n---- Employee "<<count<<" Datails are saved ----\n\n";
}

float find_net_salary()
{
da = basic * 0.52;
gross_salary = basic + da;
it = gross_salary * 0.30;
net_salary = (basic + da) - it;
return net_salary;
}

void display_emp_details(int count)


{
cout<<"\n\n*** Employee "<<count<<" Details ***\n";
cout<<"\nEmployee Number : "<<emp_number;
cout<<"\nEmployee Name : "<<emp_name;
cout<<"\nNet Salary: "<<net_salary;
cout<<"\n--------------------------\n";
}
};

int main()
{
Employee emp[10];
int no_of_emp, i;

cout<<"\nPlease enter the number of Employees (Max.10): ";


cin>>no_of_emp;

for(i=0; i< no_of_emp; i++)


{
emp[i].read_emp_details(i+1);
}

for(i=0; i < no_of_emp; i++)


{
emp[i].find_net_salary();
}

for(i=0; i < no_of_emp; i++)


{
emp[i].display_emp_details(i+1);
}

return 0;
}

2. Array of objects: Develop a C++ program to demonstrate array of objects in class


Student. Create appropriate member variables and functions to read and display
students’ USN and marks of six courses in three tests. Also calculate the average marks
for each course taking best two of three. Test the program for N students.

#include <iostream>
using namespace std;

class Students
{
string usn, name;
int marks[6][3];
float average[6];
public:
void input();
void display();
};

int min(int x, int y, int z)


{
if((x<y) && (x<y))
{
return x;
}
else if((y<x) && (y<z))
{
return y;
}
else
{
return z;
}
}

void Students::input()
{
cout << "USN:";
cin >> usn;

cout << "Name:";


cin >> name;

for(int i=0; i<6; i++)


{
cout << "Enter marks obtained in 3 tests in Subject " << i+1 << ":"<<endl;
cin >> marks[i][0] >> marks[i][1] >> marks[i][2];
int min_marks = min(marks[i][0], marks[i][1], marks[i][2]);
average[i] = float (marks[i][0] + marks[i][1] + marks[i][2] - min_marks)/2;
}
}

void Students::display()
{
cout << usn << "\t" << name << "\t";
for(float i : average) // This is a range-based for loop in C++, which iterates over
//each element i in the average array.
{
cout << i << " ";
}
cout << endl;
}

int main()
{
int n;
cout << "Enter the number of Students:" << endl;
cin >> n;
Students std[n];
for (int i = 0; i < n; i++)
{
cout << "\nEnter the details of Student-" << i+1 << endl;
std[i].input();
}
cout << "\nDetails of Students:" << endl << "USN\tName\tAverage Marks in 6
Subjects" << endl;
for (int i = 0; i < n; i++)
{
std[i].display();
}
}

3. Polymorphism: Develop a C++ program to create a class called COMPLEX with the
following overloading functions ADD that return a COMPLEX number.
i. ADD (a, s2) – where a is an integer (real part) and s2 is a complex number.
ii. ADD (s1, s2) – where s1 and s2 are complex numbers.

#include <iostream>
using namespace std;

class COMPLEX
{
private: int real, imag;

public: void getdata();


void Add(COMPLEX s1, COMPLEX s2);
void Add(int r, COMPLEX s2);
void display(COMPLEX t);
};

void COMPLEX::getdata()
{
cout << "Enter the real part and imaginary part: ";
cin >> real >> imag;
}

void COMPLEX::Add(COMPLEX s1,COMPLEX s2)


{
real = s1.real + s2.real;
imag = s1.imag + s2.imag;
}

void COMPLEX::Add(int r, COMPLEX s2)


{
real = r + s2.real;
imag =s2.imag;
}

void COMPLEX::display(COMPLEX s)
{
cout <<s.real<<"+i"<<s.imag<<endl;
}

int main()
{
COMPLEX s1, s2, s3, s4;
int r;

cout << "Addition of two complex numbers -" << endl;


s1.getdata();
s2.getdata();
s3.Add(s1,s2);

cout << "The resultant complex number is: ";


s3.display(s3);

cout << "Addition of a real number to complex number" << endl;


cout << "Enter the real part: ";
cin >> r;
s4.Add(r, s2);

cout << "The resultant complex number: ";


s4.display(s4);
}

4. Friend function: Create two classes, Class RollsRoyce and Class Lamborghini with
appropriate member variables (Model name, year, price and mileage) and member
functions (read and print). Demonstrate the comparison of two cars w.r.t price and
mileage using friend function.

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

class RollsRoyce; // Forward declaration


class Lamborghini; // Forward declaration

// Friend function declaration


void compareCars(RollsRoyce rr, Lamborghini lambo);

class RollsRoyce
{
private:
string modelName;
int year;
double price;
double mileage;

public:
void read()
{
cout << "Enter RollsRoyce Model Name: ";
cin >> modelName;
cout << "Enter Year: ";
cin >> year;
cout << "Enter Price: ";
cin >> price;
cout << "Enter Mileage: ";
cin >> mileage;
}

void print()
{
cout << "RollsRoyce Model: " << modelName
<< ", Year: " << year
<< ", Price: $" << price
<< ", Mileage: " << mileage << " MPG" << endl;
}
friend void compareCars(RollsRoyce rr, Lamborghini lambo);
};

class Lamborghini
{
private:
string modelName;
int year;
double price;
double mileage;
public:
void read()
{
cout << "Enter Lamborghini Model Name: ";
cin >> modelName;
cout << "Enter Year: ";
cin >> year;
cout << "Enter Price: ";
cin >> price;
cout << "Enter Mileage: ";
cin >> mileage;
}

void print()
{
cout << "Lamborghini Model: " << modelName
<< ", Year: " << year
<< ", Price: $" << price
<< ", Mileage: " << mileage << " MPG" << endl;
}
friend void compareCars(RollsRoyce rr, Lamborghini lambo);
};

void compareCars(RollsRoyce rr, Lamborghini lambo)


{
cout << "Comparing Cars:\n";

if (rr.price < lambo.price)


{
cout << rr.modelName << " is cheaper than " << lambo.modelName << endl;
}
else if (rr.price > lambo.price)
{
cout << rr.modelName << " is more expensive than " << lambo.modelName
<< endl;
}
else
{
cout << rr.modelName << " and " << lambo.modelName << " have the same
price." << endl;
}

if (rr.mileage > lambo.mileage)


{
cout << rr.modelName << " has better mileage than " << lambo.modelName
<< endl;
}
else if (rr.mileage < lambo.mileage)
{
cout << rr.modelName << " has worse mileage than " << lambo.modelName
<< endl;
}
else
{
cout << rr.modelName << " and " << lambo.modelName << " have the same
mileage." << endl;
}
}

int main()
{
RollsRoyce rr;
Lamborghini lambo;

// Read details from the user


rr.read();
lambo.read();

rr.print();
lambo.print();

compareCars(rr, lambo);

return 0;
}

5. Static and non-static members: Create a vehicle having a non-static data member
registration number and a static data member count. Non-static member functions
setregno() and getregno() are used to get and set the registration number. A static
member function getVehiclecount() is used to return the number of vehicles in the
garage. Use a constructor to increment the vehicle count when a vehicle is created and
the destructor to decrement the count when the vehicle is destroyed.
#include <iostream>
using namespace std;

class Vehicle
{
private:
int regNo; // Non-static data member for registration number
static int count; // Static data member to track vehicle count

public:
// Constructor
Vehicle()
{
count++; // Increment count when a vehicle is created
cout<< "Vehicle created." << endl;
}

// Destructor
~Vehicle()
{
count--; // Decrement count when a vehicle is destroyed
cout << "Vehicle with Registration Number " << regNo << "
destroyed." << endl;
}

// Setter for registration number


void setRegNo(int reg)
{
regNo = reg;
}

// Getter for registration number


int getRegNo()
{
return regNo;
}

// Static member function to get the vehicle count


static int getVehicleCount()
{
return count;
}
};

// Initialize static data member


int Vehicle::count = 0;

int main()
{
// Create vehicles
Vehicle v1;
v1.setRegNo(1001);
Vehicle v2;
v2.setRegNo(1002);

cout << "Vehicle 1 Registration Number: " << v1.getRegNo() << endl;
cout << "Vehicle 2 Registration Number: " << v2.getRegNo() << endl;
cout << "Total Vehicles in Garage: " << Vehicle::getVehicleCount() << endl;

{
Vehicle v3;
v3.setRegNo(1003);
cout << "Vehicle 3 Registration Number: " << v3.getRegNo() << endl;
cout << "Total Vehicles in Garage (after v3 created): " <<
Vehicle::getVehicleCount() << endl;
} // v3 goes out of scope and is destroyed here

cout << "Total Vehicles in Garage (after v3 destroyed): " <<


Vehicle::getVehicleCount() << endl;

return 0;
}

6. Operator Overloading: Develop a C++ program to create a class called MATRIX


using a two-dimensional array of integers. Illustrate == operator overloading
which checks the compatibility of two matrices M1 and M2 for addition and
subtraction. Find the sum and difference of matrices by overloading the operators
+ and – respectively. Display the results (sum matrix M3 and difference matrix
M4).

#include<iostream>
using namespace std;

class matrix
{
private:
int m[5][5];
int row;int col;
public:
void getdata();
int operator ==(matrix);
matrix operator+(matrix);
matrix operator-(matrix);
void display();
};

/* function to check whether the order of matrix are same or not */


int matrix::operator==(matrix cm)
{
if(row==cm.row && col==cm.col)
{
return 1;
}
return 0;
}
/* function to read data for matrix*/
void matrix::getdata()
{
cout<<"enter the number of rows\n";
cin>>row;
cout<<"enter the number of columns\n";
cin>>col;
cout<<"enter the elements of the matrix\n";
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>m[i][j];
}
}
}

/* function to add two matrix */


matrix matrix::operator+(matrix am)
{
matrix temp;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
temp.m[i][j]=m[i][j]+am.m[i][j];
}
temp.row=row;
temp.col=col;
}
return temp;
}

/* function to subtract two matrix */


matrix matrix::operator-(matrix sm)
{
matrix temp;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
temp.m[i][j]=m[i][j]-sm.m[i][j];
}
temp.row=row;
temp.col=col;
}
return temp;
}
/* function to display the contents of the matrix */
void matrix:: display()
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<m[i][j];
cout<<" ";
}
cout<<endl;
}
}

int main()
{
matrix m1,m2,m3,m4;
m1.getdata();
m2.getdata();

if(m1==m2)
{
m3=m1+m2;
m4=m1-m2;
cout<<"Addition of matrices\n";
cout<<"the result is\n";
m3.display();
cout<<"subtraction of matrices\n";
cout<<"The result is \n";
m4.display();
}
else
{
cout<<"order of the input matrices is not identical\n";
}
return 0;
}

7. Inheritance and Constructors: Design a class named PersonData with the


following member variables: lastName, firstName, address, city, state and phone.
Write the appropriate constructor, accessor and mutator functions. Next, design
a class named CustomerData, which is derived from the PersonData class. The
CustomerData class has member variables: customerNumber and email id. The
customerNumber variable holds a unique integer for each customer. Write
appropriate constructors, accessor and mutator functions. Demonstrate an object
of the CustomerData class in retrieving individual customer data.

# include <iostream>
# include <string>
using namespace std;
class PersonData
{
private:
string firstName;
string lastName;
string address;
string city;
string state;
int zip;
string phone;
public:
// constructors
PersonData()
{
firstName = "";
lastName = "";
address = "";
city = "";
state = "";
zip = 0;
phone = "";
}

PersonData(string fn, string ln, string add, string c, string s, int z, string
ph)
{
firstName = fn;
lastName = ln;
address = add;
city = c;
state = s;
zip = z;
phone = ph;
}

// mutator functions
void setFirstName(string fn)
{
firstName = fn;
}

void setLastName(string ln)


{
lastName = ln;
}

void setAddress(string add)


{
address = add;
}
void setCity(string c)
{
city = c;
}

void setState(string s)
{
state = s;
}

void setZip(int z)
{
zip = z;
}

void setPhone(string ph)


{
phone = ph;
}

// accessor functions
string getFirstName() const
{
return firstName;
}

string getLastName() const


{
return lastName;
}

string getAddress() const


{
return address;
}

string getCity() const


{
return city;
}

string getState() const


{
return state;
}

int getZip() const


{
return zip;
}
string getPhone() const
{
return phone;
}

// display functions
void displayPersonData() const
{
cout << "First Name:\t\t" << getFirstName() << endl;
cout << "Last Name:\t\t" << getLastName() << endl;
cout << "Address:\t\t" << getAddress() << endl;
cout << "City:\t\t\t" << getCity() << endl;
cout << "State:\t\t\t" << getState() << endl;
cout << "Zip:\t\t\t" << getZip() << endl;
cout << "Phone:\t\t\t" << getPhone() << endl;
}
};

class CustomerData : public PersonData


{
private:
int customerNumber;
string mailid;
public:
// constructors
CustomerData() : PersonData()
{
customerNumber = 0;
mailid="";
}

CustomerData(int num, string emid,string fn, string ln, string add,


string c, string s, int z, string ph) : PersonData(fn, ln, add, c, s, z, ph)
{
customerNumber = num;
mailid=emid;
}

// mutator functions
void setCustomerNumber(int num)
{
customerNumber = num;
}

// accessor functions
int getCustomerNumber() const
{
return customerNumber;
}
void setMailid(string mail)
{
mailid = mail;
}

string getMailid() const


{
return mailid;
}

// display functions
void displayCustomerData() const
{
cout << "Customer Number:\t" << getCustomerNumber() <<
endl;
cout << "Mailid:\t\t" << getMailid() << endl;
displayPersonData();
}
};

int main()
{
CustomerData C1(237,"[email protected]","Santhosh", "Kumar", "31 M.G
Road", "Bengaluru", "Karnataka", 560023, "2563672586");
C1.displayCustomerData();

cout<<"\n\n";

CustomerData C2(240,"[email protected]", "Rakesh", "Kumar", "64 J.C


Road", "Bengaluru", "Karnataka", 560043, "9583467891");
C2.displayCustomerData();

return 0;
}

8. Inheritance: Implement the following relationship using appropriate member


variables and member functions.

Student

Test Sports

Result
#include <iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number= a;
}
void put_number(void)
{
cout << "Roll No: “ << roll_number << "\n";
}
};
class test : public student
{
protected:
float cie1, cie2;
public:
void get_marks (float x, float y)
{
cie1 = x;
cie2 = y;
}

void put_marks (void)


{
cout<<"\nMarks obtained: "<<"\n"
<< "CIE1 = " << cie1 << "\n"
<< "CIE2 = "<< cie2 << "\n";
}
};

class sports
{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}

void put_score (void)


{
cout<<"\nSports Score: " << score << "\n\n";
}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};

void result:: display(void)


{
total = cie1+ cie2 + score;
put_number();
put_marks();
put_score();
cout<<"Total Score: " << total << "\n";
}

int main()
{
result student_1;
student_1.get_number (1234);
student_1.get_marks (27.5, 33.0);
student_1.get_score (6.0);
student_1.display();
return 0;
}

9. Pure Virtual Function: Create a Class Shape with member variables dimension and
member function: getdimenstion() to intialize the member variable and pure virtual
function calculateArea(). Create Square class which inherits the shape class and
calculates the area of square. Create Circle class which inherits the shape class and
calculates the area of circle. Demonstrate runtime polymorphism in the main function
to calculate area of square and circle.
#include <iostream>
using namespace std;

class Shape
{
protected:
double dimension;
public:
void getDimension(double dim)
{
dimension = dim;
}
virtual double calculateArea() = 0;
};

class Square : public Shape


{
public:
double calculateArea()
{
return dimension * dimension;
}
};

class Circle : public Shape


{
public:
double calculateArea()
{
return 3.142 * dimension * dimension;
}
};

int main()
{
Square square;
Circle circle;

square.getDimension(5.0);
cout << "Area of Square: " << square.calculateArea() << endl;

circle.getDimension(3.0);
cout << "Area of Circle: " << circle.calculateArea() << endl;

return 0;
}

10. Templates:
a) Illustrate class templates in a C++ program for the following operations:
Adding two arrays, finding the max and min in an array.
b) Develop a C++ program to sort using bubble sort by applying function
templates.

#include <iostream>
using namespace std;

template <typename T>


class ArrayOp
{
private:
T arr[100];
int size;
public:
ArrayOp(T a[], int Size)
{
size = Size;
for (int i = 0; i < size; i++)
{
arr[i] = a[i];
}
}
ArrayOp<T> add(ArrayOp<T> other)
{
T result[100];
for (int i = 0; i < size; i++)
{
result[i] = arr[i] + other.arr[i];
}
return ArrayOp<T>(result, size);
}

T findMax()
{
T maxVal = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] > maxVal)
{
maxVal = arr[i];
}
}
return maxVal;
}

T findMin()
{
T minVal = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] < minVal)
{
minVal = arr[i];
}
}
return minVal;
}

void display()
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
};

int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {5, 4, 3, 2, 1};
int size = 5;
int size1=5;
ArrayOp<int> ar1(arr1, size);
ArrayOp<int> ar2(arr2, size1);

cout << "Array 1: ";


ar1.display();

cout << "Array 2: ";


ar2.display();

if (size == size1)
{
ArrayOp<int> result = ar1.add(ar2);
cout << "Sum of arrays: ";
result.display();
}
else
{
cout << "Arrays must be of the same size to add." << endl;
}

cout << "Maximum value in Array 1: " << ar1.findMax() << endl;
cout << "Minimum value in Array 1: " << ar1.findMin() << endl;

return 0;
}

// C++ Program to implement Bubble sort using template function

#include <iostream>
using namespace std;

template <typename T>


void bubbleSort(T arr[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
template <typename T>
void displayArray(T arr[], int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}

int main()
{
int intArray[] = {64, 34, 25, 12, 22, 11, 90};
int intSize = sizeof(intArray) / sizeof(intArray[0]);

cout << "Original integer array: ";


displayArray(intArray, intSize);

bubbleSort(intArray, intSize);

cout << "Sorted integer array: ";


displayArray(intArray, intSize);

double doubleArray[] = {64.5, 34.2, 25.7, 12.1, 22.3, 11.8, 90.4};


int doubleSize = sizeof(doubleArray) / sizeof(doubleArray[0]);

cout << "\nOriginal double array: ";


displayArray(doubleArray, doubleSize);

bubbleSort(doubleArray, doubleSize);

cout << "Sorted double array: ";


displayArray(doubleArray, doubleSize);

return 0;
}

You might also like