1
Program 1) Write a swap function to swap two integer values using pass by reference.
Solution:
/*
Author: Hitender, 231621
*/
#include <iostream>
using namespace std;
/*
Function: swap()
Purpose: To swap two values
Arguments: &a, &b (addresses of a and b to
swap them using pass by reference.)
return type: void
*/
void swap(int &a, int &b);// Function declaration for swap()
int main()
{
int a, b;
cout << "Enter the numbers to swapping: " << endl; cin >> a >> b;
cout << "The values before swap: " <<endl <<
"a = " << a << " and " << "b = " << b << endl;
swap(a, b); // swap function call
cout << "The values after swapping: " <<endl <<
"a = " << a << " and " << "b = " << b << endl;
return 0;
}
void swap(int &a, int &b) //swap() function definition
{
int temp;
temp = a;
a = b;
b = temp;
}
2
Output:
3
Program 2) Create a time class where users may give hours, minutes and
seconds or only minutes at runtime. Provide the required constructor to
support both types of inputs.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream>
using namespace std;
/*
Class name: Time
Purpose: To display time using 2 types of parameterized constructors
Member data: int hours (to display hours),
int minutes (to display minutes),
int seconds (to display seconds)
Functions:
Constructor1:
Takes hours, minutes & seconds as input and initializes the member data.
Constructor2:
Takes minutes as input & initializes member data after some calculations.
time_display():
Return type: void (as it just displays)
Purpose: To display the time.
*/
class Time
{
private:
int hours, minutes, seconds;
public:
// Default Constructor
Time(){};
// Constructor that takes hours, minutes and seconds as input.
/*
Function Name: Constructor 1
Purpose: Constructor to initialize time using hours, minutes, and seconds
Arg1: h, type: int, Purpose: Hours
Arg2: m, type: int, Purpose: Minutes Arg3: s, type: int, Purpose:
Seconds Return: N/A
*/
Time(int h, int m, int s)
{
hours = h;
minutes = m;
seconds = s;
}
// Constructor that takes only minutes as input
/*
Function Name: Time
Purpose: Constructor to initialize time using only minutes.
Arg1: m, type: int, Purpose: Minutes
return: N/A
*/
Time(int m)
{
hours = m / 60;
minutes = m % 60;
seconds = 0;
}
/*
4
Function Name: display_Time
Purpose: Displays the time in hh:mm:ss format
Args: void
return: void
*/
void time_display()
{
cout << "Time: " << hours << " hours: " << minutes << " minutes: " <<
seconds << " seconds" << endl;
}
};
int main() {
// Using first constructor
Time t1(2, 30, 45);// hrs, mins, sec given. t1.time_display();
// Using second constructor
Time t2(125); // only minutes given. t2.time_display();
return 0;
}
Output:
5
Program 3) Demonstrate shallow copy and deep copy.
Solution:
/*
Author: Hitender(231621)
*/
#include <iostream> using
namespace std;
/*
class name: Shallow
Purpose: to demonstrate Shallow copy
Member data: *data(pointer to int data type)
Functions:
Constructor: To allocate new memory
display_shallow(): void type
:To dislay the shallow copied objects
Destructor: To free the shared memory
Imp: The normal constructor creates Shallow copies of objects.
*/
class Shallow
{
public:
int *data; public:
Shallow(int d) //Constructor
{
data = new int(d); // allocate memory
}
void display_shallow()
{
cout << "Value: " << *data << endl;
}
~Shallow() //Destructor
{
delete data; // deletes shared memory
}
};
/*
class name: Deep
Purpose: to demonstrate Deep copy
Member data: *data(pointer to int data type)
Functions:
Constructor: To allocate new memory
Copy Constructor: To create Deep copy of object.
display_deep(): void type
:To display the deep copied objects Destructor: To free the
memory
Imp: Syntax to create Deep copies: ClassName(const classname
&old_object);
*/
class Deep
{
public:
int *value; public:
Deep(int val) //Constructor
{
value = new int(val);
}
// Deep copy constructor
Deep(const Deep &d)
{
6
value = new int(*d.value); // copy actual value
}
void display_deep()
{
cout << "Value: " << *value << endl;
}
~Deep() //Destructor
{
delete value;
}
};
int main()
{
Shallow obj1(10);
Shallow obj2 = obj1; // shallow copy
*obj2.data = 20; // changing obj2 also affects obj1
obj1.display_shallow(); // Output: 20
obj2.display_shallow(); // Output: 20
Deep object1(10);
Deep object2 = object1;// deep copy (copy initialization)
*object2.value = 20; // changes object2 only
object1.display_deep(); // Output: 10
object2.display_deep(); // Output: 20
return 0;
}
Output:
7
Program 4) Create a Class Shape and multiple constructor to calculate the areas of
different shapes.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream>
using namespace std;
/*
class_name: Shape
Purpose: To demonstrate constructor overloading by calculating area
for different shapes.
Member data: float type area
Functions:
Default constructor: In absence of any parameter
Constructor1: To calculate area for circle
Arguments: float radius
Constructor2: To calculate area for rectangle
Arguments: int length, int breadth
Constructor3: To calculate area for square
Arguments: int side
display_area: to display the area calculated.
` return type: void
*/
class Shape
{
Public:
float area; public:
//Default constructor.
Shape(){};
// Constructor for Circle
/*
Function Name: Shape (Constructor 1)
Purpose: Constructor to calculate area of a circle
Arg1: radius, type: float,
Purpose: Radius of circle
return: N/A
*/
Shape(float radius)
{
area = 3.14 * radius * radius;
}
// Constructor for Rectangle
/*
Function Name: Shape
Purpose: Constructor to calculate area of a rectangle
Arg1: length, type: double, Purpose: Length of the
rectangle
Arg2: breadth, type: double, Purpose: Breadth of the rectangle
Return: N/A
*/
Shape(float length, float breadth)
{
area = length * breadth;
}
// Constructor for Square (int to differentiate)
/*
Function Name: Shape
Purpose: Constructor to calculate area of a rectangle
Arg1: side, type: int, Purpose: side of square
Return: N/A
8
*/
Shape(int side)
{
area = side * side;
}
/*
Function Name: display_area()
Purpose: Displays the calculated area.
Arg1: void
Return: void
*/
void display_area()
{
cout<<"Area of shape with provided dimensions is: "<<
area<<endl;
}
};
int main()
{
// Circle
Shape circle(5.0f); circle.display_area();
// Rectangle
Shape rectangle(4, 6); rectangle.display_area();
// Square
Shape square(4); square.display_area();
return 0;
}
Output:
9
Program 5) Create a Timekeeper class that simulates a clock. The
clock should be able to:
Set the current time (Hours and minutes),
Increment the time by a specified number of minutes,
Display the time in a 12-hours format.
Solution:
/*
Author: Hitender(231621)
*/
#include <iostream>
using namespace std;
/*
class_name: Timekeeper
Purpose:
To set time of a clock
To increment minutes
To display the time in 12 hrs format
Member data: int hrs, int min
Functions:
setTime: return type: void
Arguments: hour, minutes
Purpose: To set the time.
increment: return type: void
arguments: int minutes
purpose: To increment minutes in time
display_time(): return type: void
arguments: void
purpose: To display the time.
*/
class Timekeeper
{
public:
int hrs, min; public:
// Default constructor
Timekeeper() {};
/*
Function Name: setTime
Purpose: Sets the current time (hours and minutes)
Arg1: hour, type: int,
Purpose: Hours to set the clock
Arg2: minutes, type: int,
Purpose: Minutes to set the clock
Return: void
*/
void setTime(int hour, int minutes)
{
hrs = hour;
min = minutes;
}
/*
Function Name: increment()
Purpose: Increments the current time by a specified number
of minutes
Arg1: minutes, type: int,
Purpose: Number of minutes to increment the time by.
Return: void
*/
void increment(int minutes)
{
min += minutes; hrs
1
0
+= min / 60; min = min
% 60; hrs = hrs % 12;
}
/*
Function Name: display_time
Purpose: Displays the current time in 12 hours
Arg1: None
Return: void
*/
void display_time()
{
cout << "Time: " << hrs << ":" << (min < 10 ? "0" : "") << min <<
endl;
}
};
int main()
{
Timekeeper t;
t.setTime(10, 15);
t.display_time(); t.increment(80);
t.display_time();
return 0;
}
Output:
11
Program 6) Write a program a string concatenation using operator overloading.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream>
using namespace std;
/*
Class: Concat
Purpose: To demonstrate string concatenation using operator overloading.
Data Members: str (string type) - stores the string value
Member Functions:
Concat(string s) - constructor to initialize the string.
operator + (Concat c): overloaded '+' operator to concatenate two Concat object
display() - displays the concatenated string
*/
class Concat
{
public:
string str; // Data member to store the string
public:
/*
Function Name: Concat
Purpose: Constructor to initialize the string
Arg1: s, type: string,
Purpose: String to initialize the object
Return: N/A
*/
Concat(string s)
{
str = s;
}
/*
Function Name: operator+
Purpose: Overloads the + operator to concatenate two strings.
Arg1: c, type: Concat&,
Purpose: The second string object to concatenate
Return: Concat (result of concatenation)
*/
Concat operator + (Concat& c)
{
return Concat(str + c.str);
}
/*
Function Name: display
Purpose: Displays the stored string Arg1: None
Return: void
*/
void display()
{
cout << str << endl;
}
};
int main()
{
12
Concat a("Hello "); // Creating first object with "Hello "
Concat b("World!"); // Creating second object
with “World”.
Concat c = a + b; // Using overloaded '+' operator
to concatenate a and b.
c.display(); // Displaying the concatenated result
return 0;
}
Output:
13
Program 7) Create two Classes for 12-hours and 24-hours Time format.
Convert one time object to another.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream> using
namespace std;
/*
Class Name: Time12
Purpose: To represent time in 12-hour format and convert it to 24-hour format
Function Name: display_12, Return Type: void
Function Name: to24Hour, Return Type: void
*/
class Time12
{
private:
int hours; int
minutes;
string period; public:
/*
Function Name: Time12
Purpose: Constructor to initialize the time in 12-hour format
Arg1: h, type: int,
Purpose: Hours in 12-hour format
Arg2: m, type: int,
Purpose: Minutes in 12-hour format
Arg3: p, type: string, Purpose: Period (AM/PM)
Return: N/A
*/
Time12(int h, int m, string p) {
hours = h;
minutes = m;
period = p;
}
/*
Function Name: display
Purpose: Displays the time in 12-hour format
Arg1: None
Return: void
*/
void display_12() {
cout << "Time (12-hour format): " << hours << ":" << minutes << " "
<< period << endl;
}
/*
Function Name: to24Hour
Purpose: Converts the 12-hour format time to 24-hour format
Arg1: None Return:
void
*/
void to24Hour()
{
int hour24 = hours;
if (period == "PM" && hours != 12)
{
hour24 += 12;
}
else if (period == "AM" && hours == 12)
14
{
hour24 = 0;
}
cout << "Converted Time (24-hour format): " << hour24
<< ":" << minutes << endl;
}
};
/*
Class Name: Time24
Purpose: To represent time in 24-hour format and convert it to 12-hour format.
Function Name: display, Return Type: void
Function Name: to12Hour, Return Type: void
*/
class Time24 {
private:
int hours;
int minutes;
public:
/*
Function Name: Time24
Purpose: Constructor to initialize the time in 24-hour format
Arg1: h, type: int, Purpose: Hours in 24-hour format
Arg2: m, type: int, Purpose: Minutes in 24-hour format
Return: N/A
*/
Time24(int h, int m)
{
hours = h;
minutes = m;
}
/*
Function Name: display
Purpose: Displays the time in 24-hour format
Arg1: None
Return: void
*/
void display_24()
{
cout << "Time (24-hour format): " << hours << ":" << minutes <<
endl;
}
/*
Function Name: to12Hour
Purpose: Converts the 24-hour format time to 12-hour format
Arg1: None
Return: void
*/
void to12Hour(){
int hour12 = hours;
string period = "AM";
if (hours >= 12)
{
period = "PM";
if (hours > 12)
{
hour12 -= 12;
}
}
if (hours == 0)
{
hour12 = 12;
15
}
cout << "Converted Time (12-hour format): " << hour12
<< ":" << minutes << " " << period << endl;
}
};
int main() {
Time12 time12(10, 30, "AM");
time12.display_12();
time12.to24Hour();
Time24 time24(22, 45); time24.display_24();
time24.to12Hour();
return 0;
}
Output:
16
17
Program 8) Write a function template to implement bubble sort.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream> using
namespace std;
/*
Function: bubbleSort()
Purpose: To sort an array of any data type using Bubble Sort algorithm
Arguments:
arr[] - array to be sorted
n - number of elements in array
Return Type: void
*/
template <typename T>
void bubbleSort(T arr[], int n)
{
for(int i = 0; i < n - 1; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[5] = {5, 2, 4, 1, 3};
bubbleSort(arr, 5); // Sort the array
cout << "sorted array: " << endl;
for(int i=0; i<5; i++)
cout << arr[i] << " "; // Display sorted array
return 0;
}
18
Output:
19
Program 9) Write a Class Template to implement Stack.
Solution:
/*
Author: Hitender (231621)
*/
#include <iostream>
using namespace std;
/*
Class: Stack
Purpose: To implement a stack using a class template and fixed-size array
Data Members:
arr[100] - array to store stack elements
top - index of topmost element in stack
Function Name: push, Return Type: void
Function Name: pop, Return Type: void
Function Name: peek, Return Type: T
Function Name: isEmpty, Return Type: bool
Function Name: display, Return Type: void
*/
template <class T>
class Stack {
public:
T arr[100];
int top;
public:
Stack() {
top = -1; // stack is initially empty
}
/*
Function:
push()
Purpose:
To add element on top of stack
Arg1: value, type: T, Purpose: Element to be pushed onto the stack
Return: void
*/
void push(T value) {
if (top >= 99) {
cout << "Stack Overflow: Cannot insert more elements." <<
endl;
} else {
arr[++top] = value;
}
}
/*
Function:
pop()
Purpose:
To remove top element from stack
Arg1: None
Return: void
*/
void pop() {
if (top < 0) {
cout << "Stack Underflow: Cannot remove from empty
stack." << endl;
} else {
top--;
}
}
/*
Function:
peek()
Purpose:
20
To view top element without removing it
Return:
Top element value
*/
T peek() {
if (top < 0)
{
cout << "Stack is empty." << endl;
return T(); // default value of T
} else {
return arr[top];
}
}
/*
Function:
isEmpty()
Purpose:
To check if stack is empty
Return:
true if empty, false otherwise
*/
bool isEmpty() {
return top < 0;
}
};
int main() {
Stack<int> s; // create stack of int
s.push(10);
s.push(20);
s.push(30);
cout << "Top element: " << s.peek() << endl;
s.pop();
cout << "Top after pop: " << s.peek() << endl;
return 0;
}
Output:
21
Program 10) Create a program where the base class 'Person' contains general
information like name and age. A derived class 'Employee' includes employee-
specific attributes like employee ID and department. A further derived class
'Manager' includes additional details like the team size and budget. Write a
program to display complete information for the Manager.
Solution:
/*
Author: Hitender, 231621
*/
#include <iostream>
#include <vector>
Using namespace std;
/*
Class: Person
Purpose: To store general person details like name and age
Data Members:
name - string age - int
Functions: showPersonData() - displays person's details
*/
class Person { public:
string name; int
age;
public:
/*
Function Name: setPersonInfo
Purpose: To set the name and age of the person Arg1: n, type: string,
Purpose: Name of the person
Arg2: a, type: int, Purpose: Age of the person Return: void
*/
Person(string n, int a) { name = n;
age = a;
}
/*
Function Name: showPersonData()
Purpose: To display the general information of the person
Arg1: None
Return: void
*/
void showPersonData() {
cout << "Name: " << name << endl; cout << "Age:
" << age << endl;
}
};
/* Class:
Employee
Purpose:
Derived from Person,adds employee-specific attribute
Data Members:
employeeID - int
department - string Functions:
showEmployeeData() - displays employee's details along with person details
*/
class Employee: public Person
{
public:
int employeeID; string
department;
public:
22
Employee(string n, int a, int id, string dept): Person(n,a)
{
employeeID = id;
department = dept;
}
/*
Function Name: showEmployeeData
Purpose: To display the employee-specific information (ID
And department)
Arg1: None
Return: void
*/
void showEmployeeData() { showPersonData();
cout << "Employee ID: " << employeeID <<endl;
cout << "Department: " << department << endl;
}
};
/* Class:
Manager
Purpose:
Derived from Employee, manages a team of employees and has a budget
Data Members:
budget - double
team - vector of Employee objects
Functions:
addTeamMember() - adds an employee to manager's team showManagerData() - displays
manager's details and team
members' details
*/
class Manager : public Employee { public:
double budget;
vector<Employee> team;
Manager(string n, int a, int id, string dept, double bud)
: Employee(n, a, id, dept)
{
budget = bud;
}
void addTeamMember(Employee e)
{
team.push_back(e);
}
/*
Function Name: showManagerData Purpose:
To display manager info
Arg1: None
Return: void
*/
void showManagerData() {
cout << "\n Manager Details " <<endl;
showEmployeeData();
cout << "Budget: Rupees " << budget <<endl;
cout << "Team Size: " << team.size() <<endl;
cout << "\n Team Members " << endl; for
(size_t i = 0; i < team.size(); i++) {
cout << "\nEmployee " << i + 1 << ":" << endl; team[i].showEmployeeData();
}
cout << endl;
}
};
23
int main() {
Manager m1("ABC", 40, 101, "IT", 500000.00);
Employee e1("JKL", 28, 201, "IT");
Employee e2("PQR", 30, 202, "IT");
Employee e3("XYZ", 27, 203, "IT");
m1.addTeamMember(e1;
m1.addTeamMember(e2;
m1.addTeamMember(e3;
m1.showManagerData();
return 0;
Output:
24
25
26
Program 11) A banking system needs to handle different types of accounts:
savings accounts and current accounts. Both account types have a balance and
support operations like deposit and withdrawal. However, savings accounts
accrue interest, while current accounts might have overdraft facilities.
Design an abstract class Account with abstract methods for calculating interest
(which might return 0 for some accounts) and displaying account details. Create
concrete classes SavingsAccount and CurrentAccount that inherit from Account.
Implement the interest calculation for SavingsAccount and add an attribute for
overdraft limit in CurrentAccount. Show how you would perform deposit and
withdrawal operations on instances of both account types and display their
details, including any accrued interest or overdraft information.
Note: Overdraft facility is a service where customers can withdraw money
irrespective of their current bank balance.
Solution:
/*
Author: Hitender (231621) Description:
A simple banking system handling:
Savings Account with interest calculation Current
Account with overdraft facility
*/
#include <iostream> using
namespace std;
/*
Class: Account_Holder
Purpose: To hold customer details
Member data: name (string), balance (long long), acc_number(long long)
*/
class Account_Holder {
public:
string name;
long long balance;
long long acc_number;
Account_Holder()
{
name = "";
balance = 0;
acc_number = 0;
}
Account_Holder(string n, long long acc_no)
{
name = n;
balance = 0;
acc_number = acc_no;
}
};
/*
Abstract Class: Account
Purpose: Base for SavingsAccount & CurrentAccount
*/
class Account
{
public:
Account_Holder holder;
27
public:
Account() {} // Default constructor
Account(string n, long long acc_no) : holder(n, acc_no) {}
virtual void cal_interest() =0;
virtual void print_details() = 0;
};
/*
Class: SavingsAccount
Purpose: Savings account with interest
*/
class SavingsAccount : public Account
{
public:
int days;
int rate;
long long interest;
SavingsAccount(string n, long long acc_no, int d) : Account(n, acc_no)
{
days = d;
rate = 10;
interest = 0;
}
/*
Function Name: calculate_interest
Purpose: To calculate interest on the savings account balance
Arg1: None
Return: interest amount
*/
void cal_interest() override {
interest = (holder.balance * rate * days) / (365 * 100);
cout << "Interest accrued: " << interest << " rupees" << endl;
holder.balance += interest;
}
/*
Function Name: print_details()
Purpose: To display details of the savings account including balance and
interest
Arg1: None
Return: void
*/
void print_details() override
{
cout << "\n[Savings Account Details]\n"; cout << "Name: "
<< holder.name << endl;
cout << "Account No: " << holder.acc_number << endl;
cout << "Balance: " << holder.balance << " Rupees" <<endl;
}
void deposit(long long amount) {
holder.balance += amount;
cout << "Rupees" << amount << " deposited.\n";
}
void withdraw(long long amount)
{
if (amount <= holder.balance)
{
holder.balance -= amount;
28
cout << "Rupees" << amount << " withdrawn.\n";
}
else
{
cout << "Insufficient balance!" << endl;
}
}
void print_balance() {
cout << "Current Balance: Rupees" << holder.balance << endl;
}
};
/*
Class: CurrentAccount
Purpose: Current account with overdraft facility
*/
class CurrentAccount : public Account {
public:
long long overdraft;
public:
CurrentAccount(string n, long long acc_no) : Account(n, acc_no)
{
overdraft = 5000;
}
void cal_interest() override {} // No interest for current account
/*
Function Name: displayAccountDetails
Purpose: To display details of the current account including balance and
overdraft limit
Arg1: None
Return: void
*/
void print_details() override {
cout << "\n[Current Account Details]\n";
cout << "Name: " << holder.name << endl;
cout << "Account No: " << holder.acc_number << endl;
cout << "Balance: Ruppes" << holder.balance << endl;
cout << "Overdraft Limit: Rupees" << overdraft <<endl;
}
void deposit(long long amount) {
holder.balance += amount;
cout << "Rupees" << amount << " deposited.\n";
}
void withdraw(long long amount) {
if (amount <= (holder.balance + overdraft))
{
holder.balance -= amount;
cout << "Rupees" << amount << " withdrawn.\n";
if (holder.balance < 0)
{
cout << "Overdraft used! Remaining
overdraft: Rupees" << overdraft + holder.balance <<
endl;
}
} else {
cout << "Overdraft limit exceeded!\n";
}
}
void print_balance(){
cout << "Current Balance: Rupees" << holder.balance << endl;
29
}
};
int main() {
cout << " Savings Account Operations "; SavingsAccount s("Alice",
10000001, 365); s.deposit(10000);
s.print_balance(); s.cal_interest();
s.print_balance(); s.withdraw(5000);
s.print_details();
cout << " Current Account Operations "; CurrentAccount c("Bob",
20000002); c.deposit(5000);
c.print_balance(); c.withdraw(8000);
c.print_balance(); c.withdraw(3000);
c.print_details();
return 0;
}
Output:
30
31
32
10
13
4
13
5
13
6
13
7
13
8
39
24
0
24
1
24
2
24
3