EXPERIMENT 1: Design a class to represent a bank account.
Include the following
members. Data Members:
• Name of the depositor.
• Account number.
• Type of account.
• Balance amount in the account Methods.
• To assign initial values.
• To deposit an amount.
• To withdraw an amount after checking balance.
• To display the name and balance Incorporate a constructor to provide initial values
PROGRAM:
#include <iostream>
#include <string>
using namespace std;
class BankAccount
private:
string depositorName;
int accountNumber;
string accountType;
double balance;
public:
// Constructor to initialize values
BankAccount(string name, int accNo, string type, double initialBalance)
: depositorName(name), accountNumber(accNo), accountType(type),
balance(initialBalance)
// Method to deposit an amount
void deposit(double amount)
if (amount > 0)
{
balance += amount;
cout << "Deposited: $" << amount << endl;
else
cout << "Invalid deposit amount." << endl;
// Method to withdraw an amount
void withdraw(double amount)
if (amount > 0)
if (amount <= balance)
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
else
cout << "Insufficient balance." << endl;
else
{
cout << "Invalid withdrawal amount." << endl;
// Method to display the name and balance
void display() const
cout << "Name: " << depositorName << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Balance: $" << balance << endl;
};
int main()
// Create a BankAccount object with initial values
BankAccount account("John Doe", 123456789, "Savings", 1000.00);
// Display initial account details
cout << "Initial Account Details:" << endl;
account.display();
// Perform deposit and withdrawal operations
cout << "\nPerforming operations:" << endl;
account.deposit(500.00);
account.withdraw(200.00);
account.withdraw(2000.00); // Attempt to withdraw more than the balance
// Display updated account details
cout << "\nUpdated Account Details:" << endl;
account.display();
return 0; }
EXPERIMENT 2: Guess-the-number-game: Write a program that pays the game of
“guess the number” as follows: Your program choose the number to be guess by selecting
an integer at random in the range 1 to 1000. The program then displays the following: I have
a number between 1 and 1000. Can you guess my number? Please type your first guess.
The player then type a first guess. The program responds with one of the following: 1.
Excellent! you guessed the number! Would like to play again (y or n)? 2. Too low. Try again.
3. Too high. Try again. If the payer’s guess is incorrect, your program should loop until the
player finally get the number right. Your program should keep telling the player Too high or
Too low to help the player “zero in” on the correct answer
PROGRAM:
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
using namespace std;
void playGame() {
// Generate a random number between 1 and 1000
int numberToGuess = rand() % 1000 + 1;
int playerGuess;
bool guessedCorrectly = false;
cout << "I have a number between 1 and 1000." << endl;
cout << "Can you guess my number?" << endl;
while (!guessedCorrectly) {
cout << "Please type your guess: ";
cin >> playerGuess;
if (playerGuess < numberToGuess) {
cout << "Too low. Try again." << endl;
} else if (playerGuess > numberToGuess) {
cout << "Too high. Try again." << endl;
} else {
cout << "Excellent! You guessed the number!" << endl;
guessedCorrectly = true;
int main() {
// Seed the random number generator
srand(static_cast<unsigned>(time(0)));
char playAgain;
do {
playGame();
cout << "Would you like to play again (y or n)? ";
cin >> playAgain;
} while (playAgain == 'y' || playAgain == 'Y');
cout << "Thank you for playing!" << endl;
return 0;
}
EXPERIMENT 3: Assume that a bank maintains two kinds of account for its customers,
one called saving account and the other current account. The saving account provides
compound interest and withdrawal facilities but no cheque book facility. The current
account provides cheque book facility but no interest. Current account holders should
also maintain a minimum balance falls below this level, a service charge is imposed.
PROGRAM:
#include <iostream>
#include <string>
using namespace std;
// Base class for common account functionalities
class Account {
protected:
string customerName;
int accountNumber;
string accountType;
double balance;
public:
// Method to initialize account details
void initialize(string name, int accNo, string accType, double initialBalance) {
customerName = name;
accountNumber = accNo;
accountType = accType;
balance = initialBalance;
}
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount." << endl;
// Method to display balance
void displayBalance() const {
cout << "Account Holder: " << customerName << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Balance: $" << balance << endl;
// Method to withdraw money (pure virtual, to be implemented by derived classes)
virtual void withdraw(double amount) = 0;
virtual ~Account() {}
};
// Derived class for Savings Account
class SavAcct : public Account {
private:
double interestRate; // Annual interest rate in percentage
public:
// Method to initialize Savings Account details
void initialize(string name, int accNo, double initialBalance, double rate) {
Account::initialize(name, accNo, "Savings", initialBalance);
interestRate = rate;
// Method to compute and deposit interest
void computeInterest() {
double interest = (balance * interestRate) / 100.0;
balance += interest;
cout << "Interest applied: $" << interest << endl;
// Override withdraw method for Savings Account
void withdraw(double amount) override {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
cout << "Insufficient balance or invalid amount." << endl;
}
};
// Derived class for Current Account
class CurrAcct : public Account {
private:
double minimumBalance;
double serviceCharge;
public:
// Method to initialize Current Account details
void initialize(string name, int accNo, double initialBalance, double minBalance, double
charge) {
Account::initialize(name, accNo, "Current", initialBalance);
minimumBalance = minBalance;
serviceCharge = charge;
// Override withdraw method for Current Account
void withdraw(double amount) override {
if (amount > 0) {
if ((balance - amount) >= minimumBalance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
balance -= serviceCharge;
cout << "Insufficient funds. Service charge applied: $" << serviceCharge << endl;
} else {
cout << "Invalid withdrawal amount." << endl;
};
int main() {
// Creating and initializing Savings Account
SavAcct savings;
savings.initialize("Alice Smith", 1001, 1500.00, 5.0);
savings.displayBalance();
savings.deposit(200.00);
savings.computeInterest();
savings.withdraw(100.00);
savings.displayBalance();
cout << endl;
// Creating and initializing Current Account
CurrAcct current;
current.initialize("Bob Johnson", 2001, 500.00, 100.00, 10.00);
current.displayBalance();
current.deposit(50.00);
current.withdraw(450.00); // Should not apply service charge
current.withdraw(50.00); // Should apply service charge
current.displayBalance();
return 0;
}
EXPERIMENT 4: An election is contested by 5 candidates. The candidates are numbered
1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a
C++ program to read the ballots and count the votes cast for each candidate using an
array. In case, a number read is outside the range 1 to 5, the ballot should be considered
as a ‘spoilt ballot’ and the program should also count the number of spoilt ballots.
PROGRAM:
#include <iostream>
using namespace std;
const int NUM_CANDIDATES = 5;
int main() {
int votes[NUM_CANDIDATES] = {0}; // Array to hold the count of votes for each candidate
int spoiltBallots = 0; // Counter for spoilt ballots
int ballot; // Variable to hold each vote
char moreVotes; // Variable to check if there are more votes to enter
do {
cout << "Enter the candidate number (1 to 5) or enter 0 to finish: ";
cin >> ballot;
// Check if the ballot number is valid
if (ballot >= 1 && ballot <= NUM_CANDIDATES) {
votes[ballot - 1]++; // Increment the vote count for the respective candidate
} else if (ballot == 0) {
// End of voting input
break;
} else {
// Invalid ballot, consider it as a spoilt ballot
spoiltBallots++;
cout << "Do you want to enter another vote? (y/n): ";
cin >> moreVotes;
} while (moreVotes == 'y' || moreVotes == 'Y');
// Display the results
cout << "\nElection Results:\n";
for (int i = 0; i < NUM_CANDIDATES; i++) {
cout << "Candidate " << (i + 1) << ": " << votes[i] << " votes\n";
cout << "Spoilt Ballots: " << spoiltBallots << endl;
return 0;
#include <iostream>
using namespace std;
const int NUM_CANDIDATES = 5;
int main() {
int votes[NUM_CANDIDATES] = {0}; // Array to hold the count of votes for each candidate
int spoiltBallots = 0; // Counter for spoilt ballots
int ballot; // Variable to hold each vote
char moreVotes; // Variable to check if there are more votes to enter
do {
cout << "Enter the candidate number (1 to 5) or enter 0 to finish: ";
cin >> ballot;
// Check if the ballot number is valid
if (ballot >= 1 && ballot <= NUM_CANDIDATES) {
votes[ballot - 1]++; // Increment the vote count for the respective candidate
} else if (ballot == 0) {
// End of voting input
break;
} else {
// Invalid ballot, consider it as a spoilt ballot
spoiltBallots++;
cout << "Do you want to enter another vote? (y/n): ";
cin >> moreVotes;
} while (moreVotes == 'y' || moreVotes == 'Y');
// Display the results
cout << "\nElection Results:\n";
for (int i = 0; i < NUM_CANDIDATES; i++) {
cout << "Candidate " << (i + 1) << ": " << votes[i] << " votes\n";
cout << "Spoilt Ballots: " << spoiltBallots << endl;
return 0;
}
EXPERIMENT 5: Develop a program which will read a string and rewrite it in the
alphabetical order. For example, the word STRING should be written as GINRST.
PROGRAM:
#include <iostream>
#include <algorithm> // For std::sort
#include <string> // For std::string
using namespace std;
int main() {
string inputString;
// Read the input string
cout << "Enter a string: ";
getline(cin, inputString);
// Sort the characters of the string
sort(inputString.begin(), inputString.end());
// Output the sorted string
cout << "Sorted string: " << inputString << endl;
return 0;
}
EXPERIMENT 6: Create a class by name date with the member data day, month and
year. Perform the following:
• Overload all relational operators <, <=, >, >=, ==, !=
• Overload ++ operator to increment a date by one day
• Overload + to add given number of days to find the next date
• Provide the necessary function to use the statement like days=dt; where days is an int
variable and dt is an object of date class. The statement is intended to assign the number
of days elapsed in the current year of the date to the variable days. Note that this is a case
of conversion from derived type to basic type.
PROGRAM:
#include <iostream>
#include <stdexcept> // For std::invalid_argument
using namespace std;
class Date {
private:
int day, month, year;
// Helper function to check if a year is a leap year
bool isLeapYear(int y) const {
return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
// Helper function to get the number of days in a month
int daysInMonth(int m, int y) const {
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return isLeapYear(y) ? 29 : 28;
default: throw invalid_argument("Invalid month");
// Helper function to check if the date is valid
void checkDate() const {
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(month, year)) {
throw invalid_argument("Invalid date");
public:
// Constructor
Date(int d, int m, int y) : day(d), month(m), year(y) {
checkDate();
// Overload relational operators
bool operator<(const Date& other) const {
return (year < other.year) || (year == other.year && month < other.month) || (year ==
other.year && month == other.month && day < other.day);
}
bool operator<=(const Date& other) const {
return *this < other || *this == other;
bool operator>(const Date& other) const {
return !(*this <= other);
bool operator>=(const Date& other) const {
return !(*this < other);
bool operator==(const Date& other) const {
return day == other.day && month == other.month && year == other.year;
bool operator!=(const Date& other) const {
return !(*this == other);
// Overload ++ operator to increment date by one day
Date& operator++() {
++day;
if (day > daysInMonth(month, year)) {
day = 1;
++month;
if (month > 12) {
month = 1;
++year;
return *this;
// Overload + operator to add days to the date
Date operator+(int days) const {
Date result = *this;
result.day += days;
while (result.day > result.daysInMonth(result.month, result.year)) {
result.day -= result.daysInMonth(result.month, result.year);
++result.month;
if (result.month > 12) {
result.month = 1;
++result.year;
return result;
// Conversion operator to get the number of days elapsed in the current year
operator int() const {
int days = day;
for (int m = 1; m < month; ++m) {
days += daysInMonth(m, year);
return days;
// Function to display the date
void display() const {
cout << day << '/' << month << '/' << year << endl;
};
int main() {
try {
Date d1(28, 2, 2024); // Leap year example
Date d2(1, 3, 2024);
cout << "Date d1: "; d1.display();
cout << "Date d2: "; d2.display();
// Testing relational operators
cout << "d1 < d2: " << (d1 < d2) << endl;
cout << "d1 == d2: " << (d1 == d2) << endl;
// Testing ++ operator
++d1;
cout << "After incrementing d1: "; d1.display();
// Testing + operator
Date d3 = d2 + 30;
cout << "d2 + 30 days: "; d3.display();
// Testing conversion operator
int days = d2;
cout << "Days elapsed in the year for d2: " << days << endl;
} catch (const invalid_argument& e) {
cerr << "Error: " << e.what() << endl;
return 0;
}
EXPERIMENT 7: Develop a program to sort a file consisting of books’ details in the
alphabetical order of author names. The details of books include book_id, author_name,
price, no_of_pages, publisher, year_of_publishing.
PROGRAM:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// Define the Book class
class Book {
public:
int book_id;
string author_name;
double price;
int no_of_pages;
string publisher;
int year_of_publishing;
// Constructor to initialize the book details
Book(int id, const string& author, double pr, int pages, const string& pub, int year)
: book_id(id), author_name(author), price(pr), no_of_pages(pages), publisher(pub),
year_of_publishing(year) {}
// Overload the < operator to sort books by author_name
bool operator<(const Book& other) const {
return author_name < other.author_name;
};
// Function to read book details from a file
vector<Book> readBooksFromFile(const string& filename) {
vector<Book> books;
ifstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file for reading." << endl;
return books;
int id, pages, year;
double price;
string author, publisher;
while (file >> id >> ws && getline(file, author, ',') &&
file >> price >> pages >> ws && getline(file, publisher, ',') &&
file >> year) {
books.emplace_back(id, author, price, pages, publisher, year);
file.close();
return books;
// Function to write book details to a file
void writeBooksToFile(const string& filename, const vector<Book>& books) {
ofstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file for writing." << endl;
return;
}
for (const auto& book : books) {
file << book.book_id << ","
<< book.author_name << ","
<< book.price << ","
<< book.no_of_pages << ","
<< book.publisher << ","
<< book.year_of_publishing << "\n";
file.close();
int main() {
const string inputFilename = "books.txt"; // Input file with unsorted book details
const string outputFilename = "sorted_books.txt"; // Output file for sorted book details
// Read books from the file
vector<Book> books = readBooksFromFile(inputFilename);
if (books.empty()) {
cerr << "No books to sort." << endl;
return 1;
// Sort the books by author name
sort(books.begin(), books.end());
// Write sorted books to the file
writeBooksToFile(outputFilename, books);
cout << "Books have been sorted by author name and saved to " << outputFilename <<
endl;
return 0;
EXPERIMENT 8: Design a class template by name Vector and perform the following:
• Find the smallest of the element in the Vector.
• Search for an element in the Vector.
• Find the average of the element in the array.
PROGRAM:
#include <iostream>
#include <vector>
#include <limits> // For std::numeric_limits
using namespace std;
template <typename T>
class Vector {
private:
vector<T> elements;
public:
// Constructor to initialize the vector with a list of elements
Vector(const initializer_list<T>& initList) : elements(initList) {}
// Function to find the smallest element
T findSmallest() const {
if (elements.empty()) {
throw runtime_error("Vector is empty.");
T smallest = numeric_limits<T>::max();
for (const T& element : elements) {
if (element < smallest) {
smallest = element;
}
}
return smallest;
// Function to search for an element
bool search(const T& value) const {
for (const T& element : elements) {
if (element == value) {
return true;
return false;
// Function to find the average of the elements
double findAverage() const {
if (elements.empty()) {
throw runtime_error("Vector is empty.");
T sum = 0;
for (const T& element : elements) {
sum += element;
return static_cast<double>(sum) / elements.size();
}
// Function to display the elements of the vector
void display() const {
for (const T& element : elements) {
cout << element << " ";
cout << endl;
};
int main() {
try {
// Example with integers
Vector<int> intVector = {10, 20, 30, 40, 50};
cout << "Vector elements: ";
intVector.display();
cout << "Smallest element: " << intVector.findSmallest() << endl;
cout << "Search for 30: " << (intVector.search(30) ? "Found" : "Not Found") << endl;
cout << "Average of elements: " << intVector.findAverage() << endl;
// Example with doubles
Vector<double> doubleVector = {10.5, 20.2, 30.3, 40.1, 50.7};
cout << "Vector elements: ";
doubleVector.display();
cout << "Smallest element: " << doubleVector.findSmallest() << endl;
cout << "Search for 20.2: " << (doubleVector.search(20.2) ? "Found" : "Not Found") <<
endl;
cout << "Average of elements: " << doubleVector.findAverage() << endl;
} catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
return 0;
}
EXPERIMENT 9: Design a generic function for finding the largest of three numbers.
PROGRAM:
#include <iostream>
using namespace std;
// Function template to find the largest of three numbers
template <typename T>
T findLargest(T a, T b, T c) {
T largest = a; // Assume a is the largest initially
if (b > largest) {
largest = b; // Update largest if b is greater
if (c > largest) {
largest = c; // Update largest if c is greater
return largest;
int main() {
// Test with integer values
int int1 = 10, int2 = 20, int3 = 15;
cout << "Largest integer: " << findLargest(int1, int2, int3) << endl;
// Test with double values
double double1 = 10.5, double2 = 20.7, double3 = 15.6;
cout << "Largest double: " << findLargest(double1, double2, double3) << endl;
// Test with character values
char char1 = 'a', char2 = 'b', char3 = 'c';
cout << "Largest character: " << findLargest(char1, char2, char3) << endl;
return 0;