Programming assignment(Challenging
task)
Name – Rishabh Nirmalkar
Reg no. – 25BCG10026
1. Write a C++ program to define a class BankAccount with: ▪ Private data members:
• Account number
• Account holder name
• Balance
▪ Public member functions
• createAccount()
• deposit()
• withdraw() (check sufficient balance)
• display()
• A destructor that displays a message when object is destroyed
In main():
• Create an object
• Perform deposit and withdrawal
• Display final balance
Code :
#include <iostream>
#include <string>
#include <iomanip>
class BankAccount {
private:
std::string accountNumber;
std::string holderName;
double balance;
public:
BankAccount() : accountNumber(""), holderName(""), balance(0.0) {}
void createAccount() {
std::cout << "Enter account number: ";
std::getline(std::cin, accountNumber);
std::cout << "Enter account holder name: ";
std::getline(std::cin, holderName);
std::cout << "Enter initial balance: ";
while (!(std::cin >> balance)) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid amount. Enter initial balance: ";
}
std::[Link](10000, '\n');
std::cout << "Account created successfully.\n";
}
void deposit(double amount) {
if (amount <= 0) {
std::cout << "Deposit amount must be positive.\n";
return;
}
balance += amount;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Deposited: " << amount << ". New balance: " << balance << "\n";
}
void withdraw(double amount) {
if (amount <= 0) {
std::cout << "Withdrawal amount must be positive.\n";
return;
}
if (amount > balance) {
std::cout << "Insufficient balance. Withdrawal cancelled.\n";
return;
}
balance -= amount;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Withdrew: " << amount << ". New balance: " << balance << "\n";
}
void display() const {
std::cout << "\n--- Account Details ---\n";
std::cout << "Account Number: " << accountNumber << "\n";
std::cout << "Holder Name: " << holderName << "\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << "Balance: " << balance << "\n";
}
~BankAccount() {
std::cout << "BankAccount object for " << holderName << " is being destroyed.\n";
}
};
int main() {
BankAccount acc;
[Link]();
double amt;
std::cout << "Enter amount to deposit: ";
while (!(std::cin >> amt)) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid amount. Enter amount to deposit: ";
}
[Link](amt);
std::cout << "Enter amount to withdraw: ";
while (!(std::cin >> amt)) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid amount. Enter amount to withdraw: ";
}
[Link](amt);
[Link]();
return 0;
}
Output :
2. Write a C++ program to define a class Student with:
• Private data members: roll number, name, marks
• A parameterized constructor to initialize data
• A copy constructor
• A destructor that displays a message when the object is destroyed
• A member function to display details
In main():
• Create one object
• Create another object using the copy constructor
• Display details of both objects
Code :
#include <iostream>
#include <string>
class Student {
private:
int rollNumber;
std::string name;
double marks;
public:
Student(int roll, const std::string &studentName, double studentMarks)
: rollNumber(roll), name(studentName), marks(studentMarks) {}
Student(const Student &other)
: rollNumber([Link]), name([Link]), marks([Link]) {
std::cout << "Copy constructor called for " << name << "\n";
}
void display() const {
std::cout << "Roll Number: " << rollNumber << "\n";
std::cout << "Name: " << name << "\n";
std::cout << "Marks: " << marks << "\n";
}
~Student() {
std::cout << "Student object for " << name << " is being destroyed.\n";
}
};
int main() {
Student student1(101, "Alice Johnson", 88.5);
Student student2 = student1;
std::cout << "Details of student1:\n";
[Link]();
std::cout << "\nDetails of student2 (copy):\n";
[Link]();
return 0;
}
Output :
3. Write a C++ program to demonstrate function overloading for calculating the volume of:
• Cube
• Cylinder
• Rectangular box
Code :
#include <iostream>
static constexpr double PI = 3.14159265358979323846;
// Function overloads for volume calculation
double volume(double side) {
// Cube volume: side^3
return side * side * side;
}
double volume(double radius, double height) {
// Cylinder volume: pi * r^2 * h
return PI * radius * radius * height;
}
double volume(double length, double width, double height) {
// Rectangular box volume: l * w * h
return length * width * height;
}
int main() {
double cubeSide = 3.5;
double cylinderRadius = 2.0;
double cylinderHeight = 5.0;
double boxLength = 4.0;
double boxWidth = 2.5;
double boxHeight = 3.0;
std::cout << "Volume of cube (side " << cubeSide << "): "
<< volume(cubeSide) << "\n";
std::cout << "Volume of cylinder (radius " << cylinderRadius
<< ", height " << cylinderHeight << "): "
<< volume(cylinderRadius, cylinderHeight) << "\n";
std::cout << "Volume of rectangular box (" << boxLength << " x "
<< boxWidth << " x " << boxHeight << "): "
<< volume(boxLength, boxWidth, boxHeight) << "\n";
return 0;
}
Output :
4. Write a C++ program to calculate the electricity bill for a consumer based on the number
of units consumed. The program must use a switch-case structure with suitable range
handling logic.
The billing rules are as follows:
• 0 to 100 units: ₹5 per unit
• 101 to 200 units:₹7 per unit
• 201 to 300 units:₹10 per unit
• Above 300 units: ₹15 per unit
The program should also apply a surcharge of 10% if the total bill amount exceeds ₹3000.
Display the consumer’s units consumed, basic bill amount, surcharge if applicable, and final bill
amount.
Code :
#include <iostream>
int main() {
int units;
std::cout << "Enter the number of units consumed: ";
while (!(std::cin >> units) || units < 0) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid input. Enter a non-negative integer for units: ";
}
int rate = 0;
int slab = units / 100;
switch (slab) {
case 0:
rate = 5; // 0 - 100 units
break;
case 1:
if (units <= 100)
rate = 5;
else
rate = 7;
break;
case 2:
if (units <= 200)
rate = 7;
else
rate = 10;
break;
case 3:
if (units <= 300)
rate = 10;
else
rate = 15;
break;
default:
rate = 15;
break;
}
double basicAmount = units * rate;
double surcharge = 0.0;
if (basicAmount > 3000.0) {
surcharge = basicAmount * 0.10;
}
double finalAmount = basicAmount + surcharge;
std::cout << "\nUnits consumed: " << units << "\n";
std::cout << "Basic bill amount: ₹" << basicAmount << "\n";
if (surcharge > 0.0) {
std::cout << "Surcharge (10%): ₹" << surcharge << "\n";
} else {
std::cout << "Surcharge: ₹0.00\n";
}
std::cout << "Final bill amount: ₹" << finalAmount << "\n";
return 0;
}
Output :
5. Write a C++ program to design a class Employee for analyzing employee salary and
performance records.
The class should contain the following private data members:
employeeID, name, department, basicSalary, experience, performanceRating, and grossSalary.
The class should contain the following public member functions:
input() to accept employee details.
calculateSalary() to calculate gross salary using basic salary, experience bonus, and
performance-based bonus. display() to display employee details.
Create an array of 5 Employee objects and perform the following operations:
1. Calculate gross salary for each employee.
2. Display employees whose gross salary is above the average gross salary.
3. Display the details of the highest-paid employee.
4. Count and display the number of employees in each department.
Code :
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
class Employee {
private:
std::string employeeID;
std::string name;
std::string department;
double basicSalary;
int experience;
int performanceRating;
double grossSalary;
public:
Employee()
: basicSalary(0.0), experience(0), performanceRating(0), grossSalary(0.0) {}
void input() {
std::cout << "Enter employee ID: ";
std::getline(std::cin, employeeID);
std::cout << "Enter employee name: ";
std::getline(std::cin, name);
std::cout << "Enter department: ";
std::getline(std::cin, department);
std::cout << "Enter basic salary: ";
while (!(std::cin >> basicSalary) || basicSalary < 0.0) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid salary. Enter basic salary: ";
}
std::cout << "Enter years of experience: ";
while (!(std::cin >> experience) || experience < 0) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid experience. Enter years of experience: ";
}
std::cout << "Enter performance rating (1 to 5): ";
while (!(std::cin >> performanceRating) || performanceRating < 1 || performanceRating >
5) {
std::[Link]();
std::[Link](10000, '\n');
std::cout << "Invalid rating. Enter performance rating (1 to 5): ";
}
std::[Link](10000, '\n');
}
void calculateSalary() {
double experienceBonus = basicSalary * 0.03 * experience; // 3% of basic salary per year
double performanceBonusRate = 0.0;
switch (performanceRating) {
case 1: performanceBonusRate = 0.03; break;
case 2: performanceBonusRate = 0.05; break;
case 3: performanceBonusRate = 0.08; break;
case 4: performanceBonusRate = 0.10; break;
case 5: performanceBonusRate = 0.12; break;
default: performanceBonusRate = 0.0; break;
}
double performanceBonus = basicSalary * performanceBonusRate;
grossSalary = basicSalary + experienceBonus + performanceBonus;
}
void display() const {
std::cout << "Employee ID: " << employeeID << "\n";
std::cout << "Name: " << name << "\n";
std::cout << "Department: " << department << "\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << "Basic Salary: ₹" << basicSalary << "\n";
std::cout << "Experience: " << experience << " years\n";
std::cout << "Performance Rating: " << performanceRating << "\n";
std::cout << "Gross Salary: ₹" << grossSalary << "\n";
}
double getGrossSalary() const {
return grossSalary;
}
const std::string &getDepartment() const {
return department;
}
};
int main() {
const int employeeCount = 5;
std::vector<Employee> employees(employeeCount);
std::cout << "Enter details for " << employeeCount << " employees:\n\n";
for (int i = 0; i < employeeCount; ++i) {
std::cout << "Employee " << (i + 1) << ":\n";
employees[i].input();
employees[i].calculateSalary();
std::cout << "\n";
}
double totalGross = 0.0;
for (const auto &emp : employees) {
totalGross += [Link]();
}
double averageGross = totalGross / employeeCount;
std::cout << "Average gross salary: ₹" << std::fixed << std::setprecision(2) << averageGross <<
"\n\n";
std::cout << "Employees with gross salary above average:\n";
for (const auto &emp : employees) {
if ([Link]() > averageGross) {
[Link]();
std::cout << "--------------------------\n";
}
}
const Employee *highestPaid = &employees[0];
for (const auto &emp : employees) {
if ([Link]() > highestPaid->getGrossSalary()) {
highestPaid = &emp;
}
}
std::cout << "\nHighest-paid employee details:\n";
highestPaid->display();
std::cout << "\n";
std::map<std::string, int> departmentCount;
for (const auto &emp : employees) {
departmentCount[[Link]()]++;
}
std::cout << "Employee count by department:\n";
for (const auto &entry : departmentCount) {
std::cout << [Link] << ": " << [Link] << "\n";
}
return 0;
}
Output :
6. Write a C++ program to define a base class Shape with a function area(). Derive classes
Rectangle, Circle, and Triangle from Shape. Override the area()function in each derived class to
calculate and display the area according to the shape.
Code :
#include <iostream>
#include <cmath>
class Shape {
public:
virtual ~Shape() = default;
virtual void area() const {
std::cout << "Shape area is undefined." << std::endl;
}
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
void area() const override {
double a = width * height;
std::cout << "Rectangle area: " << a << std::endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void area() const override {
double a = M_PI * radius * radius;
std::cout << "Circle area: " << a << std::endl;
}
};
class Triangle : public Shape {
private:
double base;
double height;
public:
Triangle(double b, double h) : base(b), height(h) {}
void area() const override {
double a = 0.5 * base * height;
std::cout << "Triangle area: " << a << std::endl;
}
};
int main() {
Rectangle rect(5.0, 3.0);
Circle circ(2.5);
Triangle tri(4.0, 6.0);
Shape* shapes[] = {&rect, &circ, &tri};
for (Shape* shape : shapes) {
shape->area();
}
return 0;
}
Output :
7. Write a C++ program to define a class Student with private data members rollNumber, name,
and marks.
Overload:
• >> operator to input student details.
• << operator to display student details.
Create one Student object and demonstrate input/output using overloaded stream operators.
Code :
#include <iostream>
#include <limits>
#include <string>
class Student {
private:
int rollNumber;
std::string name;
double marks;
public:
Student() : rollNumber(0), name(""), marks(0.0) {}
friend std::istream& operator>>(std::istream& in, Student& s) {
std::cout << "Enter roll number: ";
in >> [Link];
[Link](std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter name: ";
std::getline(in, [Link]);
std::cout << "Enter marks: ";
in >> [Link];
[Link](std::numeric_limits<std::streamsize>::max(), '\n');
return in;
}
friend std::ostream& operator<<(std::ostream& out, const Student& s) {
out << "Student Details:\n";
out << "Roll Number: " << [Link] << "\n";
out << "Name: " << [Link] << "\n";
out << "Marks: " << [Link] << "\n";
return out;
}
};
int main() {
Student student;
std::cin >> student;
std::cout << "\n" << student;
return 0;
}
Output :
8. Write a C++ program to swap the values of three variables without using a third variable.
Your program must include:
1. A function using call by value with no return type.
2. A function using call by reference with no return type.
3. Swapping logic without using any extra variable.
4. Display the values before and after calling both functions.
5. Show how call by value and call by reference differ in their output.
Code :
#include <iostream>
void swapByValue(int a, int b, int c) {
std::cout << " swapByValue (inside) - before: a=" << a << " b=" << b << " c=" << c << "\n";
a = a ^ b ^ c;
b = a ^ b ^ c;
c = a ^ b ^ c;
a = a ^ b ^ c;
std::cout << " swapByValue (inside) - after: a=" << a << " b=" << b << " c=" << c << "\n";
}
void swapByReference(int &a, int &b, int &c) {
std::cout << " swapByReference (inside) - before: a=" << a << " b=" << b << " c=" << c << "\n";
a = a ^ b ^ c;
b = a ^ b ^ c;
c = a ^ b ^ c;
a = a ^ b ^ c;
std::cout << " swapByReference (inside) - after: a=" << a << " b=" << b << " c=" << c << "\n";
}
int main() {
int a = 10;
int b = 20;
int c = 30;
std::cout << "Original values: a=" << a << " b=" << b << " c=" << c << "\n\n";
std::cout << "Calling swapByValue(a, b, c)...\n";
swapByValue(a, b, c);
std::cout << "After swapByValue call: a=" << a << " b=" << b << " c=" << c << "\n\n";
std::cout << "Calling swapByReference(a, b, c)...\n";
swapByReference(a, b, c);
std::cout << "After swapByReference call: a=" << a << " b=" << b << " c=" << c << "\n";
return 0;
}
Output :
9. Write a C++ program to illustrate operator overloading for inserters (<>)
Code :
#include <iostream>
#include <string>
class Person {
public:
std::string name;
int age;
Person() : name(""), age(0) {}
Person(const std::string &name, int age) : name(name), age(age) {}
};
std::ostream &operator<<(std::ostream &out, const Person &p) {
out << "Name: " << [Link] << ", Age: " << [Link];
return out;
}
std::istream &operator>>(std::istream &in, Person &p) {
std::cout << "Enter name: ";
std::getline(in >> std::ws, [Link]);
std::cout << "Enter age: ";
in >> [Link];
return in;
}
int main() {
Person alice("Alice", 28);
std::cout << "Using overloaded inserter (<<) to display object:\n";
std::cout << alice << "\n\n";
Person bob;
std::cout << "Using overloaded extractor (>>) to read object values:\n";
std::cin >> bob;
std::cout << "You entered: " << bob << "\n";
return 0;
}
Output :
10. Write a C++ program to overload unary and binary operators.
Code :
#include <iostream>
class Number {
public:
int value;
Number(int v = 0) : value(v) {}
// Unary operator overloads
Number operator+() const {
return Number(+value);
}
Number operator-() const {
return Number(-value);
}
Number &operator++() {
++value;
return *this;
}
Number operator++(int) {
Number temp(*this);
value++;
return temp;
}
// Binary operator overloads
Number operator+(const Number &other) const {
return Number(value + [Link]);
}
Number operator-(const Number &other) const {
return Number(value - [Link]);
}
};
std::ostream &operator<<(std::ostream &out, const Number &num) {
out << [Link];
return out;
}
int main() {
Number a(5);
Number b(3);
std::cout << "Original values: a=" << a << " b=" << b << "\n";
Number unaryPlus = +a;
Number unaryMinus = -a;
std::cout << "Unary +a => " << unaryPlus << "\n";
std::cout << "Unary -a => " << unaryMinus << "\n";
Number sum = a + b;
Number diff = a - b;
std::cout << "Binary a + b => " << sum << "\n";
std::cout << "Binary a - b => " << diff << "\n";
std::cout << "Prefix ++a => " << ++a << "\n";
std::cout << "After prefix, a=" << a << "\n";
Number post = a++;
std::cout << "Postfix a++ returned " << post << " and now a=" << a << "\n";
return 0;
}
Output :
11. Write a C++ program to write data to a text file and read it back.
Code :
#include <iostream>
#include <fstream>
#include <string>
int main() {
const std::string filename = "[Link]";
// Write data to the text file
std::ofstream outFile(filename);
if (!outFile) {
std::cerr << "Error: Cannot open " << filename << " for writing.\n";
return 1;
}
outFile << "Line 1: Hello, file I/O!\n";
outFile << "Line 2: This is written to a text file.\n";
outFile << "Line 3: Reading it back now.\n";
[Link]();
std::cout << "Data written to " << filename << " successfully.\n";
// Read data back from the text file
std::ifstream inFile(filename);
if (!inFile) {
std::cerr << "Error: Cannot open " << filename << " for reading.\n";
return 1;
}
std::cout << "Reading data from " << filename << ":\n";
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << "\n";
}
[Link]();
return 0;
}
Output :
12. Write a C++ program to demonstrate a friend function that accesses private members of a
class.
Code :
#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
public:
BankAccount(const std::string &name, double initialBalance)
: accountHolder(name), balance(initialBalance) {}
// Friend function declaration
friend void displayAccountDetails(const BankAccount &account);
friend void updateBalance(BankAccount &account, double amount);
};
// Friend function definition - can access private members
void displayAccountDetails(const BankAccount &account) {
std::cout << "Account Holder: " << [Link] << "\n";
std::cout << "Current Balance: $" << [Link] << "\n";
}
// Another friend function that modifies private members
void updateBalance(BankAccount &account, double amount) {
[Link] += amount;
std::cout << "Balance updated. New balance: $" << [Link] << "\n";
}
int main() {
BankAccount myAccount("John Doe", 5000.0);
std::cout << "Using friend function to access private members:\n";
displayAccountDetails(myAccount);
std::cout << "\nDepositing $1500...\n";
updateBalance(myAccount, 1500);
std::cout << "\nWithdrawing $500...\n";
updateBalance(myAccount, -500);
std::cout << "\nFinal Account Details:\n";
displayAccountDetails(myAccount);
return 0;
}
Output :
13. Write a C++ program to demonstrate the use of manipulators (setw, setprecision, setfill) for
formatted output.
Code :
#include <iostream>
#include <iomanip>
int main() {
std::cout << "===== Demonstrating C++ Manipulators =====\n\n";
// 1. setw() - Set field width
std::cout << "1. Using setw() for field width:\n";
std::cout << " Right-aligned (default):\n";
std::cout << std::setw(10) << "Name" << std::setw(10) << "Age" << std::setw(10) << "Score\n";
std::cout << std::setw(10) << "Alice" << std::setw(10) << 28 << std::setw(10) << 95.5 << "\n";
std::cout << std::setw(10) << "Bob" << std::setw(10) << 25 << std::setw(10) << 87.3 << "\n";
std::cout << std::setw(10) << "Charlie" << std::setw(10) << 30 << std::setw(10) << 92.1 << "\n\
n";
// 2. Left alignment with setw()
std::cout << "2. Using setw() with left alignment:\n";
std::cout << std::left;
std::cout << std::setw(15) << "Product" << std::setw(10) << "Price" << std::setw(8) << "Qty\n";
std::cout << std::setw(15) << "Apples" << std::setw(10) << "$1.50" << std::setw(8) << 10 << "\
n";
std::cout << std::setw(15) << "Oranges" << std::setw(10) << "$2.00" << std::setw(8) << 7 << "\
n";
std::cout << std::right; // Reset to right
// 3. setfill() - Set fill character
std::cout << "\n3. Using setfill() with dashes:\n";
std::cout << "Progress: " << std::setfill('-') << std::setw(20) << "DONE" << "\n";
std::cout << "Status: " << std::setfill('=') << std::setw(20) << "COMPLETE" << "\n";
std::cout << std::setfill(' '); // Reset to space
// 4. setprecision() - Set decimal precision
std::cout << "\n4. Using setprecision() for decimals:\n";
double pi = 3.14159265359;
double value = 123.456789;
std::cout << "Default precision: " << pi << "\n";
std::cout << "Precision 2: " << std::setprecision(2) << pi << "\n";
std::cout << "Precision 5: " << std::setprecision(5) << pi << "\n";
std::cout << "Precision 8: " << std::setprecision(8) << pi << "\n";
// 5. Fixed notation with setprecision()
std::cout << "\n5. Using fixed notation with setprecision():\n";
std::cout << "Value: " << value << "\n";
std::cout << "Fixed with precision 2: " << std::fixed << std::setprecision(2) << value << "\n";
std::cout << "Fixed with precision 4: " << std::setprecision(4) << value << "\n";
// 6. Combining manipulators
std::cout << "\n6. Combining multiple manipulators:\n";
std::cout << std::right << std::setfill('*') << std::fixed << std::setprecision(2);
std::cout << std::setw(15) << 100.1 << "\n";
std::cout << std::setw(15) << 200.555 << "\n";
std::cout << std::setw(15) << 50.9 << "\n";
return 0;
}
Output :
14. Write a C++ program to define a class BankAccount with private data members
accountNumber, accountHolderName, and balance. Create a member function withdraw() that
throws an exception if the withdrawal amount is greater than the available balance. Display the
updated balance after successful withdrawal.
Code :
#include <iostream>
#include <string>
#include <iomanip>
class InsufficientFundsException : public std::exception {
private:
std::string message;
public:
InsufficientFundsException(double required, double available)
: message("Error: Insufficient funds! Required: $" + std::to_string(required)
+ ", Available: $" + std::to_string(available)) {}
const char* what() const noexcept override {
return message.c_str();
}
};
class BankAccount {
private:
int accountNumber;
std::string accountHolderName;
double balance;
public:
BankAccount(int accNum, const std::string &holder, double initialBalance)
: accountNumber(accNum), accountHolderName(holder), balance(initialBalance) {}
void withdraw(double amount) {
if (amount > balance) {
throw InsufficientFundsException(amount, balance);
}
balance -= amount;
std::cout << "Withdrawal successful!\n";
displayBalance();
}
void deposit(double amount) {
balance += amount;
std::cout << "Deposit successful!\n";
displayBalance();
}
void displayBalance() const {
std::cout << "Account Number: " << accountNumber << "\n";
std::cout << "Account Holder: " << accountHolderName << "\n";
std::cout << "Current Balance: $" << std::fixed << std::setprecision(2) << balance << "\n";
}
double getBalance() const {
return balance;
}
};
int main() {
BankAccount account(12345, "John Doe", 1000.00);
std::cout << "===== Bank Account Management =====\n\n";
[Link]();
std::cout << "\n--- Attempting withdrawal of $500 ---\n";
try {
[Link](500);
} catch (const InsufficientFundsException &e) {
std::cerr << [Link]() << "\n";
}
std::cout << "\n--- Attempting withdrawal of $600 ---\n";
try {
[Link](600);
} catch (const InsufficientFundsException &e) {
std::cerr << [Link]() << "\n";
}
std::cout << "\n--- Attempting withdrawal of $100 (exceeds balance) ---\n";
try {
[Link](100);
} catch (const InsufficientFundsException &e) {
std::cerr << [Link]() << "\n";
}
std::cout << "\n--- Depositing $300 ---\n";
[Link](300);
std::cout << "\n--- Now attempting withdrawal of $100 ---\n";
try {
[Link](100);
} catch (const InsufficientFundsException &e) {
std::cerr << [Link]() << "\n";
}
return 0;
}
Output :
15. Write a C++ program to define a class Number with two private data members num1 and
num2.
The class should contain:
• A member function input() to accept both numbers.
• A member function display() to display both numbers.
• A friend function findGreater() to access private data members and display the greater
number.
Code :
#include <iostream>
class Number {
private:
int num1;
int num2;
public:
Number() : num1(0), num2(0) {}
void input() {
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
}
void display() const {
std::cout << "Numbers: " << num1 << " and " << num2 << "\n";
}
// Friend function declaration
friend void findGreater(const Number &obj);
};
// Friend function definition - can access private members
void findGreater(const Number &obj) {
std::cout << "Comparing private members...\n";
if (obj.num1 > obj.num2) {
std::cout << "Greater number: " << obj.num1 << "\n";
} else if (obj.num2 > obj.num1) {
std::cout << "Greater number: " << obj.num2 << "\n";
} else {
std::cout << "Both numbers are equal: " << obj.num1 << "\n";
}
}
int main() {
Number num;
std::cout << "===== Number Comparison Program =====\n\n";
[Link]();
std::cout << "\n";
std::cout << "Using member function display():\n";
[Link]();
std::cout << "\nUsing friend function findGreater():\n";
findGreater(num);
return 0;
}
Output :
16. Write a C++ program to define a class Complex with public data members real and imag.
The class should contain:
• A constructor to initialize complex numbers.
• A member function display() to display the complex number.
• Overload the + operator to add two complex numbers.
Create two objects of class Complex, add them using overloaded + operator, and display the
result.
Code :
#include <iostream>
class Complex {
public:
double real;
double imag;
// Constructor to initialize complex numbers
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// Member function to display complex number
void display() const {
if (imag >= 0) {
std::cout << real << " + " << imag << "i\n";
} else {
std::cout << real << " - " << -imag << "i\n";
}
}
// Overload + operator to add two complex numbers
Complex operator+(const Complex &other) const {
Complex result;
[Link] = this->real + [Link];
[Link] = this->imag + [Link];
return result;
}
};
int main() {
std::cout << "===== Complex Number Addition =====\n\n";
// Create two complex objects
Complex c1(3, 4);
Complex c2(1, 2);
std::cout << "Complex Number 1: ";
[Link]();
std::cout << "Complex Number 2: ";
[Link]();
// Add two complex numbers using overloaded + operator
Complex sum = c1 + c2;
std::cout << "\nSum (c1 + c2): ";
[Link]();
// Another example
std::cout << "\n--- Another Example ---\n";
Complex c3(5, -3);
Complex c4(-2, 6);
std::cout << "Complex Number 3: ";
[Link]();
std::cout << "Complex Number 4: ";
[Link]();
Complex sum2 = c3 + c4;
std::cout << "\nSum (c3 + c4): ";
[Link]();
return 0;
}
Output :
17. Write a C++ program to accept two integers from the user. Perform division and modulus
operations. Use exception handling to throw an exception if the second number is zero.
Code :
#include <iostream>
#include <stdexcept>
int main() {
int num1, num2;
std::cout << "===== Division and Modulus Operations =====\n\n";
std::cout << "Enter first integer: ";
std::cin >> num1;
std::cout << "Enter second integer: ";
std::cin >> num2;
try {
// Check if second number is zero
if (num2 == 0) {
throw std::invalid_argument("Error: Cannot divide by zero!");
}
// Perform division and modulus operations
int quotient = num1 / num2;
int remainder = num1 % num2;
std::cout << "\n--- Results ---\n";
std::cout << "Division: " << num1 << " / " << num2 << " = " << quotient << "\n";
std::cout << "Modulus: " << num1 << " % " << num2 << " = " << remainder << "\n";
}
catch (const std::invalid_argument &e) {
std::cerr << [Link]() << "\n";
std::cerr << "Please provide a non-zero second integer.\n";
}
return 0;
}
Output :
18. Write a C++ program using STL algorithms (like sort, find, search, count, and merge)
Code :
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
void printVector(const std::vector<int> &vec) {
for (int num : vec) {
std::cout << num << " ";
}
std::cout << "\n";
}
int main() {
std::cout << "===== STL Algorithms Demonstration =====\n\n";
// 1. sort() algorithm
std::cout << "1. Using sort() to sort elements:\n";
std::vector<int> arr1 = {50, 20, 40, 10, 30};
std::cout << " Original: ";
printVector(arr1);
std::sort([Link](), [Link]());
std::cout << " Sorted: ";
printVector(arr1);
// 2. find() algorithm
std::cout << "\n2. Using find() to locate an element:\n";
std::vector<int> arr2 = {10, 20, 30, 40, 50};
int target = 30;
auto it = std::find([Link](), [Link](), target);
if (it != [Link]()) {
std::cout << " Found " << target << " at position: "
<< std::distance([Link](), it) << "\n";
} else {
std::cout << " Element not found.\n";
}
// 3. count() algorithm
std::cout << "\n3. Using count() to count occurrences:\n";
std::vector<int> arr3 = {1, 2, 2, 3, 2, 4, 2, 5};
std::cout << " Vector: ";
printVector(arr3);
int counted = std::count([Link](), [Link](), 2);
std::cout << " Count of 2: " << counted << "\n";
// 4. search() algorithm
std::cout << "\n4. Using search() to find a subsequence:\n";
std::vector<int> arr4 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> pattern = {5, 6, 7};
std::cout << " Main sequence: ";
printVector(arr4);
std::cout << " Pattern to find: ";
printVector(pattern);
auto result = std::search([Link](), [Link](),
[Link](), [Link]());
if (result != [Link]()) {
std::cout << " Pattern found at position: "
<< std::distance([Link](), result) << "\n";
} else {
std::cout << " Pattern not found.\n";
}
// 5. merge() algorithm
std::cout << "\n5. Using merge() to merge two sorted sequences:\n";
std::vector<int> arr5 = {1, 3, 5, 7};
std::vector<int> arr6 = {2, 4, 6, 8};
std::vector<int> merged([Link]() + [Link]());
std::cout << " First sorted sequence: ";
printVector(arr5);
std::cout << " Second sorted sequence: ";
printVector(arr6);
std::merge([Link](), [Link](),
[Link](), [Link](),
[Link]());
std::cout << " Merged result: ";
printVector(merged);
return 0;
}
Output :
19. Write a C++ program to demonstrate the scope, lifetime, and storage location of storage
classes (auto, static, and extern) in C++ with suitable examples.
Code :
#include <iostream>
// Global variable - has extern (external) scope by default
int globalCounter = 0;
// Static global variable - internal linkage, visible only in this file
static int staticGlobal = 100;
void demonstrateAuto() {
std::cout << "\n1. AUTO Storage Class:\n";
std::cout << " Scope: Local\n";
std::cout << " Lifetime: Automatic (created and destroyed with function call)\n";
std::cout << " Storage: Stack\n";
for (int i = 0; i < 3; i++) {
auto localVar = i * 10; // auto keyword (default for local variables)
std::cout << " Inside loop - localVar: " << localVar << "\n";
}
// localVar is destroyed here
std::cout << " Outside loop - localVar no longer exists\n";
}
void demonstrateStatic() {
std::cout << "\n2. STATIC Storage Class:\n";
std::cout << " Scope: Local (but persistent)\n";
std::cout << " Lifetime: Static (persists between function calls)\n";
std::cout << " Storage: Memory (not on stack)\n";
static int callCount = 0; // Initialized only once
callCount++;
std::cout << " Function called " << callCount << " time(s)\n";
std::cout << " Static variable value persists between calls\n";
}
void demonstrateStaticLocal() {
std::cout << "\n3. STATIC Local Variable Demo:\n";
static int staticLocal = 1;
std::cout << " Calling function 3 times...\n";
for (int i = 0; i < 3; i++) {
staticLocal += 5;
std::cout << " Call " << (i + 1) << ": staticLocal = " << staticLocal << "\n";
}
}
int main() {
std::cout << "===== Storage Classes Demonstration =====\n";
// AUTO storage class example
demonstrateAuto();
// STATIC storage class example
std::cout << "\n--- Demonstrating Static Storage Persistence ---\n";
demonstrateStatic();
demonstrateStatic();
demonstrateStatic();
// STATIC Local variable example
std::cout << "\n--- Demonstrating Static Local Variable ---\n";
demonstrateStaticLocal();
// EXTERN/Global variable example
std::cout << "\n4. EXTERN/GLOBAL Storage Class:\n";
std::cout << " Scope: Global (visible throughout the program)\n";
std::cout << " Lifetime: Static (entire program duration)\n";
std::cout << " Storage: Data segment\n";
std::cout << " globalCounter: " << globalCounter << "\n";
globalCounter += 50;
std::cout << " After modification - globalCounter: " << globalCounter << "\n";
// STATIC global variable
std::cout << "\n5. STATIC Global Variable:\n";
std::cout << " Scope: Internal (visible only in this file)\n";
std::cout << " Lifetime: Static (entire program duration)\n";
std::cout << " Storage: Data segment\n";
std::cout << " staticGlobal: " << staticGlobal << "\n";
// Comparison table
std::cout << "\n===== Storage Classes Comparison =====\n";
std::cout << "Class | Scope | Lifetime | Default | Initialization\n";
std::cout << "---------|-----------|-------------|---------|----------------\n";
std::cout << "auto | Local | Automatic | yes | Not initialized\n";
std::cout << "static | Local* | Static | no | Zero initialized\n";
std::cout << "extern | Global | Static | no | Zero initialized\n";
std::cout << "*Local static persists between function calls\n";
return 0;
}
Output :
20. What do you mean by default arguments in C++? Write a C++ program that defines a function
power(base, exponent = 2) to calculate power. Demonstrate function calls with and without
passing the exponent.
Code :
#include <iostream>
#include <cmath>
#include <iomanip>
// Function with default argument
double power(double base, int exponent = 2) {
return std::pow(base, exponent);
}
int main() {
std::cout << "===== Default Arguments in C++ =====\n\n";
std::cout << "What are Default Arguments?\n";
std::cout << "Default arguments are values provided in function definition.\n";
std::cout << "If a value is not passed, the default value is used.\n";
std::cout << "Syntax: returnType functionName(dataType param1, dataType param2 =
defaultValue)\n\n";
std::cout << "Example: double power(double base, int exponent = 2)\n";
std::cout << "Here, exponent has a default value of 2.\n\n";
// Demonstration
std::cout << "===== Function Calls =====\n\n";
// Call 1: With both arguments
double base1 = 5;
int exp1 = 3;
double result1 = power(base1, exp1);
std::cout << "1. power(" << base1 << ", " << exp1 << "):\n";
std::cout << " " << base1 << "^" << exp1 << " = " << result1 << "\n\n";
// Call 2: Without exponent (uses default value 2)
double base2 = 7;
double result2 = power(base2);
std::cout << "2. power(" << base2 << "):\n";
std::cout << " " << base2 << "^2 = " << result2 << " (default exponent = 2)\n\n";
// Call 3: Another example with default
double base3 = 10;
double result3 = power(base3);
std::cout << "3. power(" << base3 << "):\n";
std::cout << " " << base3 << "^2 = " << result3 << " (default exponent = 2)\n\n";
// Call 4: With custom exponent
double base4 = 2;
int exp4 = 5;
double result4 = power(base4, exp4);
std::cout << "4. power(" << base4 << ", " << exp4 << "):\n";
std::cout << " " << base4 << "^" << exp4 << " = " << result4 << "\n\n";
// Table showing comparisons
std::cout << "===== Comparison Table =====\n";
std::cout << std::setw(20) << "Function Call"
<< std::setw(20) << "Exponent Used"
<< std::setw(15) << "Result\n";
std::cout << std::string(55, '-') << "\n";
std::cout << std::setw(20) << "power(3)"
<< std::setw(20) << "2 (default)"
<< std::setw(15) << power(3) << "\n";
std::cout << std::setw(20) << "power(3, 3)"
<< std::setw(20) << "3 (provided)"
<< std::setw(15) << power(3, 3) << "\n";
std::cout << std::setw(20) << "power(4)"
<< std::setw(20) << "2 (default)"
<< std::setw(15) << power(4) << "\n";
std::cout << std::setw(20) << "power(4, 4)"
<< std::setw(20) << "4 (provided)"
<< std::setw(15) << power(4, 4) << "\n";
// Key points
std::cout << "\n===== Key Points =====\n";
std::cout << "1. Default arguments must be at the end of parameter list.\n";
std::cout << "2. Once a parameter has default value, all following must have defaults.\n";
std::cout << "3. Reduces code redundancy when common values are used.\n";
std::cout << "4. Makes function more flexible and user-friendly.\n";
return 0;
}
Output :