Oops Lab Programs
Oops Lab Programs
Program:
#include<iostream>
using namespace std;
int main()
{
char a[5]={'A','B','C','D','E'},i,j;
for(i=5;i>=1;i--){
for(j=0;j<i;j++){
cout<<a[j]<<"\t";
}
cout<<"\n";
}
return 0;
}
Result:
Thus, the above C++ program to print the Given pattern has been successfully executed.
B.Write a C++ program to print the Given pattern.
Aim:
To write a C++ program to check if the given number is prime or not.
Algorithm:
1. Start the program.
2. Input a number from the user.
3. Check if the number is less than or equal to 1; if so, it is not prime.
4. For numbers greater than 1, loop through numbers from 2 to the square root of the
number.
5. If the number is divisible by any of these numbers, it is not prime.
6. If no divisors are found, the number is prime.
7. Print whether the number is prime or not.
8. End the program.
Program:
#include <iostream>
using namespace std;
int main() {
int num, primeFlag = 0;
cout << "Enter a positive integer: ";
cin >> num;
if (num <= 1) {
primeFlag = 1;
} else {
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
primeFlag = 1; // If num is divisible by i, it's not prime
break;
}
}
}
if (primeFlag == 0)
cout << num << " is a prime number." << endl;
else
cout << num << " is not a prime number." << endl;
return 0;
}
Output:
Enter a positive integer: 7
7 is a prime number.
Enter a positive integer: 12
12 is not a prime number.
Result:
Thus, the above C++ program to check whether the given number is prime or not has been
successfully executed.
C. Write a C++ program that asks the user to enter a number and prints the multiplication
table of that number from 1 to 10.
Aim:
To write a C++ program that asks the user to enter a number and prints the multiplication
table of that number from 1 to 10.
Algorithm:
1. Start the program.
2. Input a number from the user.
3. Loop from 1 to 10.
4. For each iteration, multiply the number by the loop variable and print the result.
5. End the program.
Program:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Multiplication table of " << num << ":\n";
for (int i = 1; i <= 10; i++) {
cout << num << " x " << i << " = " << num * i << endl;
}
return 0;
}
Output:
Enter a positive integer: 7
7 is a prime number.
Enter a positive integer: 12
12 is not a prime number.
Result:
Thus, the above C++ program for printing the multiplication table of that number from 1 to
10 has been successfully executed.
D. Write a C++ program that asks to enter any number and then prints the multiplication table
of that number from 1 to 10. d. An electricity board charges the following rates to domestic
users to discourage large conceptions of energy. First 100 units Rs 1.50 p/unit From 100 to
200 units Rs 1.80 p/unit Beyond 200 Rs 2.50 p/unit All users are charged a minimum of Rs
50/-. If the total amount is more than 300 then an additional surcharge of 15% of the
calculated amount is added. Write a C++ program to read the name of a user, number of units
consumed and print out the Electricity bill in a neat format. give aim, algorithm, program and
output
Aim:
To write a C++ program to calculate the electricity bill based on the number of units
consumed by the user.
Algorithm:
1. Start the program.
2. Input the user's name and the number of units consumed.
3. If the units are less than or equal to 100, calculate the bill at Rs 1.50 per unit.
4. If the units are between 100 and 200, calculate the first 100 units at Rs 1.50 and the
rest at Rs 1.80 per unit.
5. If the units are greater than 200, calculate the first 100 units at Rs 1.50, the next 100
units at Rs 1.80, and the rest at Rs 2.50 per unit.
6. Apply a minimum bill of Rs 50.
7. If the bill exceeds Rs 300, add a surcharge of 15%.
8. Print the user's name, units consumed, and the total bill in a neat format.
9. End the program.
Program:
#include <iostream>
using namespace std;
int main() {
char userName[50];
float units, billAmount = 0, surcharge = 0;
cout << "Enter the user's name: ";
cin >> userName;
cout << "Enter the number of units consumed: ";
cin >> units;
if (units <= 100) {
billAmount = units * 1.50;
} else if (units <= 200) {
billAmount = 100 * 1.50 + (units - 100) * 1.80;
} else {
billAmount = 100 * 1.50 + 100 * 1.80 + (units - 200) * 2.50;
}
if (billAmount < 50) {
billAmount = 50;
}
if (billAmount > 300) {
surcharge = billAmount * 0.15;
billAmount += surcharge;
}
cout << "\nElectricity Bill" << endl;
cout << "User Name: " << userName << endl;
cout << "Units Consumed: " << units << " units" << endl;
cout << "Total Bill: Rs " << billAmount << endl;
if (surcharge > 0) {
cout << "Surcharge (15%): Rs " << surcharge << endl;
}
return 0;
}
Output:
Enter the user's name: Basharath
Enter the number of units consumed: 250
Electricity Bill
User Name: Basharath
Units Consumed: 250 units
Total Bill: Rs 402.5
Surcharge (15%): Rs 52.5
Result:
Thus, the above C++ program for calculate the electricity bill based on the number of units
consumed by the user has been successfully executed.
EX.NO:2 Programs Using Functions DATE:
A.Write a C++ program to input and output data for finding area of rectangle using functions.
Aim:
To create a C++ program that inputs the length and width of a rectangle and calculates the
area using a function.
Algorithm:
1. Start the program.
2. Declare variables for length, width, and area.
3. Create a function to calculate the area.
4. Input length and width from the user.
5. Call the function to compute the area.
6. Display the area.
7. End the program.
Program:
#include <iostream>
using namespace std;
double calculateArea(double length, double width) {
return length * width;
}
int main() {
double length, width, area;
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "Enter the width of the rectangle: ";
cin >> width;
area = calculateArea(length, width);
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
Output:
Enter the length of the rectangle: 5
Enter the width of the rectangle: 3
The area of the rectangle is: 15
Result:
Thus, the above C++ program for calculating the area of the rectangle using a function has
been successfully executed.
B.Write a C++ program using functions to perform matrix addition & subtraction.
Aim:
To write a C++ program that performs matrix addition and subtraction using functions.
Algorithm:
1. Start the program.
2. Input the dimensions and elements of two matrices.
3. Create functions for matrix addition and subtraction.
4. Perform the operations by calling the respective functions.
5. Display the results.
6. End the program.
Program:
#include <iostream>
using namespace std;
const int MAX = 3;
void addMatrix(int matrix1[MAX][MAX], int matrix2[MAX][MAX], int result[MAX]
[MAX]) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
void subtractMatrix(int matrix1[MAX][MAX], int matrix2[MAX][MAX], int result[MAX]
[MAX]) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
void displayMatrix(int matrix[MAX][MAX]) {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix1[MAX][MAX], matrix2[MAX][MAX], result[MAX][MAX];
cout << "Enter elements of matrix 1 (3x3):" << endl;
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
cin >> matrix1[i][j];
}
}
cout << "Enter elements of matrix 2 (3x3):" << endl;
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
cin >> matrix2[i][j];
}
}
addMatrix(matrix1, matrix2, result);
cout << "Matrix after addition:" << endl;
displayMatrix(result);
subtractMatrix(matrix1, matrix2, result);
cout << "Matrix after subtraction:" << endl;
displayMatrix(result);
return 0;
}
Output:
Enter elements of matrix 1 (3x3):
123
456
789
Enter elements of matrix 2 (3x3):
987
654
321
Matrix after addition:
10 10 10
10 10 10
10 10 10
Matrix after subtraction:
-8 -6 -4
-2 0 2
468
Result:
Thus, the above C++ program for performing matrix addition and subtraction using functions
has been successfully executed.
C.Write a C++ program to swap two integer values using functions with call by value, call by
reference and call by pointers techniques.
Aim:
To swap two integers using different techniques: call by value, call by reference, and call by
pointers.
Algorithm:
1. Start the program.
2. Define functions for call by value, reference, and pointers.
3. Input two integers.
4. Perform swapping using each method and display the results.
5. End the program.
Program:
#include <iostream>
using namespace std;
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "After swapping (Call by Value): a = " << a << ", b = " << b << endl;
}
void swapByReference(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void swapByPointer(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
swapByValue(a, b);
swapByReference(a, b);
cout << "After swapping (Call by Reference): a = " << a << ", b = " << b << endl;
swapByPointer(&a, &b);
cout << "After swapping (Call by Pointer): a = " << a << ", b = " << b << endl;
return 0;
}
Output:
Enter two integers: 5 10
Before swapping: a = 5, b = 10
After swapping (Call by Value): a = 10, b = 5
After swapping (Call by Reference): a = 10, b = 5
After swapping (Call by Pointer): a = 5, b = 10
Result:
Thus, the above C++ program for swapping two integers using different techniques: call by
value, call by reference, and call by pointers has been successfully executed.
D.Write a C++ program to find and print the volume of a cube using inline functions.
Aim:
To .
Algorithm:
1. Start the program.
2. Input the side length of the cube.
3. Define an inline function to calculate the volume.
4. Output the volume.
5. End the program.
Program:
#include <iostream>
using namespace std;
inline double volumeOfCube(double side) {
return side * side * side;
}
int main() {
double side;
cout << "Enter the side length of the cube: ";
cin >> side;
cout << "The volume of the cube is: " << volumeOfCube(side) << endl;
return 0;
}
Output:
Enter the side length of the cube: 4
The volume of the cube is: 64
Result:
Thus, the above C++ program for calculating the volume of a cube using inline functions has
been successfully executed.
EX.NO:3 Program using Classes DATE:
A. Define a class to represent a bank account. Include the following members. Data
Members: Name of depositor, Account number, Type of Account, Balance amount in the
account Member functions : To assign initial values, To deposit an amount, To withdraw
an amount after checking the balance, To display name and balance.
Aim:
To define a class representing a bank account with features to deposit, withdraw, and display
the account balance.
Algorithm:
1. Define the BankAccount class.
2. Include data members: Name, Account number, Type of Account, and Balance.
3. Add member functions to assign values, deposit, withdraw, and display account
details.
4. Use these functions to manipulate the account data and display results.
Program:
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
char depositorName[50];
int accountNumber;
char accountType[50];
float balance;
public:
void initialize(char *name, int accNo, char *accType, float bal) {
depositorName = name;
accountNumber = accNo;
accountType = accType;
balance = bal;
}
void deposit(float amount) {
balance += amount;
cout << "Amount deposited successfully. New balance: " << balance << endl;
}
void withdraw(float amount) {
if (amount > balance) {
cout << "Insufficient balance!" << endl;
} else {
balance -= amount;
cout << "Amount withdrawn successfully. New balance: " << balance << endl;
}
}
void display() {
cout << "Depositor Name: " << depositorName << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Balance: " << balance << endl;
}
};
int main() {
BankAccount account;
char name[50];
int accNo;
char accType[50];
float bal, amount;
int choice;
cout << "Enter depositor name: ";
cin >> name;
cout << "Enter account number: ";
cin >> accNo;
cout << "Enter account type: ";
cin >> accType;
cout << "Enter initial balance: ";
cin >> bal;
account.initialize(name, accNo, accType, bal);
do {
cout << "\nMenu:\n";
cout << "1. Deposit\n";
cout << "2. Withdraw\n";
cout << "3. Display Account Details\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter amount to deposit: ";
cin >> amount;
account.deposit(amount);
break;
case 2:
cout << "Enter amount to withdraw: ";
cin >> amount;
account.withdraw(amount);
break;
case 3:
account.display();
break;
case 4:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 4);
return 0;
}
Output:
Enter depositor name: Basharath
Enter account number: 123456
Enter account type: Savings
Enter initial balance: 5000
Menu:
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 1
Enter amount to deposit: 1000
Amount deposited successfully. New balance: 6000
Menu:
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 2
Enter amount to withdraw: 2000
Amount withdrawn successfully. New balance: 4000
Menu:
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 3
Depositor Name: Basharath
Account Number: 123456
Account Type: Savings
Balance: 4000
Menu:
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 4
Exiting...
Result:
Thus, the above C++ program for representing a bank account with features to deposit,
withdraw, and display the account balance has been successfully executed.
B. Create a class complex with real and imaginary as data members. Also include member
functions to get the values for a complex number, to add two complex number, to
multiply two complex numbers, to print the complex number in a+ib format.
Aim:
To define a class representing a complex number with functions to add and multiply complex
numbers.
Algorithm:
1. Define a Complex class.
2. Include real and imaginary as data members.
3. Add member functions to get values, add, and multiply complex numbers.
4. Display results in a+ib format.
Program:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
void getValues(double r, double i) {
real = r;
imag = i;
}
Complex add(Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
Complex multiply(Complex c) {
Complex temp;
temp.real = (real * c.real) - (imag * c.imag);
temp.imag = (real * c.imag) + (imag * c.real);
return temp;
}
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1, c2, result;
c1.getValues(3, 2);
c2.getValues(1, 4);
result = c1.add(c2);
cout << "Sum of complex numbers: ";
result.print();
result = c1.multiply(c2);
cout << "Product of complex numbers: ";
result.print();
return 0;
}
Output:
Sum of complex numbers: 4 + 6i
Product of complex numbers: -5 + 14i
Result:
Thus, the above C++ program for representing a complex number with functions to add and
multiply complex numbers has been successfully executed.
C. Create a class complex with real and imaginary as data members. Also include member
functions to get the values for a complex number and to print the complex number in a+ib
format. Also include friend functions to add two complex numbers and multiply two
complex numbers.
Aim:
To define a class representing a complex number with friend functions to add and multiply
complex numbers.
Algorithm:
1. Define a Complex class with real and imaginary members.
2. Add friend functions to add and multiply two complex numbers.
3. Display results in a+ib format.
Program:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
void getValues(double r, double i) {
real = r;
imag = i;
}
friend Complex add(Complex c1, Complex c2);
friend Complex multiply(Complex c1, Complex c2);
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
Complex add(Complex c1, Complex c2) {
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
Complex multiply(Complex c1, Complex c2) {
Complex temp;
temp.real = (c1.real * c2.real) - (c1.imag * c2.imag);
temp.imag = (c1.real * c2.imag) + (c1.imag * c2.real);
return temp;
}
int main() {
Complex c1, c2, result;
c1.getValues(3, 2);
c2.getValues(1, 4);
result = add(c1, c2);
cout << "Sum of complex numbers: ";
result.print();
result = multiply(c1, c2);
cout << "Product of complex numbers: ";
result.print();
return 0;
}
Output:
Sum of complex numbers: 4 + 6i
Product of complex numbers: -5 + 14i
Result:
Thus, the above C++ program for representing a complex number with friend functions to
add and multiply complex numbers has been successfully executed.
D. Write a C++ program to implement the stack data structure using classes.
Aim:
To implement the stack data structure using a class in C++.
Algorithm:
1. Define a Stack class with members: array, top, and stack size.
2. Implement functions for push, pop, and display operations.
3. Push elements onto the stack.
4. Pop elements from the stack.
5. Display the stack contents.
Program:
#include <iostream>
using namespace std;
class Stack {
private:
int top;
int arr[5]; // Stack size of 5
public:
Stack() {
top = -1;
}
void push(int value) {
if (top == 4) {
cout << "Stack overflow!" << endl;
} else {
top++;
arr[top] = value;
cout << value << " pushed into the stack." << endl;
}
}
void pop() {
if (top == -1) {
cout << "Stack underflow!" << endl;
} else {
cout << arr[top] << " popped from the stack." << endl;
top--;
}
}
void display() const {
if (top == -1) {
cout << "Stack is empty!" << endl;
} else {
cout << "Stack elements: ";
for (int i = top; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << endl;
}
}
};
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);
s.display();
s.pop();
s.display();
return 0;
}
Output:
10 pushed into the stack.
20 pushed into the stack.
30 pushed into the stack.
Stack elements: 30 20 10
30 popped from the stack.
Stack elements: 20 10
Result:
Thus, the above C++ program for implementing the stack data structure using a class has
been successfully executed.
EX.NO:4 Constructor and Destructor DATE:
A. Create a class called Employee that includes three pieces of information as instance
variables – a first name (type String), a last name (type String) and a monthly salary
(double). Create a constructor in above class to initialize the three instance variables.
Provide a get method for each instance variable. Create two employee objects and display
each object’s yearly salary using display function. Give each employee a 10% raise using
raise_salary function and display each Employee’s yearly salary again.
Aim:
To create a class Employee with instance variables: first name, last name, and monthly salary.
The program initializes these values, calculates and displays the yearly salary, gives a 10%
raise to the employees, and displays the updated salary.
Algorithm:
1. Define a class Employee with private data members: first name, last name, and
monthly salary.
2. Create a constructor to initialize the instance variables.
3. Provide getter methods for each variable.
4. Implement a function displaySalary() to show the employee's yearly salary.
5. Implement a function raiseSalary() to give a 10% raise to the employee.
6. Create two objects of the Employee class and demonstrate salary raise functionality.
Program:
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
char firstName[50];
char lastName[50];
double monthlySalary;
public:
Employee(char *fName, char *lName, double salary) {
firstName = fName;
lastName = lName;
if (salary >= 0)
monthlySalary = salary;
else
monthlySalary = 0;
}
string getFirstName() const {
return firstName;
}
string getLastName() const {
return lastName;
}
double getMonthlySalary() const {
return monthlySalary;
}
void displaySalary() const {
cout << "Yearly Salary of " << firstName << " " << lastName << ": " << (monthlySalary
* 12) << endl;
}
void raiseSalary() {
monthlySalary += monthlySalary * 0.1;
}
};
int main() {
Employee emp1("Basharath", "S", 5000);
Employee emp2("Syed", "Rahaman", 6000);
emp1.displaySalary();
emp2.displaySalary();
emp1.raiseSalary();
emp2.raiseSalary();
cout << "\nAfter 10% raise:\n";
emp1.displaySalary();
emp2.displaySalary();
return 0;
}
Output:
Yearly Salary of Basharath S: 60000
Yearly Salary of Syed Rahaman: 72000
After 10% raise:
Yearly Salary of Basharath S: 66000
Yearly Salary of Syed Rahaman: 79200
Result:
Thus, the above C++ program for creating a class Employee and display each Employee’s
yearly salary with 10% raise has been successfully executed.
B. Write a C++ program to count the number of objects created and destroyed for a class
using stating data members and static member functions.
Aim:
To count the number of objects created and destroyed for a class using static data members
and static member functions.
Algorithm:
1. Define a class ObjectCounter with a static data member objectCount to track the
number of objects created.
2. In the constructor, increment the objectCount each time an object is created.
3. In the destructor, decrement the objectCount when an object is destroyed.
4. Implement a static member function getCount() that returns the current count of
objects.
5. In the main() function, create and destroy objects, and display the object count after
each operation.
Program:
#include <iostream>
using namespace std;
class ObjectCounter {
private:
static int objectCount;
public:
ObjectCounter() {
objectCount++;
cout << "Object created. Current object count: " << objectCount << endl;
}
~ObjectCounter() {
objectCount--;
cout << "Object destroyed. Current object count: " << objectCount << endl;
}
static int getCount() {
return objectCount;
}
};
int ObjectCounter::objectCount = 0;
int main() {
cout << "Creating first object:" << endl;
ObjectCounter obj1;
cout << "\nCreating second object:" << endl;
ObjectCounter obj2;
cout << "\nCurrent object count: " << ObjectCounter::getCount() << endl;
{
cout << "\nCreating objects inside a block:" << endl;
ObjectCounter obj3, obj4;
cout << "Current object count inside block: " << ObjectCounter::getCount() << endl;
}
cout << "\nObject count after block: " << ObjectCounter::getCount() << endl;
return 0;
}
Output:
Creating first object:
Object created. Current object count: 1
Creating second object:
Object created. Current object count: 2
Current object count: 2
Creating objects inside a block:
Object created. Current object count: 3
Object created. Current object count: 4
Current object count inside block: 4
Object destroyed. Current object count: 3
Object destroyed. Current object count: 2
Object count after block: 2
Object destroyed. Current object count: 1
Object destroyed. Current object count: 0
Result:
Thus, the above C++ program counting the number of objects created and destroyed for a
class using static data members and static member functions has been successfully executed.
EX.NO:5 Function Overloading DATE:
A. Write a C++ program to find the area of a square and rectangle using function
overloading.
Aim:
To write a C++ program that calculates the area of a square and a rectangle using function
overloading.
Algorithm:
1. Define a class Shape.
2. Overload the function area() to compute the area of a square and a rectangle.
3. Call the appropriate function based on the number of arguments passed.
Program:
#include <iostream>
using namespace std;
class Shape {
public:
int area(int side) {
return side * side;
}int area(int length, int breadth) {
return length * breadth;
}
};
int main() {
Shape shape;
int side = 5;
int length = 10;
int breadth = 7;
cout << "Area of square: " << shape.area(side) << endl;
cout << "Area of rectangle: " << shape.area(length, breadth) << endl;
return 0;
}
Output:
Result:
Thus, the above C++ program for calculating the area of a square and rectangle using
function overloading has been successfully executed.
B. Write a C++ program to find the volume of a cube, cone and a rectangle using function
overloading.
Aim:
To write a C++ program to find the volume of a cube, cone, and a rectangular prism using
function overloading.
Algorithm:
1. Define a class Volume.
2. Overload the function volume() to compute the volume of a cube, cone, and
rectangular prism.
3. Call the appropriate function based on the number of arguments passed.
Program:
#include <iostream>
#include <cmath>
using namespace std;
class Volume {
public:
int volume(int side) {
return side * side * side;
}
double volume(double radius, double height) {
return (M_PI * radius * radius * height) / 3;
}
int volume(int length, int breadth, int height) {
return length * breadth * height;
}
};
int main() {
Volume vol;
int side = 4;
double radius = 3.0;
double height_cone = 5.0;
int length = 7, breadth = 3, height_prism = 6
cout << "Volume of cube: " << vol.volume(side) << endl;
cout << "Volume of cone: " << vol.volume(radius, height_cone) << endl;
cout << "Volume of rectangular prism: " << vol.volume(length, breadth, height_prism) <<
endl;
return 0;
}
Output:
Result:
Thus, the above C++ program for calculating the volume of a cube, cone, and a rectangular
prism using function overloading has been successfully executed.
C. Write a C++ program to swap two integers, floats, characters and two strings suing
function overloading concept.
Aim:
To write a C++ program that swaps two integers, floats, characters, and two strings using
function overloading.
Algorithm:
1. Define a class Swapper.
2. Overload the function swap() to handle different data types (integers, floats,
characters, and strings).
3. Use the function to swap two values of each type.
Program:
#include <iostream>
#include <string>
using namespace std;
class Swapper {
public:
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void swap(float &a, float &b) {
float temp = a;
a = b;
b = temp;
}
void swap(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}
void swap(char a[], char b[]) {
char temp[50];
temp = a;
a = b;
b = temp;
}
};
int main() {
Swapper swapper;
int int1 = 10, int2 = 20;
float float1 = 3.14f, float2 = 1.59f;
char char1 = 'A', char2 = 'B';
char str1[50] = "Hello", str2[50]= "World";
cout << "Before swapping: " << endl;
cout << "Integers: " << int1 << ", " << int2 << endl;
cout << "Floats: " << float1 << ", " << float2 << endl;
cout << "Characters: " << char1 << ", " << char2 << endl;
cout << "Strings: " << str1 << ", " << str2 << endl;
swapper.swap(int1, int2);
swapper.swap(float1, float2);
swapper.swap(char1, char2);
swapper.swap(str1, str2);
cout << "\nAfter swapping: " << endl;
cout << "Integers: " << int1 << ", " << int2 << endl;
cout << "Floats: " << float1 << ", " << float2 << endl;
cout << "Characters: " << char1 << ", " << char2 << endl;
cout << "Strings: " << str1 << ", " << str2 << endl;
return 0;
}
Output:
Result:
Thus, the above C++ program that swaps two integers, floats, characters, and two strings
using function overloading has been successfully executed.
EX.NO:6 Operator Overloading DATE:
Aim:
To write a C++ program that performs complex number addition, subtraction, and
multiplication using operator overloading with member functions.
Algorithm:
1. Define a Complex class.
2. Overload +, -, and * operators as member functions.
3. Implement these overloaded operators to handle complex number operations.
Program:
#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
// Constructor
Complex(float r = 0, float i = 0) : {
real = r;
imag = i;
}
Complex operator+(const Complex &obj) {
return Complex(real + obj.real, imag + obj.imag);
}
Complex operator-(const Complex &obj) {
return Complex(real - obj.real, imag - obj.imag);
}
Complex operator*(const Complex &obj) {
return Complex((real * obj.real - imag * obj.imag), (real * obj.imag + imag *
obj.real));
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 2), c2(1, 7), result;
result = c1 + c2;
cout << "Addition: ";
result.display();
result = c1 - c2;
cout << "Subtraction: ";
result.display();
result = c1 * c2;
cout << "Multiplication: ";
result.display();
return 0;
}
Output:
Result:
Thus, the above C++ program that performs complex number addition, subtraction, and
multiplication using operator overloading with member functions has been successfully
executed.
Result:
Thus, the above C++ program that performs complex number addition, subtraction, and
multiplication using operator overloading with friend functions has been successfully
executed.
C. Write a C++ program to perform matrix addition, subtraction, multiplication using
operator overloading with friend functions.
Aim:
To write a C++ program that performs matrix addition, subtraction, and multiplication using
operator overloading with friend functions.
Algorithm:
1. Define a Matrix class with a 2D array.
2. Overload +, -, and * operators as friend functions.
3. Implement these overloaded operators to handle matrix operations.
Program:
#include <iostream>
using namespace std;
class Matrix {
private:
int mat[2][2]; // Matrix size fixed at 2x2
public:
Matrix() {}
Matrix(int a[2][2]) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
mat[i][j] = a[i][j];
}
friend Matrix operator+(const Matrix &m1, const Matrix &m2);
friend Matrix operator-(const Matrix &m1, const Matrix &m2);
friend Matrix operator*(const Matrix &m1, const Matrix &m2);
void display() const {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
};
Matrix operator+(const Matrix &m1, const Matrix &m2) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
return res;
}
Matrix operator-(const Matrix &m1, const Matrix &m2) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = m1.mat[i][j] - m2.mat[i][j];
return res;
}
Matrix operator*(const Matrix &m1, const Matrix &m2) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = 0; // Initialize with 0
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
res.mat[i][j] += m1.mat[i][k] * m2.mat[k][j];
return res;
}
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
Matrix m1(a), m2(b), result;
result = m1 + m2;
cout << "Addition of matrices:" << endl;
result.display();
result = m1 - m2;
cout << "\nSubtraction of matrices:" << endl;
result.display();
result = m1 * m2;
cout << "\nMultiplication of matrices:" << endl;
result.display();
return 0;
}
Output:
Result:
Thus, the above C++ program to performs matrix addition, subtraction, and multiplication
using operator overloading with friend functions has been successfully executed.
D. Write a C++ program to perform matrix addition, subtraction, multiplication using
operator overloading with member functions.
Aim:
To write a C++ program that performs matrix addition, subtraction, and multiplication using
operator overloading with member functions.
Algorithm:
1. Define a Matrix class with a 2D array.
2. Overload the operators +, -, and * as member functions for matrix operations.
3. Implement each overloaded operator for matrix addition, subtraction, and
multiplication.
4. Display the result using a display() function.
Program:
#include <iostream>
using namespace std;
class Matrix {
private:
int mat[2][2];
public:
Matrix() {}
Matrix(int a[2][2]) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
mat[i][j] = a[i][j];
}
Matrix operator+(const Matrix &m) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = mat[i][j] + m.mat[i][j];
return res;
}
Matrix operator-(const Matrix &m) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = mat[i][j] - m.mat[i][j];
return res;
}
Matrix operator*(const Matrix &m) {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
res.mat[i][j] = 0;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
res.mat[i][j] += mat[i][k] * m.mat[k][j];
return res;
}
void display() const {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
};
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
Matrix m1(a), m2(b), result;
result = m1 + m2;
cout << "Addition of matrices:" << endl;
result.display();
result = m1 - m2;
cout << "\nSubtraction of matrices:" << endl;
result.display();
result = m1 * m2;
cout << "\nMultiplication of matrices:" << endl;
result.display();
return 0;
}
Output:
Result:
Thus, the above C++ program to performs matrix addition, subtraction, and multiplication
using operator overloading with member functions has been successfully executed.
A. Imagine a publishing company that markets both book and audio-cassette versions of its
work. Create a class publication that stores the title and price. From this class derive two
classes book and tape; book includes one more property: page numbers and tape contains
its length in minutes (float). Each of these classes must have getdata () functions and
putdata () functions to input/output its data. Write a main function to test the book and
tape classes.
Aim:
To create a class hierarchy for a publication company that handles both book and audio-
cassette versions. The base class Publication contains common attributes, while Book and
Tape inherit from Publication and add specific properties.
Algorithm:
1. Create a base class Publication with attributes title and price.
2. Create derived classes Book and Tape.
3. The Book class contains an additional attribute page_count.
4. The Tape class contains an additional attribute play_time.
5. Define getdata() and putdata() functions in each class to handle input/output.
6. In the main() function, test objects of Book and Tape.
Program:
#include <iostream>
#include <string>
using namespace std;
class Publication {
protected:
char title[50];
float price;
public:
void getdata() {
cout << "Enter title: ";
cin >> title;
cout << "Enter price: ";
cin >> price;
}
void putdata() {
cout << "Title: " << title << endl;
cout << "Price: " << price << endl;
}
};
class Book : public Publication {
private:
int page_count;
public:
void getdata() {
Publication::getdata();
cout << "Enter page count: ";
cin >> page_count;
}
void putdata() {
Publication::putdata();
cout << "Page Count: " << page_count << endl;
}
};
class Tape : public Publication {
private:
float play_time;
public:
void getdata() {
Publication::getdata();
cout << "Enter play time (in minutes): ";
cin >> play_time;
}
void putdata() {
Publication::putdata();
cout << "Play Time: " << play_time << " minutes" << endl;
}
};
int main() {
Book b;
Tape t;
cout << "Enter book details:\n";
b.getdata();
cout << "\nEnter tape details:\n";
t.getdata();
cout << "\nBook Details:\n";
b.putdata();
cout << "\nTape Details:\n";
t.putdata();
return 0;
}
Output:
Result:
Thus, the above C++ program to create a class hierarchy for a publication company has been
successfully executed.
B. Create three classes Student, Test and Result classes. The student class contains student
relevant information. Test class contains marks for five subjects. The result class contains
Total and average of the marks obtained in five subjects. Inherit the properties of Student
and Test class details in Result class through multilevel inheritance.
Aim:
To demonstrate multilevel inheritance using Student, Test, and Result classes where a Student
class holds student information, Test holds marks of five subjects, and Result holds the total
and average of marks.
Algorithm:
1. Create a Student class to store student information.
2. Create a Test class that inherits from Student and stores marks of five subjects.
3. Create a Result class that inherits from Test and calculates total and average marks.
4. In the main() function, create an object of Result and call functions to get and display
data.
Program:
#include <iostream>
using namespace std;
class Student {
protected:
char name[50];
int roll_number;
public:
void get_student_data() {
cout << "Enter name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> roll_number;
}
void put_student_data() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << roll_number << endl;
}
};
class Test : public Student {
protected:
float marks[5];
public:
void get_marks() {
cout << "Enter marks for 5 subjects: ";
for(int i = 0; i < 5; i++)
cin >> marks[i];
}
void put_marks() {
cout << "Marks in 5 subjects: ";
for(int i = 0; i < 5; i++)
cout << marks[i] << " ";
cout << endl;
}
};
class Result : public Test {
private:
float total, average;
public:
void calculate_result() {
total = 0;
for(int i = 0; i < 5; i++)
total += marks[i];
average = total / 5;
}
void display_result() {
put_student_data();
put_marks();
cout << "Total Marks: " << total << endl;
cout << "Average Marks: " << average << endl;
}
};
int main() {
Result student;
student.get_student_data();
student.get_marks();
student.calculate_result();
student.display_result();
return 0;
}
Output:
Result:
Thus, the above C++ program To demonstrate multilevel inheritance using student
information has been successfully executed.
C. Create three classes Student, Test and Result classes. The student class contains student
relevant information. Test class contains marks for five subjects. The result class contains
Total and average of the marks obtained in five subjects. Inherit the properties of Student
and Test class details in Result class through multiple inheritance.
Aim:
To create a system where Student contains basic student information, Test contains marks of
five subjects, and Result calculates the total and average marks using multiple inheritance.
Algorithm:
1. Create a Student class that stores student information (name, roll number).
2. Create a Test class that stores marks of five subjects.
3. Create a Result class that inherits from both Student and Test classes.
4. The Result class will calculate the total and average of marks.
5. Implement getdata() and putdata() functions in each class for input and output.
6. In the main() function, create an object of Result and use it to test functionality.
Program:
#include <iostream>
using namespace std;
class Student {
protected:
char name[50];
int roll_number;
public:
void get_student_data() {
cout << "Enter student name: ";
cin >> name;
cout << "Enter roll number: ";
cin >> roll_number;
}
void put_student_data() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << roll_number << endl;
}
};
class Test {
protected:
float marks[5];
public:
void get_marks() {
cout << "Enter marks for 5 subjects: ";
for (int i = 0; i < 5; i++)
cin >> marks[i];
}
void put_marks() {
cout << "Marks: ";
for (int i = 0; i < 5; i++)
cout << marks[i] << " ";
cout << endl;
}
};
class Result : public Student, public Test {
private:
float total, average;
public:
void calculate_result() {
total = 0;
for (int i = 0; i < 5; i++)
total += marks[i];
average = total / 5;
}
void display_result() {
put_student_data();
put_marks();
cout << "Total Marks: " << total << endl;
cout << "Average Marks: " << average << endl;
}
};
int main() {
Result student;
student.get_student_data();
student.get_marks();
student.calculate_result();
student.display_result();
return 0;
}
Output:
Result:
Thus, the above C++ program To demonstrate multiple inheritance using student information
has been successfully executed.
D. Create three classes Employee, Boss and CEO. Employee class stores basic details like,
name, employee no, department, salary. The Boss class contains bonus information and
CEO class contains shares that he owns information. Include AskInfo( ) and writeInfo( )
functions in all the classes. In main create and object for CEO class and call its functions.
Use scope resolution operator in CEO functions to call Employee and Boss functions.
Note : CEO is a boss and boss is an employee.
Aim:
To implement a system with multiple levels of inheritance where the CEO class inherits
from Boss, and Boss inherits from Employee. The CEO class will use scope resolution to
access functions from both Employee and Boss.
Algorithm:
1. Create an Employee class that stores basic employee information (name, employee
number, department, salary).
2. Create a Boss class that inherits from Employee and adds bonus information.
3. Create a CEO class that inherits from Boss and adds share ownership information.
4. Implement AskInfo() and writeInfo() functions in all classes.
5. In the main() function, create a CEO object and call the relevant functions, using the
scope resolution operator to access base class methods.
Program:
#include <iostream>
using namespace std;
class Employee {
protected:
char name[50];
int employee_no;
string department;
float salary;
public:
void AskInfo() {
cout << "Enter employee name: ";
cin >> name;
cout << "Enter employee number: ";
cin >> employee_no;
cout << "Enter department: ";
cin >> department;
cout << "Enter salary: ";
cin >> salary;
}
void writeInfo() {
cout << "Name: " << name << endl;
cout << "Employee No: " << employee_no << endl;
cout << "Department: " << department << endl;
cout << "Salary: $" << salary << endl;
}
};
class Boss : public Employee {
protected:
float bonus;
public:
void AskInfo() {
Employee::AskInfo();
cout << "Enter bonus: ";
cin >> bonus;
}
void writeInfo() {
Employee::writeInfo();
cout << "Bonus: $" << bonus << endl;
}
};
class CEO : public Boss {
private:
int shares;
public:
void AskInfo() {
Boss::AskInfo(); // Call base class function
cout << "Enter number of shares: ";
cin >> shares;
}
void writeInfo() {
Boss::writeInfo(); // Call base class function
cout << "Shares: " << shares << endl;
}
};
int main() {
CEO ceo;
ceo.AskInfo();
cout << "\nCEO Details:\n";
ceo.writeInfo();
return 0;
}
Output:
Result:
Thus, the above C++ program to implement a system with multiple levels of inheritance as
been successfully executed.
EX.NO:8 Polymorphism & Virtual Functions DATE:
A. Create a base class Shape with relevant data members and member functions to get data
and print the area. Create two more classes Rectangle and Triangle which inherit Shape
class. Make the print data function as virtual function in base class. Write a C++ main ()
function to check this.
Aim:
To create a base class Shape with virtual functions to handle polymorphism. Derived classes
Rectangle and Triangle will inherit from Shape and override the area calculation method.
Algorithm:
1. Create a base class Shape with:
Data members for dimensions.
A virtual print_area() function to calculate and display the area.
2. Create derived classes Rectangle and Triangle:
Override the print_area() function to calculate the specific area for each shape.
3. In the main() function, create pointers of type Shape and assign them to objects of
Rectangle and Triangle to demonstrate runtime polymorphism.
4. Use virtual functions to invoke the correct print_area() method based on the object type.
Program:
#include <iostream>
using namespace std;
class Shape {
protected:
float dimension1, dimension2;
public:
void get_data() {
cout << "Enter first dimension: ";
cin >> dimension1;
cout << "Enter second dimension: ";
cin >> dimension2;
}
virtual void print_area() = 0;
};
class Rectangle : public Shape {
public:
void print_area() override {
cout << "Area of Rectangle: " << dimension1 * dimension2 << endl;
}
};
class Triangle : public Shape {
public:
void print_area() override {
cout << "Area of Triangle: " << 0.5 * dimension1 * dimension2 << endl;
}
};
int main() {
Shape* shapePtr;
Rectangle rect;
Triangle tri;
cout << "Enter details for Rectangle:\n";
shapePtr = ▭
shapePtr->get_data();
shapePtr->print_area();
cout << "\nEnter details for Triangle:\n";
shapePtr = &tri;
shapePtr->get_data();
shapePtr->print_area();
return 0;
}
Output:
Result:
Thus, the above C++ program to create two more classes Rectangle and Triangle which
inherit Shape class has been successfully executed.
Result:
Thus, the above C++ program to create a function template that can find the minimum value
from an array has been successfully executed.
B. Write C++ program to design a simple calculator using class and function template
Aim:
To design a simple calculator in C++ using a class and function templates for basic arithmetic
operations (addition, subtraction, multiplication, and division).
Algorithm:
1. Create a class Calculator with a function template calculate().
2. The calculate() function will perform operations based on a specified operator (+, -, *,
/).
3. In the main() function, create an object of the Calculator class and call the template
function to perform calculations on different data types.
Program:
#include <iostream>
using namespace std;
template < class t>
class calculator {
private:
t num1, num2;
public:
calculator(t n1, t n2){
num1=n1;
num2=n2;
}
void display (){
cout<<"Values : "<<num1<<" and "<<num2<<endl;
cout<<num1<<" + "<<num2<<" : "<<add()<<endl;
cout<<num1<<" - "<<num2<<" : "<<sub()<<endl;
cout<<num1<<" * "<<num2<<" : "<<mul()<<endl;
cout<<num1<<" / "<<num2<<" : "<<div()<<endl;
}
t add(){
return num1+num2;
}
t sub(){
return num1-num2;
}
t mul(){
return num1*num2;
}
t div(){
return num1/num2;
}
};
int main(){
calculator<int> ical(5,3);
calculator<float> fcal(5.3,3.4);
ical.display();
fcal.display();
return 0;
}
Output:
Result:
Thus, the above C++ program to design a simple calculator using class template has been
successfully executed.
Result:
Thus, the above C++ program for designing two functions with an exception-specification
has been successfully executed.
B. Write a C++ program to handle divide by zero exception.
Aim:
To handle the divide by zero exception using C++ exception handling.
Algorithm:
1. Create a function for division of two numbers.
2. In the function, check if the denominator is zero.
o If it is, throw an exception.
3. In the main() function:
o Use a try-catch block to call the division function.
o Catch the divide by zero exception and display an appropriate message.
Program:
#include <iostream>
using namespace std;
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero error!";
}
return static_cast<double>(numerator) / denominator;
}
int main() {
int num, denom;
cout << "Enter numerator: ";
cin >> num;
cout << "Enter denominator: ";
cin >> denom;
try {
double result = divide(num, denom);
cout << "Result: " << result << endl;
}
catch (const char* e) {
cout << "Exception caught: " << e << endl;
}
return 0;
}
Output:
Result:
Thus, the above C++ program to handle the divide by zero exception has been successfully
executed.
C. Write a C++ program to handle array out of bound exception.
Aim:
To handle array out-of-bound exceptions using C++ exception handling.
Algorithm:
1. Declare an array and its size.
2. Create a function to access array elements based on an index.
o Throw an exception if the index is out of bounds.
3. In the main() function:
o Use a try-catch block to handle out-of-bound access exceptions.
Program:
#include <iostream>
using namespace std;
void accessArray(int arr[], int size, int index) {
if (index < 0 || index >= size) {
throw "Array index out of bounds!";
}
cout << "Element at index " << index << " is " << arr[index] << endl;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int index;
cout << "Enter the index to access: ";
cin >> index;
try {
accessArray(arr, size, index);
}
catch (const char* e) {
cout << "Exception caught: " << e << endl;
}
return 0;
}
Output:
Result:
Thus, the above C++ program to handle array out-of-bound exceptions has been successfully
executed.
D. Write a C++ program to process memory allocation error using exception handling
mechanism.
Aim:
To handle memory allocation errors using the std::bad_alloc exception handling mechanism
in C++.
Algorithm:
1. Dynamically allocate memory for a large array using new.
2. If memory allocation fails, the bad_alloc exception is thrown automatically.
3. In the main() function:
o Use a try-catch block to handle the bad_alloc exception.
Program:
#include <iostream>
#include <new>
using namespace std;
int main() {
int* largeArray;
try {
largeArray = new int[10000000078060000];
cout << "Memory allocation successful!" << endl;
}
catch (bad_alloc& e) {
cout << "Memory allocation failed: " << e.what() << endl;
}
delete[] largeArray;
return 0;
}
Output:
Result:
Thus, the above C++ program to handle memory allocation errors using the std::bad_alloc
exception handling mechanism has been successfully executed.