You are on page 1of 76

Exercise 1

Introduction to C++ Programming


SET A
1. Write a program in C++ to calculate the volume of a sphere.
#include <iostream>
#include <cmath>

using namespace std;

double calculateSphereVolume(double radius) {


double volume = (4.0 / 3.0) * M_PI * pow(radius, 3);
return volume;
}

int main() {
double radius;

cout << "Enter the radius of the sphere: ";


cin >> radius;

double volume = calculateSphereVolume(radius);

cout << "The volume of the sphere is: " << volume << endl;

return 0;
}

2. . Write a program in C++ to swap two numbers


#include <iostream>

using namespace std;

void swapNumbers(int& num1, int& num2) {


int temp = num1;
num1 = num2;
num2 = temp;
}

int main() {
int num1, num2;

cout << "Enter the first number: ";


cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

cout << "Before swapping: " << endl;


cout << "First number: " << num1 << endl;
cout << "Second number: " << num2 << endl;

swapNumbers(num1, num2);

cout << "After swapping: " << endl;


cout << "First number: " << num1 << endl;
cout << "Second number: " << num2 << endl;

return 0;
}

3. Write a program in C++ to display various type or arithmetic operation using mixed data type
#include <iostream>

using namespace std;

int main() {
int num1 = 10;
float num2 = 5.5;
double num3 = 7.8;

// Addition
float addition = num1 + num2 + num3;
cout << "Addition: " << addition << endl;

// Subtraction
double subtraction = num3 - num2 - num1;
cout << "Subtraction: " << subtraction << endl;

// Multiplication
double multiplication = num1 * num2 * num3;
cout << "Multiplication: " << multiplication << endl;

// Division
double division = num3 / num2 / num1;
cout << "Division: " << division << endl;

// Modulus
int modulus = num1 % 3;
cout << "Modulus: " << modulus << endl;
return 0;
}

4. Write a program in C++ to find the Area and Perimeter of a Rectangle.


#include <iostream>

using namespace std;

int main() {
float length, width;

// Read the length and width from the user


cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "Enter the width of the rectangle: ";
cin >> width;

// Calculate the area and perimeter


float area = length * width;
float perimeter = 2 * (length + width);

// Display the area and perimeter


cout << "Area of the rectangle: " << area << endl;
cout << "Perimeter of the rectangle: " << perimeter << endl;

return 0;
}

SET B
1. Write a program in C++ to find the area and circumference of a circle
#include <iostream>
using namespace std;

int main() {
float radius;

// Read the radius from the user


cout << "Enter the radius of the circle: ";
cin >> radius;

// Calculate the area and circumference


float area = 3.14 * radius * radius;
float circumference = 2 * 3.14 * radius;

// Display the area and circumference


cout << "Area of the circle: " << area << endl;
cout << "Circumference of the circle: " << circumference << endl;

return 0;
}
2.Program to build simple calculator using switch case.
#include <iostream>
using namespace std;

int main() {
int num1, num2;
char operation;

// Read the first number, operation, and second number from the user
cout << "Enter the first number: ";
cin >> num1;

cout << "Enter the operation (+, -, *, /): ";


cin >> operation;

cout << "Enter the second number: ";


cin >> num2;

// Perform the calculation based on the operation


switch (operation) {
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;
} else {
cout << "Error: Division by zero is not allowed." << endl;
}
break;
default:
cout << "Error: Invalid operation." << endl;
}

return 0;
}

3. . Write a program in C++ to convert temperature in Fahrenheit to Celsius


#include <iostream>
using namespace std;

int main() {
double fahrenheit, celsius;

// Read the temperature in Fahrenheit from the user


cout << "Enter the temperature in Fahrenheit: ";
cin >> fahrenheit;
// Convert Fahrenheit to Celsius
celsius = (fahrenheit - 32) * 5 / 9;

// Display the converted temperature in Celsius


cout << "Temperature in Celsius: " << celsius << " degrees" << endl;

return 0;
}

4. . Write a program in C++ to check whether a number is positive, negative or zero.


#include <iostream>
using namespace std;

int main() {
int number;

// Read the number from the user


cout << "Enter a number: ";
cin >> number;

// Check if the number is positive, negative, or zero


if (number > 0) {
cout << "The number is positive." << endl;
} else if (number < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}

return 0;
}

Set C
1 Write a C++ program to display the current date and time
#include <iostream>
#include <ctime>

int main() {
// Get the current time
std::time_t currentTime = std::time(nullptr);

// Convert the current time to string format


std::string dateTime = std::ctime(&currentTime);

// Display the current date and time


std::cout << "Current Date and Time: " << dateTime << std::endl;

return 0;
}
2.Write a program in C++ that takes a number as input and prints its multiplication table upto 10.
#include <iostream>

int main() {
int number;

// Input the number


std::cout << "Enter a number: ";
std::cin >> number;

// Print the multiplication table


std::cout << "Multiplication Table of " << number << ":" << std::endl;
for (int i = 1; i <= 10; i++) {
std::cout << number << " x " << i << " = " << (number * i) << std::endl;
}

return 0;
}

3. Write a program in C++ to enter P, T, R and calculate Simple Interest.


#include <iostream>

int main() {
float principal, time, rate, simpleInterest;

// Input the principal amount, time period, and rate of interest


cout << "Enter the principal amount: ";
cin >> principal;

cout << "Enter the time period (in years): ";


cin >> time;

cout << "Enter the rate of interest (in percentage): ";


cin >> rate;

// Calculate the simple interest


simpleInterest = (principal * time * rate) / 100;

// Print the result


cout << "Simple Interest = " << simpleInterest << endl;

return 0;
}
Exersice 2
Functions in C++
SET A
1. Write a program using function which accept two integers as an argument and return its sum.
Call this function from main( ) and print the results in main( ).
#include <iostream>

// Function to calculate the sum of two integers


int sum(int num1, int num2) {
int result = num1 + num2;
return result;
}

int main() {
int a, b;
int result;

// Input the two integers


std::cout << "Enter two integers: ";
std::cin >> a >> b;

// Call the sum function and store the result


result = sum(a, b);

// Print the result


std::cout << "Sum: " << result << std::endl;

return 0;
}

2. Write a function to calculate the factorial value of any integer as an argument. Call this
function from main( ) and print the results in main( ).
#include <iostream>

// Function to calculate the factorial of a number


int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

int main() {
int num;
int result;

// Input the number


std::cout << "Enter an integer: ";
std::cin >> num;
// Call the factorial function and store the result
result = factorial(num);

// Print the result


std::cout << "Factorial: " << result << std::endl;

return 0;
}

3. Write a function that receives two numbers as an argument and display all prime numbers
between these two numbers. Call this function from main( ).
#include <iostream>

// Function to check if a number is prime


bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}

// Function to display prime numbers between two numbers


void displayPrimeNumbers(int start, int end) {
std::cout << "Prime numbers between " << start << " and " << end << ": ";

for (int i = start; i <= end; ++i) {


if (isPrime(i)) {
std::cout << i << " ";
}
}

std::cout << std::endl;


}

int main() {
int num1, num2;

// Input the numbers


std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;

// Call the displayPrimeNumbers function


displayPrimeNumbers(num1, num2);

return 0;
}
SET B
1. Write a function that receives two numbers as an argument and display all prime numbers
between these two numbers. Call this function from main( ).
#include <iostream>

// Function to check if a number is prime


bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}

// Function to display prime numbers between two numbers


void displayPrimeNumbers(int start, int end) {
std::cout << "Prime numbers between " << start << " and " << end << ": ";

for (int i = start; i <= end; ++i) {


if (isPrime(i)) {
std::cout << i << " ";
}
}

std::cout << std::endl;


}

int main() {
int num1, num2;

// Input the numbers


std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;

// Call the displayPrimeNumbers function


displayPrimeNumbers(num1, num2);

return 0;
}

2. Raising a number to a power p is the same as multiplying n by itself p times. Write a function
called power that takes two arguments, a double value for n and an int value for p, and return
the result as double value. Use default argument of 2 for p, so that if this argument is omitted
the number will be squared. Write the main function that gets value from the user to test power
function.
#include <iostream>
// Function to calculate the power of a number
double power(double n, int p = 2) {
double result = 1.0;
for (int i = 0; i < p; ++i) {
result *= n;
}
return result;
}

int main() {
double number;
int exponent;

// Input the number


std::cout << "Enter a number: ";
std::cin >> number;

// Input the exponent (optional)


std::cout << "Enter the exponent (optional): ";
std::cin >> exponent;

// Calculate and display the result using the power function


double result;
if (exponent != 0) {
result = power(number, exponent);
} else {
result = power(number);
}

std::cout << "Result: " << result << std::endl;

return 0;
}

SET C
1. Write a program that lets the user perform arithmetic operations on two numbers. Your
program must be menu driven, allowing the user to select the operation (+, -, *, or /) and input the
numbers. Furthermore, your program must consist of following functions: 1. Function
showChoice: This function shows the options to the user and explains how to enter data. 2.
Function add: This function accepts two number as arguments and returns sum. 3. Function
subtract: This function accepts two number as arguments and returns their difference.
4. Function multiply: This function accepts two number as arguments and returns product. 5.
Function divide: This function accepts two number as arguments and returns quotient.

#include <iostream>

// Function to display the menu options


void showChoice() {
std::cout << "Menu Options:\n";
std::cout << "1. Add\n";
std::cout << "2. Subtract\n";
std::cout << "3. Multiply\n";
std::cout << "4. Divide\n";
std::cout << "Enter your choice (1-4): ";
}

// Function to perform addition


double add(double a, double b) {
return a + b;
}

// Function to perform subtraction


double subtract(double a, double b) {
return a - b;
}

// Function to perform multiplication


double multiply(double a, double b) {
return a * b;
}

// Function to perform division


double divide(double a, double b) {
return a / b;
}

int main() {
int choice;
double num1, num2;

// Display the menu options


showChoice();
std::cin >> choice;

// Input the numbers


std::cout << "Enter the first number: ";
std::cin >> num1;
std::cout << "Enter the second number: ";
std::cin >> num2;

// Perform the selected operation and display the result


switch (choice) {
case 1:
std::cout << "Result: " << add(num1, num2) << std::endl;
break;
case 2:
std::cout << "Result: " << subtract(num1, num2) << std::endl;
break;
case 3:
std::cout << "Result: " << multiply(num1, num2) << std::endl;
break;
case 4:
std::cout << "Result: " << divide(num1, num2) << std::endl;
break;
default:
std::cout << "Invalid choice! Please select a valid option.\n";
break;
}

return 0;
}
Assignment 3:
1. Define a class student with the following specification Private members of class
student admno integer sname 20 character eng. math, science float total float
ctotal() a function to calculate eng + math + science with float return type. Public
member function of class student Takedata() Function to accept values for admno,
sname, eng, science and invoke ctotal() to calculate total. Showdata() Function to
display all the data members on the screen
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int admno;
string sname;
float eng, math, science;
float total;

float ctotal() {
return eng + math + science;
}

public:
void Takedata() {
cout << "Enter Admission Number: ";
cin >> admno;
cout << "Enter Student Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, sname);
cout << "Enter marks for English: ";
cin >> eng;
cout << "Enter marks for Math: ";
cin >> math;
cout << "Enter marks for Science: ";
cin >> science;

total = ctotal(); // Calculate total


}

void Showdata() {
cout << "Admission Number: " << admno << endl;
cout << "Student Name: " << sname << endl;
cout << "English Marks: " << eng << endl;
cout << "Math Marks: " << math << endl;
cout << "Science Marks: " << science << endl;
cout << "Total Marks: " << total << endl;
}
};

int main() {
Student student;
student.Takedata();
cout << "\nStudent Information:\n";
student.Showdata();
return 0;
}

2. Define a class batsman with the following specifications: Private members: bcode
4 digits code number bname 20 characters innings, notout, runs integer type
batavg it is calculated according to the formula – batavg =runs/(innings-notout)
calcavg() Function to compute batavg Public members: readdata() Function to
accept value from bcode, name, innings, notout and invoke the function calcavg()
displaydata() Function to display the data members on the screen.

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

class Batsman {
private:
int bcode;
string bname;
int innings, notout, runs;
float batavg;

void calcavg() {
batavg = static_cast<float>(runs) / (innings - notout);
}

public:
void readdata() {
cout << "Enter Batsman Code: ";
cin >> bcode;
cout << "Enter Batsman Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, bname);
cout << "Enter Innings: ";
cin >> innings;
cout << "Enter Not Out: ";
cin >> notout;
cout << "Enter Runs: ";
cin >> runs;

calcavg(); // Calculate batting average


}

void displaydata() {
cout << "Batsman Code: " << bcode << endl;
cout << "Batsman Name: " << bname << endl;
cout << "Innings: " << innings << endl;
cout << "Not Out: " << notout << endl;
cout << "Runs: " << runs << endl;
cout << "Batting Average: " << batavg << endl;
}
};
int main() {
Batsman batsman;
batsman.readdata();
cout << "\nBatsman Information:\n";
batsman.displaydata();

return 0;
}

3. Define a class TEST in C++ with following description: Private Members TestCode
of type integer Description of type string , NoCandidate of type integer CenterReqd
(number of centers required) of type integer A member function CALCNTR() to
calculate and return the number of centers as (NoCandidates/100+1) Public
Members - A function SCHEDULE() to allow user to enter values for TestCode,
Description, NoCandidate & call function CALCNTR() to calculate the number of
Centres - A function DISPTEST() to allow user to view the content of all the data
members

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

class TEST {
private:
int TestCode;
string Description;
int NoCandidate;
int CenterReqd;

int CALCNTR() {
return (NoCandidate / 100) + 1;
}

public:
void SCHEDULE() {
cout << "Enter Test Code: ";
cin >> TestCode;
cout << "Enter Description: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, Description);
cout << "Enter Number of Candidates: ";
cin >> NoCandidate;

CenterReqd = CALCNTR(); // Calculate the number of centers required


}

void DISPTEST() {
cout << "Test Code: " << TestCode << endl;
cout << "Description: " << Description << endl;
cout << "Number of Candidates: " << NoCandidate << endl;
cout << "Number of Centers Required: " << CenterReqd << endl;
}
};

int main() {
TEST test;
test.SCHEDULE();
cout << "\nTest Information:\n";
test.DISPTEST();

return 0;
}

4. Define a class in C++ with following description: Private Members A data member
Flight number of type integer A data member Destination of type string A data
member Distance of type float A data member Fuel of type float A member function
CALFUEL() to calculate the value of Fuel as per the following criteria Distance Fuel
<=1000 500 more than 1000 and <=2000 1100 more than 2000 2200 Public
Members A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel A
function SHOWINFO() to allow user to view the content of all the data members.

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

class Flight {
private:
int FlightNumber;
string Destination;
float Distance;
float Fuel;

void CALFUEL() {
if (Distance <= 1000)
Fuel = 500;
else if (Distance <= 2000)
Fuel = 1100;
else
Fuel = 2200;
}

public:
void FEEDINFO() {
cout << "Enter Flight Number: ";
cin >> FlightNumber;
cout << "Enter Destination: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, Destination);
cout << "Enter Distance: ";
cin >> Distance;

CALFUEL(); // Calculate the quantity of fuel


}
void SHOWINFO() {
cout << "Flight Number: " << FlightNumber << endl;
cout << "Destination: " << Destination << endl;
cout << "Distance: " << Distance << " km" << endl;
cout << "Fuel: " << Fuel << " liters" << endl;
}
};

int main() {
Flight flight;
flight.FEEDINFO();
cout << "\nFlight Information:\n";
flight.SHOWINFO();

return 0;
}

5. Define a class BOOK with the following specifications : Private members of


the class BOOK are BOOK NO integer type BOOKTITLE 20 characters PRICE
float (price per copy) TOTAL_COST() A function to calculate the total cost for N
number of copies where N is passed to the function as argument. Public
members of the class BOOK are INPUT() function to read BOOK_NO.
BOOKTITLE, PRICE PURCHASE() function to ask the user to input the number
of copies to be purchased. It invokes TOTAL_COST() and prints the total cost to
be paid by the user. Note : You are also required to give detailed function
definitions.

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

class BOOK {
private:
int BOOK_NO;
string BOOKTITLE;
float PRICE;

float TOTAL_COST(int numCopies) {


return PRICE * numCopies;
}

public:
void INPUT() {
cout << "Enter Book Number: ";
cin >> BOOK_NO;
cout << "Enter Book Title: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, BOOKTITLE);
cout << "Enter Price: ";
cin >> PRICE;
}
void PURCHASE() {
int numCopies;
cout << "Enter the number of copies to be purchased: ";
cin >> numCopies;

float totalCost = TOTAL_COST(numCopies);


cout << "Total cost to be paid: $" << totalCost << endl;
}
};

int main() {
BOOK book;
book.INPUT();
book.PURCHASE();

return 0;
}

6. Define a class REPORT with the following specification: Private members :


adno 4 digit admission number name 20 characters marks an array of 5
floating point values average average marks obtained GETAVG() a function to
compute the average obtained in five subject Public members: READINFO()
function to accept values for adno, name, marks. Invoke the function .
DISPLAYINFO() function to display all data members of report on the screen.
You should give function definitions.

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

class REPORT {
private:
int adno;
string name;
float marks[5];
float average;

void GETAVG() {
float sum = 0;
for (int i = 0; i < 5; i++) {
sum += marks[i];
}
average = sum / 5;
}

public:
void READINFO() {
cout << "Enter Admission Number: ";
cin >> adno;
cout << "Enter Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, name);
cout << "Enter Marks for 5 Subjects:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << (i + 1) << ": ";
cin >> marks[i];
}

GETAVG(); // Calculate the average marks


}

void DISPLAYINFO() {
cout << "Admission Number: " << adno << endl;
cout << "Name: " << name << endl;
cout << "Marks: ";
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
cout << "Average Marks: " << average << endl;
}
};

int main() {
REPORT report;
report.READINFO();
cout << "\nReport Information:\n";
report.DISPLAYINFO();

return 0;
}

SET C
1. Write the definition for a class called Rectangle that has floating point data
members length and width. The class has the following member functions:
void setlength(float) to set the length data member
void setwidth(float) to set the width data member
float perimeter() to calculate and return the perimeter of the rectangle
float area() to calculate and return the area of the rectangle

#include <iostream>
using namespace std;

class Rectangle {
private:
float length;
float width;

public:
void setlength(float len) {
length = len;
}

void setwidth(float wid) {


width = wid;
}

float perimeter() {
return 2 * (length + width);
}

float area() {
return length * width;
}
};

int main() {
Rectangle rect;
float len, wid;

cout << "Enter the length of the rectangle: ";


cin >> len;
rect.setlength(len);

cout << "Enter the width of the rectangle: ";


cin >> wid;
rect.setwidth(wid);

cout << "Perimeter of the rectangle: " << rect.perimeter() << endl;
cout << "Area of the rectangle: " << rect.area() << endl;

return 0;
}

Exercise 4
Constructors & Destructors
SET A
1.Write a program to display student details(Rolllno,name,class,percent) using
constructor and destructor
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int RollNo;
string Name;
string Class;
float Percentage;

public:
Student(int rollNo, const string& name, const string& className, float
percent)
: RollNo(rollNo), Name(name), Class(className), Percentage(percent) {
cout << "Constructor called for Roll No: " << RollNo << endl;
}

~Student() {
cout << "Destructor called for Roll No: " << RollNo << endl;
}

void DisplayDetails() {
cout << "Roll No: " << RollNo << endl;
cout << "Name: " << Name << endl;
cout << "Class: " << Class << endl;
cout << "Percentage: " << Percentage << "%" << endl;
}
};

int main() {
Student student(1234, "John Doe", "10th Grade", 87.5);
student.DisplayDetails();

return 0;
}

2.Define a class Fraction having members numerator and denominator. Define


parameterized and default constructors (default values 0 and 1). Create two
fraction objects and perform the following operations by defining member
functions: Addition, Subtraction, Multiplication and division.

#include <iostream>
using namespace std;

class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int num = 0, int den = 1) {
numerator = num;
denominator = den;
}

Fraction Addition(const Fraction& other) {


int num = (numerator * other.denominator) + (other.numerator *
denominator);
int den = denominator * other.denominator;
return Fraction(num, den);
}

Fraction Subtraction(const Fraction& other) {


int num = (numerator * other.denominator) - (other.numerator *
denominator);
int den = denominator * other.denominator;
return Fraction(num, den);
}

Fraction Multiplication(const Fraction& other) {


int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Fraction(num, den);
}

Fraction Division(const Fraction& other) {


int num = numerator * other.denominator;
int den = denominator * other.numerator;
return Fraction(num, den);
}

void Display() {
cout << numerator << "/" << denominator << endl;
}
};

int main() {
Fraction fraction1(3, 4);
Fraction fraction2(2, 5);

Fraction additionResult = fraction1.Addition(fraction2);


cout << "Addition: ";
additionResult.Display();

Fraction subtractionResult = fraction1.Subtraction(fraction2);


cout << "Subtraction: ";
subtractionResult.Display();

Fraction multiplicationResult = fraction1.Multiplication(fraction2);


cout << "Multiplication: ";
multiplicationResult.Display();
Fraction divisionResult = fraction1.Division(fraction2);
cout << "Division: ";
divisionResult.Display();

return 0;
}

SET B
1. Write a c++ program to read the information like plant_name, plant_code,
plant_type, price. Construct the database with suitable member functions for
initializing and for destroying the data, viz. constructor, copy constructor,
destructor.

C++ program that demonstrates the construction and destruction of a database


for plant information, including member functions for initialization and
destruction using constructors, copy constructor, and destructor:

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

class Plant {
private:
string plant_name;
int plant_code;
string plant_type;
float price;

public:
Plant() {
cout << "Default constructor called" << endl;
}

Plant(const string& name, int code, const string& type, float p) {


plant_name = name;
plant_code = code;
plant_type = type;
price = p;
cout << "Parameterized constructor called" << endl;
}

Plant(const Plant& other) {


plant_name = other.plant_name;
plant_code = other.plant_code;
plant_type = other.plant_type;
price = other.price;
cout << "Copy constructor called" << endl;
}

~Plant() {
cout << "Destructor called for plant: " << plant_name << endl;
}

void Display() {
cout << "Plant Name: " << plant_name << endl;
cout << "Plant Code: " << plant_code << endl;
cout << "Plant Type: " << plant_type << endl;
cout << "Price: " << price << endl;
cout << endl;
}
};

int main() {
Plant plant1("Rose", 1, "Flowering", 10.99);
Plant plant2 = plant1;
Plant plant3;

plant1.Display();
plant2.Display();
plant3.Display();

return 0;
}

In this program, the `Plant` class represents a plant with private data members
`plant_name` (string), `plant_code` (integer), `plant_type` (string), and `price`
(float). The class defines a default constructor, a parameterized constructor, a
copy constructor, and a destructor.

In the `main()` function, we create three `Plant` objects: `plant1` using the
parameterized constructor, `plant2` using the copy constructor with `plant1` as
an argument, and `plant3` using the default constructor. The `Display()`
member function is called on each object to display the plant information.

The output of the program demonstrates the construction and destruction of


the `Plant` objects using the constructors and destructor.

2.Write a cpp program to demonstrate the concept of destructor.

#include <iostream>
using namespace std;

class MyClass {
public:
MyClass() {
cout << "Constructor called" << endl;
}

~MyClass() {
cout << "Destructor called" << endl;
}
};
int main() {
MyClass obj1; // Creating an object of MyClass

// Creating a dynamic object of MyClass using 'new'


MyClass* obj2 = new MyClass();

delete obj2; // Deallocating the dynamic object

return 0;
}

In this program, the `MyClass` class has a constructor and a destructor. The
constructor is called when an object of `MyClass` is created, and the destructor is
called when an object is destroyed or goes out of scope.

In the `main()` function, we demonstrate the concept of a destructor by creating two


objects: `obj1`, which is created on the stack, and `obj2`, which is created
dynamically using the `new` keyword.

When `obj1` is created, the constructor is called and displays the message
"Constructor called". When `obj2` is created using `new`, the constructor is called,
and the message is displayed.

When `delete obj2` is called, it deallocates the memory occupied by `obj2`, and
before that, the destructor is called, displaying the message "Destructor called".

The output of the program will be:

Constructor called
Constructor called
Destructor called

SET C
1. A common place to buy candy is from a machine. The machine sells candies,
chips, gum, and cookies. You have been asked to write a program for this candy
machine. The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.

#include <iostream>
using namespace std;

class CandyMachine {
private:
string product;
float cost;

public:
void showProducts() {
cout << "Products available in the candy machine:" << endl;
cout << "1. Candies" << endl;
cout << "2. Chips" << endl;
cout << "3. Gum" << endl;
cout << "4. Cookies" << endl;
cout << endl;
}

void makeSelection(int choice) {


switch (choice) {
case 1:
product = "Candies";
cost = 0.75;
break;
case 2:
product = "Chips";
cost = 1.25;
break;
case 3:
product = "Gum";
cost = 0.50;
break;
case 4:
product = "Cookies";
cost = 1.00;
break;
default:
cout << "Invalid selection." << endl;
return;
}
cout << "You have selected: " << product << endl;
cout << "Cost: $" << cost << endl;
}

void acceptMoney(float amount) {


if (amount >= cost) {
cout << "Thank you for purchasing " << product << "!" << endl;
float change = amount - cost;
if (change > 0) {
cout << "Your change: $" << change << endl;
}
} else {
cout << "Insufficient amount. Please insert more money." << endl;
}
}
};

int main() {
CandyMachine candyMachine;
candyMachine.showProducts();

int selection;
cout << "Enter your selection (1-4): ";
cin >> selection;

candyMachine.makeSelection(selection);

float amount;
cout << "Enter the amount: $";
cin >> amount;

candyMachine.acceptMoney(amount);

return 0;
}

In this program, the `CandyMachine` class represents a candy machine. It has


member functions to show the available products, let the customer make a
selection, show the cost of the selected item, and accept money from the
customer. The data members `product` and `cost` store the selected product
and its cost, respectively.

In the `main()` function, an object of `CandyMachine` is created. The


`showProducts()` function is called to display the available products. The
customer enters their selection (1-4) and the `makeSelection()` function is called
to set the `product` and `cost` based on the selection. The cost of the selected
item is displayed.

Then, the customer enters the amount of money they want to insert, and the
`acceptMoney()` function is called to check if the amount is sufficient. If the
amount is enough, a message is displayed thanking the customer and providing
change if applicable. If the amount is insufficient, a message is displayed asking
the customer to insert more money.

2. Define class cashRegister in C++ with the following descriptions :


Private Members: cashOnHand of type
integer Public Members:
A default constructor cashRegister() sets the cash in the register to 500.
A constructor cashRegister(int) sets the cash in the register to a specific
amount. A function getCurrentBalance() which returns value of cashOnHand
A function acceptAmount(int) to receive the amount deposited by the customer
and update the amount in the register

#include <iostream>
using namespace std;

class cashRegister {
private:
int cashOnHand;

public:
cashRegister() {
cashOnHand = 500;
}

cashRegister(int cash) {
cashOnHand = cash;
}

int getCurrentBalance() {
return cashOnHand;
}

void acceptAmount(int amount) {


cashOnHand += amount;
}
};

int main() {
cashRegister register1;
cout << "Current balance: $" << register1.getCurrentBalance() << endl;
register1.acceptAmount(100);
cout << "Current balance: $" << register1.getCurrentBalance() << endl;

cashRegister register2(1000);
cout << "Current balance: $" << register2.getCurrentBalance() << endl;
register2.acceptAmount(200);
cout << "Current balance: $" << register2.getCurrentBalance() << endl;

return 0;
}
Exercise 5
Operator Overloading
SET A
1. Write a C++ program to overload ! operator to find factorial of an INTEGER
object.
#include <iostream>
using namespace std;

class INTEGER {
private:
int value;

public:
INTEGER(int val) {
value = val;
}

int operator!() {
int factorial = 1;
for (int i = 1; i <= value; i++) {
factorial *= i;
}
return factorial;
}
};

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

INTEGER obj(num);
int result = !obj;

cout << "Factorial of " << num << " is: " << result << endl;

return 0;
}

2. Create a class Rational to represent a Rational number. Perform the Basic


Arithmetic operations: Addition, Subtraction, Multiplication and Division for
Two Rational Numbers.
#include <iostream>
using namespace std;

class Rational {
private:
int numerator;
int denominator;

public:
Rational(int num = 0, int den = 1) {
numerator = num;
denominator = den;
simplify();
}

void simplify() {
int gcd = calculateGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) {
numerator *= -1;
denominator *= -1;
}
}

int calculateGCD(int a, int b) {


if (b == 0)
return a;
return calculateGCD(b, a % b);
}

Rational operator+(const Rational& other) const {


int num = (numerator * other.denominator) + (other.numerator *
denominator);
int den = denominator * other.denominator;
return Rational(num, den);
}

Rational operator-(const Rational& other) const {


int num = (numerator * other.denominator) - (other.numerator *
denominator);
int den = denominator * other.denominator;
return Rational(num, den);
}

Rational operator*(const Rational& other) const {


int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Rational(num, den);
}

Rational operator/(const Rational& other) const {


int num = numerator * other.denominator;
int den = denominator * other.numerator;
return Rational(num, den);
}

void display() {
cout << numerator << "/" << denominator;
}
};

int main() {
Rational r1(3, 4);
Rational r2(2, 5);

cout << "Rational Number 1: ";


r1.display();
cout << endl;

cout << "Rational Number 2: ";


r2.display();
cout << endl;

Rational addition = r1 + r2;


cout << "Addition: ";
addition.display();
cout << endl;

Rational subtraction = r1 - r2;


cout << "Subtraction: ";
subtraction.display();
cout << endl;

Rational multiplication = r1 * r2;


cout << "Multiplication: ";
multiplication.display();
cout << endl;

Rational division = r1 / r2;


cout << "Division: ";
division.display();
cout << endl;

return 0;
}

3. Create a class String to represent a string. Overload the + operator to


concatenate 2 strings, <=, == , >= to compare 2 strings

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

class String {
private:
char* str;
int length;

public:
String(const char* s = "") {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}

String(const String& other) {


length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}

~String() {
delete[] str;
}

String operator+(const String& other) const {


int newLength = length + other.length;
char* temp = new char[newLength + 1];
strcpy(temp, str);
strcat(temp, other.str);
String result(temp);
delete[] temp;
return result;
}

bool operator<=(const String& other) const {


return strcmp(str, other.str) <= 0;
}

bool operator==(const String& other) const {


return strcmp(str, other.str) == 0;
}

bool operator>=(const String& other) const {


return strcmp(str, other.str) >= 0;
}

void display() const {


cout << str;
}
};

int main() {
String s1("Hello");
String s2("World");

cout << "String 1: ";


s1.display();
cout << endl;

cout << "String 2: ";


s2.display();
cout << endl;

String concatenated = s1 + s2;


cout << "Concatenated String: ";
concatenated.display();
cout << endl;

cout << "Comparison: ";


if (s1 <= s2)
cout << "String 1 is less than or equal to String 2";
else if (s1 == s2)
cout << "String 1 is equal to String 2";
else if (s1 >= s2)
cout << "String 1 is greater than or equal to String 2";
cout << endl;

return 0;
}

SET B
1. Define a class Date. Overload the operators << and >> for this class to shift a
date by specific number of days.
#include <iostream>
using namespace std;

class Date {
private:
int day;
int month;
int year;

public:
Date(int d = 0, int m = 0, int y = 0) {
day = d;
month = m;
year = y;
}

void shiftDate(int numDays) {


// Increment the date by the specified number of days
int totalDays = day + numDays;
while (totalDays > getDaysInMonth(month, year)) {
totalDays -= getDaysInMonth(month, year);
month++;
if (month > 12) {
month = 1;
year++;
}
}
day = totalDays;
}

int getDaysInMonth(int m, int y) {


// Returns the number of days in a given month and year
int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (m == 2 && isLeapYear(y)) {
return 29; // February in a leap year
}
return daysInMonth[m];
}

bool isLeapYear(int y) {
// Returns true if the year is a leap year, false otherwise
if (y % 4 == 0) {
if (y % 100 == 0) {
if (y % 400 == 0) {
return true;
}
return false;
}
return true;
}
return false;
}

friend ostream& operator<<(ostream& os, const Date& date);


friend istream& operator>>(istream& is, Date& date);
};

ostream& operator<<(ostream& os, const Date& date) {


os << date.day << "/" << date.month << "/" << date.year;
return os;
}

istream& operator>>(istream& is, Date& date) {


is >> date.day >> date.month >> date.year;
return is;
}

int main() {
Date date;

cout << "Enter a date (day month year): ";


cin >> date;

int numDays;
cout << "Enter the number of days to shift the date: ";
cin >> numDays;

date.shiftDate(numDays);

cout << "Shifted date: " << date << endl;

return 0;
}

2. Create a class matrix which stores a matrix of integers of given size. Write a
necessary member functions. Overload the following operators
+ Adds two matrices and stores in the third.
== Returns 1 if the two matrices are same otherwise 0. (Use dynamic memory
allocation)

#include <iostream>
using namespace std;
class Matrix {
private:
int rows;
int columns;
int** data;

public:
Matrix(int r, int c) {
rows = r;
columns = c;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[columns];
}
}

Matrix(const Matrix& other) {


rows = other.rows;
columns = other.columns;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[columns];
for (int j = 0; j < columns; j++) {
data[i][j] = other.data[i][j];
}
}
}

~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}

void setElement(int row, int col, int value) {


if (row >= 0 && row < rows && col >= 0 && col < columns) {
data[row][col] = value;
}
}

int getElement(int row, int col) const {


if (row >= 0 && row < rows && col >= 0 && col < columns) {
return data[row][col];
}
return 0;
}
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || columns != other.columns) {
// Matrices are not of the same size
return Matrix(0, 0);
}

Matrix result(rows, columns);


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}

return result;
}

bool operator==(const Matrix& other) const {


if (rows != other.rows || columns != other.columns) {
// Matrices are not of the same size
return false;
}

for (int i = 0; i < rows; i++) {


for (int j = 0; j < columns; j++) {
if (data[i][j] != other.data[i][j]) {
return false;
}
}
}

return true;
}
};

int main() {
Matrix matrix1(2, 2);
matrix1.setElement(0, 0, 1);
matrix1.setElement(0, 1, 2);
matrix1.setElement(1, 0, 3);
matrix1.setElement(1, 1, 4);

Matrix matrix2(2, 2);


matrix2.setElement(0, 0, 5);
matrix2.setElement(0, 1, 6);
matrix2.setElement(1, 0, 7);
matrix2.setElement(1, 1, 8);

Matrix matrix3 = matrix1 + matrix2;


if (matrix1 == matrix2) {
cout << "Matrix 1 is equal to Matrix 2" << endl;
} else {
cout << "Matrix 1 is not equal to Matrix 2" << endl;
}

if (matrix1 == matrix3) {
cout << "Matrix 1 is equal to Matrix 3" << endl;
} else {
cout << "Matrix 1 is not equal to Matrix 3" << endl;
}

return 0;
}

3. Create a class Fraction having two data members (numerator, denominator).


The default values should be 0 and 1. Overload the following operators
<< Insertion
>> Extraction (display in reduced form)
< Returns 1 if first fraction is less than second
Accept n fraction objects and sort them in the ascending order.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Fraction {
private:
int numerator;
int denominator;

public:
Fraction(int num = 0, int denom = 1) : numerator(num), denominator(denom)
{}

friend ostream& operator<<(ostream& os, const Fraction& fraction) {


os << fraction.numerator << "/" << fraction.denominator;
return os;
}

friend istream& operator>>(istream& is, Fraction& fraction) {


char separator;
is >> fraction.numerator >> separator >> fraction.denominator;
fraction.reduce();
return is;
}

bool operator<(const Fraction& other) const {


return (numerator * other.denominator < other.numerator * denominator);
}

void reduce() {
int gcd = computeGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}

static int computeGCD(int a, int b) {


if (b == 0) {
return a;
}
return computeGCD(b, a % b);
}
};

int main() {
int n;
cout << "Enter the number of fractions: ";
cin >> n;

vector<Fraction> fractions(n);
cout << "Enter " << n << " fractions in the format
'numerator/denominator':\n";
for (int i = 0; i < n; i++) {
cout << "Fraction " << i + 1 << ": ";
cin >> fractions[i];
}

sort(fractions.begin(), fractions.end());

cout << "Fractions in ascending order:\n";


for (const Fraction& fraction : fractions) {
cout << fraction << endl;
}

return 0;
}

In this program, the `Fraction` class represents a fraction with a numerator and
denominator. The class overloads the `<<` operator for insertion, allowing
fractions to be printed in the "numerator/denominator" format. It also overloads
the `>>` operator for extraction, enabling fractions to be read from input in the
same format and automatically reduced to their simplest form.

The `<` operator is overloaded to compare two fractions based on their decimal
values. The `reduce()` function is used to reduce the fraction to its simplest
form by dividing both the numerator and denominator by their greatest
common divisor (GCD).

In the `main()` function, the user is prompted to enter the number of fractions
and then input each fraction. The fractions are stored in a vector and sorted in
ascending order using the `<` operator. Finally, the sorted fractions are
displayed on the console.

You can run this program and provide the desired number of fractions to see
them sorted in ascending order.

SET C
1. Write a program to overload the new and delete operator
Certainly! Here's an example of how you can overload the `new` and `delete`
operators in C++:

#include <iostream>
using namespace std;

class MyClass {
public:
int data;

MyClass() : data(0) {
cout << "Default constructor called." << endl;
}

MyClass(int value) : data(value) {


cout << "Parameterized constructor called." << endl;
}

void* operator new(size_t size) {


cout << "Overloaded new operator called. Size: " << size << " bytes." <<
endl;
void* ptr = ::new MyClass(); // Allocating memory using global new
operator
return ptr;
}

void operator delete(void* ptr) {


cout << "Overloaded delete operator called." << endl;
::delete ptr; // Deallocating memory using global delete operator
}
};

int main() {
MyClass* obj = new MyClass(42);
cout << "Data: " << obj->data << endl;
delete obj;

return 0;
}
In this program, the `MyClass` class overloads the `new` and `delete` operators.
The `new` operator is overloaded with the `operator new` function, which is a
static member function of the class. Inside this function, you can customize the
memory allocation behavior. In this example, it prints a message indicating the
size of the allocated memory and then uses the global `new` operator to allocate
memory for the object. The `delete` operator is overloaded with the `operator
delete` function, which is also a static member function of the class. Inside this
function, you can customize the memory deallocation behavior. In this example,
it prints a message and uses the global `delete` operator to deallocate the
memory.

In the `main()` function, an object of `MyClass` is created using the overloaded


`new` operator. The constructor is called with the provided value, and the data
member is accessed and printed. Finally, the object is deleted using the
overloaded `delete` operator.

When you run this program, you will see the customized messages printed
when the overloaded `new` and `delete` operators are called. The output may
vary depending on the compiler and system you are using.

2. Sparse matrices are used in a number of numerical methods (e.g., finite


element analysis). A sparse matrix is one which has the great majority of its
elements set to zero. In practice, sparse matrices of sizes up to 500 500 are not
uncommon. On a machine which uses a 64-bit representation for reals, storing
such a matrix as an array would require 2 megabytes of storage. A more
economic representation would record only nonzero elements together with
their positions in the matrix. Define a SparseMatrix class which uses a linked-
list to record only nonzero elements, overload the +, -, and * operators for it.
Also define an appropriate memberwise initialization constructor and
memberwise assignment operator for the class.

#include <iostream>
using namespace std;

class SparseMatrix {
private:
struct Node {
int row;
int col;
int value;
Node* next;

Node(int r, int c, int v) : row(r), col(c), value(v), next(nullptr) {}


};

int numRows;
int numCols;
Node* head;

public:
SparseMatrix(int rows, int cols) : numRows(rows), numCols(cols), head(nullptr) {}

void insertElement(int row, int col, int value) {


Node* newNode = new Node(row, col, value);
newNode->next = head;
head = newNode;
}

int getElement(int row, int col) {


Node* curr = head;
while (curr != nullptr) {
if (curr->row == row && curr->col == col) {
return curr->value;
}
curr = curr->next;
}
return 0;
}

SparseMatrix operator+(const SparseMatrix& other) {


if (numRows != other.numRows || numCols != other.numCols) {
throw runtime_error("Matrix dimensions must be the same.");
}

SparseMatrix result(numRows, numCols);

Node* curr = head;


while (curr != nullptr) {
result.insertElement(curr->row, curr->col, curr->value);
curr = curr->next;
}

curr = other.head;
while (curr != nullptr) {
int existingValue = result.getElement(curr->row, curr->col);
result.insertElement(curr->row, curr->col, existingValue + curr->value);
curr = curr->next;
}

return result;
}

SparseMatrix operator-(const SparseMatrix& other) {


if (numRows != other.numRows || numCols != other.numCols) {
throw runtime_error("Matrix dimensions must be the same.");
}

SparseMatrix result(numRows, numCols);

Node* curr = head;


while (curr != nullptr) {
result.insertElement(curr->row, curr->col, curr->value);
curr = curr->next;
}

curr = other.head;
while (curr != nullptr) {
int existingValue = result.getElement(curr->row, curr->col);
result.insertElement(curr->row, curr->col, existingValue - curr->value);
curr = curr->next;
}

return result;
}

SparseMatrix operator*(const SparseMatrix& other) {


if (numCols != other.numRows) {
throw runtime_error("Invalid matrix dimensions for multiplication.");
}

SparseMatrix result(numRows, other.numCols);

Node* currA = head;


while (currA != nullptr) {
Node* currB = other.head;
while (currB != nullptr) {
if (currA->col == currB->row) {
int existingValue = result.getElement(currA->row, currB->col);
result.insertElement(currA->row, currB->col, existingValue + (currA-
>value * currB->value));
}
currB = currB->next;
}
currA = currA->next;
}

return result;
}

void displayMatrix() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols;

j++) {
int element = getElement(i, j);
cout << element << " ";
}
cout << endl;
}
}
};

int main() {
SparseMatrix matrixA(3, 3);
matrixA.insertElement(0, 0, 1);
matrixA.insertElement(0, 2, 2);
matrixA.insertElement(1, 1, 3);
matrixA.insertElement(2, 0, 4);
matrixA.insertElement(2, 2, 5);

SparseMatrix matrixB(3, 3);


matrixB.insertElement(0, 0, 1);
matrixB.insertElement(0, 1, 2);
matrixB.insertElement(1, 0, 3);
matrixB.insertElement(1, 2, 4);
matrixB.insertElement(2, 2, 5);

cout << "Matrix A:" << endl;


matrixA.displayMatrix();

cout << "Matrix B:" << endl;


matrixB.displayMatrix();

cout << "Matrix A + B:" << endl;


SparseMatrix matrixSum = matrixA + matrixB;
matrixSum.displayMatrix();

cout << "Matrix A - B:" << endl;


SparseMatrix matrixDiff = matrixA - matrixB;
matrixDiff.displayMatrix();

cout << "Matrix A * B:" << endl;


SparseMatrix matrixProd = matrixA * matrixB;
matrixProd.displayMatrix();

return 0;
}
In this program, the `SparseMatrix` class represents a sparse matrix using a linked
list to store only nonzero elements. The class has a private `Node` struct to
represent each nonzero element, which contains the row, column, value, and a
pointer to the next element. The `SparseMatrix` class itself has a pointer to the
head of the linked list.

The `insertElement()` function inserts a new element into the linked list at the
beginning. The `getElement()` function retrieves the value of an element given its
row and column. The `displayMatrix()` function displays the matrix by iterating
through each element and printing its value.

The class overloads the +, -, and * operators for matrix operations. These operators
take two `SparseMatrix` objects and perform the corresponding matrix operations.
The result is stored in a new `SparseMatrix` object and returned.
In the `main()` function, two `SparseMatrix` objects (`matrixA` and `matrixB`) are
created and populated with elements using the `insertElement()` function. The
matrices are then displayed using the `displayMatrix()` function.

The +, -, and * operations are demonstrated by performing these operations on


`matrixA` and `matrixB` and storing the results in new `SparseMatrix` objects
(`matrixSum`, `matrixDiff`, and `matrixProd`). The resulting matrices are then
displayed using the `displayMatrix()` function.

Exercise 6
Inheritance
Set A
1. Create base class called shape. Use this class to store two double type values
that could be used to compute the area of figures. Derive three specific classes
called triangle, circle and rectangle from the base shape. Add to the base class,
a member function get_data() to initialize base class data members and
display_area() to compute and display area. Make display_area() as a virtual
function.(Hint: **use default value for one parameter while accepting values for
shape circle.)

#include <iostream>
#include <cmath>

using namespace std;

class Shape {
protected:
double dimension1;
double dimension2;

public:
void get_data(double d1, double d2) {
dimension1 = d1;
dimension2 = d2;
}

virtual void display_area() {


cout << "Area: " << "Undefined" << endl;
}
};
class Triangle : public Shape {
public:
void display_area() override {
double area = 0.5 * dimension1 * dimension2;
cout << "Area of Triangle: " << area << endl;
}
};

class Circle : public Shape {


public:
void display_area() override {
double area = 3.14 * pow(dimension1, 2);
cout << "Area of Circle: " << area << endl;
}
};

class Rectangle : public Shape {


public:
void display_area() override {
double area = dimension1 * dimension2;
cout << "Area of Rectangle: " << area << endl;
}
};

int main() {
Triangle triangle;
triangle.get_data(5.0, 10.0);
triangle.display_area();

Circle circle;
circle.get_data(5.0, 0.0);
circle.display_area();

Rectangle rectangle;
rectangle.get_data(5.0, 10.0);
rectangle.display_area();

return 0;
}
In this program, the `Shape` class is the base class that stores two double
values representing dimensions. It provides a member function `get_data()` to
initialize these dimensions and a virtual member function `display_area()` to
compute and display the area. The `display_area()` function is made virtual to
enable dynamic polymorphism.
The `Triangle`, `Circle`, and `Rectangle` classes are derived from the `Shape`
base class. They inherit the `dimension1` and `dimension2` members from the
base class and override the `display_area()` function to compute and display the
specific areas for each shape.

In the `main()` function, objects of the derived classes (`Triangle`, `Circle`, and
`Rectangle`) are created. The `get_data()` function is called to initialize the
dimensions of each shape, and the `display_area()` function is called to compute
and display the respective areas for each shape.

2. Write a program in C++ to read the following information from the keyboard
in which the base class consists of employee name, code and designation. The
derived class Manager which contains the data members namely, year of
experience and salary. Display the whole information on the screen
#include <iostream>
#include <string>

using namespace std;

class Employee {
protected:
string name;
int code;
string designation;

public:
void get_data() {
cout << "Enter employee name: ";
getline(cin, name);

cout << "Enter employee code: ";


cin >> code;
cin.ignore(); // Ignore the newline character

cout << "Enter employee designation: ";


getline(cin, designation);
}

void display_data() {
cout << "Employee Name: " << name << endl;
cout << "Employee Code: " << code << endl;
cout << "Employee Designation: " << designation << endl;
}
};

class Manager : public Employee {


private:
int experience;
double salary;

public:
void get_data() {
Employee::get_data();

cout << "Enter years of experience: ";


cin >> experience;

cout << "Enter salary: ";


cin >> salary;
}

void display_data() {
Employee::display_data();
cout << "Years of Experience: " << experience << endl;
cout << "Salary: $" << salary << endl;
}
};

int main() {
Manager manager;

cout << "Enter Manager Information:" << endl;


manager.get_data();

cout << "\nManager Information:" << endl;


manager.display_data();

return 0;
}
In this program, the base class `Employee` contains the data members `name`,
`code`, and `designation`. It provides member functions `get_data()` to read
employee information from the keyboard and `display_data()` to display the
employee information on the screen.

The derived class `Manager` inherits from the base class `Employee` and adds the
additional data members `experience` and `salary`. It overrides the `get_data()` and
`display_data()` functions to include the manager-specific information.

In the `main()` function, an object of the `Manager` class is created. The `get_data()`
function is called to read the manager's information from the keyboard, and the
`display_data()` function is called to display the manager's information on the
screen.

-----------------------------------------------------------------------------------------------------
-------------------------
Set B
1. Design a base class person(name,address,phone_no).Derive a class
employee(e_no,ename) from person.Derive a class
manager(designation,department,basic_salary) from employee. Write a menu
driven program to
Accept all details of ‘n’ manager.
Display manager having highest salary. (Use private inheritance)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Person {
protected:
string name;
string address;
string phone_no;

public:
void get_details() {
cout << "Enter name: ";
getline(cin, name);

cout << "Enter address: ";


getline(cin, address);

cout << "Enter phone number: ";


getline(cin, phone_no);
}
};

class Employee : private Person {


protected:
string e_no;
string ename;

public:
void get_employee_details() {
get_details();

cout << "Enter employee number: ";


getline(cin, e_no);

cout << "Enter employee name: ";


getline(cin, ename);
}
};

class Manager : private Employee {


private:
string designation;
string department;
double basic_salary;

public:
void get_manager_details() {
get_employee_details();
cout << "Enter designation: ";
getline(cin, designation);

cout << "Enter department: ";


getline(cin, department);

cout << "Enter basic salary: ";


cin >> basic_salary;
cin.ignore(); // Ignore the newline character after reading basic salary
}

double get_salary() const {


return basic_salary;
}

void display_details() const {


cout << "Manager Details:" << endl;
cout << "----------------" << endl;
cout << "Name: " << name << endl;
cout << "Address: " << address << endl;
cout << "Phone number: " << phone_no << endl;
cout << "Employee number: " << e_no << endl;
cout << "Employee name: " << ename << endl;
cout << "Designation: " << designation << endl;
cout << "Department: " << department << endl;
cout << "Basic Salary: " << basic_salary << endl;
}
};

int main() {
int n;
cout << "Enter the number of managers: ";
cin >> n;
cin.ignore(); // Ignore the newline character after reading the number of
managers

vector<Manager> managers(n);

for (int i = 0; i < n; i++) {


cout << "Enter details for Manager " << i + 1 << ":" << endl;
managers[i].get_manager_details();
cout << endl;
}

double max_salary = 0;
int max_salary_index = -1;

for (int i = 0; i < n; i++) {


if (managers[i].get_salary() > max_salary) {
max_salary = managers[i].get_salary();
max_salary_index = i;
}
}

if (max_salary_index != -1) {
cout << "Manager with the highest salary: " << endl;
managers[max_salary_index].display_details();
} else {
cout << "No managers found." << endl;
}

return 0;
}
In this program, the `Person` class serves as the base class that contains
common attributes like name, address, and phone number. The `Employee`
class is derived from `Person` and adds employee-specific attributes like
employee number and employee name. Finally, the `Manager` class is derived
from `Employee` and adds manager-specific attributes like designation,
department, and basic salary.

The program prompts the user to enter the number of managers and then
accepts the details for each manager using the `get_manager_details()` function

. After that, it finds the manager with the highest salary and displays their
details using the `display_details()` function.

2. A company markets books audio tapes. Prepare a class publication having


members(title,price).From this class derive two classes
Book which adds a page count.
Tape which adds a playing time in minutes. The program should contain
following menu.
Display all books.
Display all tapes.
All books having pages>n.
All tapes having palying time>=n minutes.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Publication {
protected:
string title;
float price;

public:
Publication(const string& _title, float _price) : title(_title), price(_price) {}
virtual void display() const {
cout << "Title: " << title << endl;
cout << "Price: $" << price << endl;
}
};

class Book : public Publication {


private:
int pageCount;

public:
Book(const string& _title, float _price, int _pageCount) : Publication(_title,
_price), pageCount(_pageCount) {}

void display() const override {


Publication::display();
cout << "Page Count: " << pageCount << endl;
}
};

class Tape : public Publication {


private:
int playingTime;

public:
Tape(const string& _title, float _price, int _playingTime) : Publication(_title,
_price), playingTime(_playingTime) {}

void display() const override {


Publication::display();
cout << "Playing Time: " << playingTime << " minutes" << endl;
}
};

int main() {
vector<Publication*> publications;

// Add some books and tapes


publications.push_back(new Book("Book 1", 10.99, 200));
publications.push_back(new Book("Book 2", 12.99, 150));
publications.push_back(new Tape("Tape 1", 8.99, 60));
publications.push_back(new Tape("Tape 2", 9.99, 90));

int choice;
while (true) {
cout << "Menu:" << endl;
cout << "1. Display all books" << endl;
cout << "2. Display all tapes" << endl;
cout << "3. Filter books with page count greater than a value" << endl;
cout << "4. Filter tapes with playing time greater than or equal to a value"
<< endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Ignore the newline character after reading the choice

cout << endl;

if (choice == 1) {
cout << "All Books:" << endl;
for (const auto& publication : publications) {
Book* book = dynamic_cast<Book*>(publication);
if (book)
book->display();
}
} else if (choice == 2) {
cout << "All Tapes:" << endl;
for (const auto& publication : publications) {
Tape* tape = dynamic_cast<Tape*>(publication);
if (tape)
tape->display();
}
} else if (choice == 3) {
int pageCount;
cout << "Enter the minimum page count: ";
cin >> pageCount;

cout << "Books with page count greater than " << pageCount << ":" <<
endl;
for (const auto& publication : publications) {
Book* book = dynamic_cast<Book*>(publication);
if (book && book->getPageCount() > pageCount)
book->display();
}
} else if (choice == 4) {
int playingTime;
cout << "Enter the minimum playing time (in minutes): ";
cin >> playingTime;

cout << "Tapes with playing time greater than or equal to " <<
playingTime << " minutes

:" << endl;


for (const auto& publication : publications) {
Tape* tape = dynamic_cast<Tape*>(publication);
if (tape && tape->getPlayingTime() >= playingTime)
tape->display();
}
} else if (choice == 5) {
// Cleanup and exit
for (auto& publication : publications)
delete publication;
break;
} else {
cout << "Invalid choice. Please try again." << endl;
}

cout << endl;


}

return 0;
}

In this program, the `Publication` class is the base class, and `Book` and `Tape`
are derived classes that add specific features. The `Publication` class has a
virtual `display()` function that is overridden in the derived classes to display
additional information.

The program creates a vector to store pointers to `Publication` objects, which


can hold both `Book` and `Tape` objects. The user is presented with a menu to
display all books, all tapes, and filter books/tapes based on page count and
playing time. The menu options are implemented using a `switch` statement.

3. Design two base classes Student(roll_no,name,class) and Marks(mark[3]).


Design one derived class Result(percentage,grade).Write a menu driven program
with following options
Add the details of ‘n’ students with marks.
Display result of all students in descending order of percentage.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Student {
protected:
int rollNo;
string name;
string className;

public:
Student(int _rollNo, const string& _name, const string& _className)
: rollNo(_rollNo), name(_name), className(_className) {}

void display() const {


cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Class: " << className << endl;
}
};
class Marks {
protected:
float marks[3];

public:
Marks(float m1, float m2, float m3) {
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;
}

void display() const {


cout << "Marks: ";
for (int i = 0; i < 3; i++) {
cout << marks[i] << " ";
}
cout << endl;
}
};

class Result : public Student, public Marks {


private:
float percentage;
string grade;

public:
Result(int rollNo, const string& name, const string& className, float m1, float
m2, float m3)
: Student(rollNo, name, className), Marks(m1, m2, m3) {
calculatePercentage();
calculateGrade();
}

void calculatePercentage() {
percentage = (marks[0] + marks[1] + marks[2]) / 3.0;
}

void calculateGrade() {
if (percentage >= 90) {
grade = "A+";
} else if (percentage >= 80) {
grade = "A";
} else if (percentage >= 70) {
grade = "B";
} else if (percentage >= 60) {
grade = "C";
} else {
grade = "F";
}
}

void display() const {


Student::display();
Marks::display();
cout << "Percentage: " << percentage << endl;
cout << "Grade: " << grade << endl;
}

float getPercentage() const {


return percentage;
}
};

bool compareByPercentage(const Result* r1, const Result* r2) {


return r1->getPercentage() > r2->getPercentage();
}

int main() {
vector<Result*> results;

int choice;
while (true) {
cout << "Menu:" << endl;
cout << "1. Add student details with marks" << endl;
cout << "2. Display results of all students in descending order of percentage"
<< endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Ignore the newline character after reading the choice

cout << endl;

if (choice == 1) {
int rollNo;
string name, className;
float marks[3];

cout << "Enter Roll No: ";


cin >> rollNo;
cin.ignore();

cout << "Enter Name: ";


getline(cin, name);

cout << "Enter Class: ";


getline(cin, className);

cout << "Enter Marks (3 subjects): ";


cin >> marks[0] >> marks[1] >> marks[2];

Result* result = new Result(rollNo, name, className, marks[0], marks[1],


marks[2]);
results.push_back(result);

cout << "Student details added successfully!" << endl;


} else if (choice == 2) {
if (results.empty()) {
cout << "No student details found." << endl;
} else {
// Sort the results vector in descending order of percentage
sort(results.begin(), results.end(), compareByPercentage);

cout << "Results of all students in descending order of percentage:" <<


endl;
for (const auto& result : results) {
result->display();
cout << endl;
}
}
} else if (choice == 3) {
// Cleanup and exit
for (auto& result : results) {
delete result;
}
break;
} else {
cout << "Invalid choice. Please try again." << endl;
}

cout << endl;


}

return 0;
}
In this program, the base class `Student` represents the basic information of a
student, the base class `Marks` represents the marks of a student, and the derived
class `Result` combines both the student details and marks to calculate the
percentage and grade. The program provides a menu-driven interface to add
student details with marks and display the results of all students in descending
order of percentage. The results are stored in a vector of `Result` pointers, allowing
dynamic addition and sorting of student results. The `display()` function is
overridden in the derived class to display all relevant information.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Person {
protected:
int id;
string name;

public:
void accept() {
cout << "Enter ID: ";
cin >> id;
cin.ignore(); // Ignore the newline character after reading the ID

cout << "Enter name: ";


getline(cin, name);
}

void display() const {


cout << "ID: " << id << endl;
cout << "Name: " << name << endl;
}
};

class Teaching : public Person {


protected:
string subject;

public:
void accept() {
Person::accept();

cout << "Enter subject: ";


getline(cin, subject);
}

void display() const {


Person::display();
cout << "Subject: " << subject << endl;
}
};

class NonTeaching : public Person {


protected:
string department;

public:
void accept() {
Person::accept();

cout << "Enter department: ";


getline(cin, department);
}

void display() const {


Person::display();
cout << "Department: " << department << endl;
}
};

class Instructor : public Person {


public:
void accept() {
Person::accept();
}

void display() const {


Person::display();
}
};

int main() {
int n;
cout << "Enter the number of instructors: ";
cin >> n;
cin.ignore(); // Ignore the newline character after reading the number

vector<Instructor> instructors(n);

for (int i = 0; i < n; i++) {


cout << "Enter details for Instructor " << i + 1 << ":" << endl;
instructors[i].accept();
}

cout << endl;


cout << "Details of Instructors:" << endl;

for (const auto& instructor : instructors) {


instructor.display();
cout << endl;
}

return 0;
}

In this updated program, the base class `Person` represents the common attributes
of a person, such as ID and name. The derived class `Teaching` inherits from
`Person` and adds an additional attribute called `subject`. The derived class
`NonTeaching` also inherits from `Person` and adds an additional attribute called
`department`. The derived class `Instructor` directly inherits from `Person` without
any additional attributes.

The program allows the user to input the number of instructors and their details.
The instructors are stored in a vector of `Instructor` objects. The `accept()` and
`display()` functions are overridden in the appropriate derived classes to handle
their specific attributes. Finally, the program displays the details of all the
instructors by iterating through the vector and calling the `display()` function for
each object.

Exercise 7
File I/O
Set A
1. Write a program to count the number of characters, number of words and
number of lines in a file.
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
string filename;
cout << "Enter the filename: ";
getline(cin, filename);

ifstream file(filename);

if (!file) {
cout << "Error opening file." << endl;
return 1;
}

int charCount = 0;
int wordCount = 0;
int lineCount = 0;
string line;

while (getline(file, line)) {


lineCount++;

// Count characters
charCount += line.length();

// Count words
size_t pos = 0;
while (pos != string::npos) {
pos = line.find_first_not_of(" \t\n", pos); // Skip leading whitespace
if (pos != string::npos) {
pos = line.find_first_of(" \t\n", pos); // Find the next word
wordCount++;
}
}
}

file.close();

cout << "Number of characters: " << charCount << endl;


cout << "Number of words: " << wordCount << endl;
cout << "Number of lines: " << lineCount << endl;

return 0;
}

In this program, we first prompt the user to enter the filename. Then, we open
the file using an `ifstream` object. If the file fails to open, we display an error
message and return from the program.

We use three variables (`charCount`, `wordCount`, and `lineCount`) to keep


track of the respective counts. We read the file line by line using the `getline`
function, incrementing the line count at each iteration.

For each line, we count the number of characters by adding the length of the
line to `charCount`.
To count the words, we use a loop and the `find_first_not_of` and `find_first_of`
functions. We start by skipping any leading whitespace using `find_first_not_of`.
Then, we continue finding the next occurrence of whitespace or newline using
`find_first_of`, incrementing the word count each time.

Finally, we close the file and display the counts of characters, words, and lines.

-------------------------------------------------------------------------------------------------
------------

2. write a single file handling program in c++ to reading and writing data on a file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
string filename = "data.txt";

// Writing data to file


ofstream outputFile(filename);

if (!outputFile) {
cout << "Error creating file." << endl;
return 1;
}

outputFile << "Hello, World!" << endl;


outputFile << "This is a sample text." << endl;
outputFile << "Writing data to a file." << endl;

outputFile.close();
cout << "Data written to the file successfully." << endl;

// Reading data from file


ifstream inputFile(filename);

if (!inputFile) {
cout << "Error opening file." << endl;
return 1;
}

string line;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();

return 0;
}

In this program, we first define a `filename` variable to store the name of the file we
want to read from and write to (in this example, "data.txt").

To write data to the file, we create an `ofstream` object named `outputFile` and
open the file using that object. We check if the file was successfully created and if
not, display an error message and return from the program. We then use the `<<`
operator to write data to the file. In this example, we write three lines of text to the
file. Finally, we close the output file.

To read data from the file, we create an `ifstream` object named `inputFile` and
open the file using that object. We check if the file was successfully opened and if
not, display an error message and return from the program. We then use the
`getline` function to read each line from the file and display it on the console.
Finally, we close the input file.

Note: This program assumes that the file "data.txt" exists in the same directory as
the program. Make sure to create the file beforehand or modify the `filename`
variable to point to an existing file.

3. Write a user-defined function in C++ to read the content from a text file
OUT.TXT, count and display the number of alphabets, words and lines present
in it.

#include <iostream>
#include <fstream>
#include <cctype>

using namespace std;

void countAlphabetsWordsLines(const string& filename) {


ifstream inputFile(filename);

if (!inputFile) {
cout << "Error opening file." << endl;
return;
}

char ch;
int alphabetCount = 0;
int wordCount = 0;
int lineCount = 0;
bool isWord = false;

while (inputFile.get(ch)) {
if (isalpha(ch)) {
alphabetCount++;
}

if (!isspace(ch) && !isWord) {


isWord = true;
wordCount++;
}

if (ch == '\n') {
lineCount++;
isWord = false;
}
}

inputFile.close();

cout << "Number of Alphabets: " << alphabetCount << endl;


cout << "Number of Words: " << wordCount << endl;
cout << "Number of Lines: " << lineCount << endl;
}

int main() {
string filename = "OUT.txt";
countAlphabetsWordsLines(filename);

return 0;
}

In this program, we define a function `countAlphabetsWordsLines` that takes the


filename as a parameter. Inside the function, we create an `ifstream` object named
`inputFile` and open the file using that object. We check if the file was successfully
opened and if not, display an error message and return from the function.

We declare variables to keep track of the alphabet count, word count, line count,
and a boolean flag to check if a word is encountered. We iterate through each
character in the file using the `get` function. If the character is an alphabet, we
increment the `alphabetCount`. If the character is not a space and `isWord` is false,
we set `isWord` to true and increment the `wordCount`. If the character is a newline
character (`\n`), we increment the `lineCount` and set `isWord` to false.

After counting the alphabets, words, and lines, we close the input file and display
the results.

-----------------------------------------------------------------------------------------------------
-----------------------------

Set B
1. Assuming that a text file named FIRST.TXT contains some text written into it,
write a function named copyupper(), that reads the file FIRST.TXT and creates a
new file named SECOND.TXT contains all words from the file FIRST.TXT in
uppercase.
#include <iostream>
#include <fstream>
#include <cctype>

using namespace std;

void copyUpper() {
ifstream inputFile("FIRST.TXT");
ofstream outputFile("SECOND.TXT");

if (!inputFile) {
cout << "Error opening input file." << endl;
return;
}

if (!outputFile) {
cout << "Error creating output file." << endl;
inputFile.close();
return;
}

string word;

while (inputFile >> word) {


for (char& ch : word) {
ch = toupper(ch);
}
outputFile << word << " ";
}

inputFile.close();
outputFile.close();

cout << "Copying completed successfully." << endl;


}

int main() {
copyUpper();

return 0;
}

In this program, we define a function `copyUpper()` that reads the input file
"FIRST.TXT" and creates an output file "SECOND.TXT". Inside the function, we
create an `ifstream` object named `inputFile` and open the input file. We also
create an `ofstream` object named `outputFile` and open the output file. If there
are any errors opening the files, we display an error message, close the files,
and return from the function.

We then use a `while` loop to read each word from the input file using the `>>`
operator. For each word, we iterate through each character and convert it to
uppercase using the `toupper()` function from the `<cctype>` library. We write
the uppercase word followed by a space into the output file.
After processing all the words, we close both the input and output files and
display a success message.

2. Given the following class declaration, class myFile

{
fstream in_out; public:
myfiile(char * fname);
void display() // reads the files
void append(); // append a character to a file void fileclose(); // close the file
}
Write a menu driven program with the following options
Dislay
Append
Exit
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

class myFile {
fstream in_out;

public:
myFile(char* fname);
void display();
void append();
void fileclose();
};

myFile::myFile(char* fname) {
in_out.open(fname, ios::in | ios::out | ios::app);
}

void myFile::display() {
char ch;
in_out.seekg(0, ios::beg);

while (in_out.get(ch)) {
cout << ch;
}
}

void myFile::append() {
char ch;
cin.ignore();
cout << "Enter a character to append to the file: ";
cin.get(ch);
in_out.seekp(0, ios::end);
in_out.put(ch);
}

void myFile::fileclose() {
in_out.close();
}

int main() {
char filename[100];
char choice;
bool exitProgram = false;

cout << "Enter the file name: ";


cin.getline(filename, 100);

myFile file(filename);

while (!exitProgram) {
cout << "\nMenu:" << endl;
cout << "1. Display" << endl;
cout << "2. Append" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case '1':
file.display();
break;
case '2':
file.append();
break;
case '3':
file.fileclose();
exitProgram = true;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
}

return 0;
}
In this program, the `myFile` class is defined with a constructor that takes a
filename as an argument and opens the file in both input and output modes.

The `display()` member function reads the contents of the file and displays them on
the console. It uses the `seekg()` function to set the get position to the beginning of
the file, and then reads each character using `get()`.

The `append()` member function prompts the user to enter a character and
appends it to the end of the file. It uses `seekp()` to set the put position to the end
of the file, and then uses `put()` to write the character.

The `fileclose()` member function simply closes the file.


In the `main()` function, a menu is displayed with three options: "Display",
"Append", and "Exit". The user is prompted to enter their choice, and based on the
input, the corresponding member function of the `myFile` object is called.

The program continues to display the menu and accept user input until the user
chooses to exit by selecting the "Exit" option.

3. Write a C++ program to create a text file which stores employee.


Objects(emp_id, emp_name, emp_sal). Write a menu driven program with the
options
Append
Modify
Delete
Display
Exit

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class Employee {
public:
int emp_id;
string emp_name;
double emp_sal;

void readData() {
cout << "Enter Employee ID: ";
cin >> emp_id;
cin.ignore();

cout << "Enter Employee Name: ";


getline(cin, emp_name);

cout << "Enter Employee Salary: ";


cin >> emp_sal;
}

void displayData() {
cout << "Employee ID: " << emp_id << endl;
cout << "Employee Name: " << emp_name << endl;
cout << "Employee Salary: " << emp_sal << endl;
cout << "-------------------------------" << endl;
}
};

void appendToFile(const string& filename, const Employee& employee) {


ofstream outFile(filename, ios::app);
if (!outFile) {
cout << "Error opening the file." << endl;
return;
}

outFile << employee.emp_id << "," << employee.emp_name << "," <<
employee.emp_sal << endl;

cout << "Employee data appended to the file." << endl;

outFile.close();
}

vector<Employee> readFromFile(const string& filename) {


vector<Employee> employees;
ifstream inFile(filename);

if (!inFile) {
cout << "Error opening the file." << endl;
return employees;
}

Employee employee;
string line;

while (getline(inFile, line)) {


size_t commaPos1 = line.find(",");
size_t commaPos2 = line.find(",", commaPos1 + 1);

employee.emp_id = stoi(line.substr(0, commaPos1));


employee.emp_name = line.substr(commaPos1 + 1, commaPos2 - commaPos1
- 1);
employee.emp_sal = stod(line.substr(commaPos2 + 1));

employees.push_back(employee);
}

inFile.close();

return employees;
}

void displayEmployees(const vector<Employee>& employees) {


for (const auto& employee : employees) {
employee.displayData();
}
}

void modifyEmployee(vector<Employee>& employees, int empId) {


for (auto& employee : employees) {
if (employee.emp_id == empId) {
cout << "Enter new details for the employee with ID " << empId << ":" <<
endl;
employee.readData();
cout << "Employee details modified successfully." << endl;
return;
}
}

cout << "Employee with ID " << empId << " not found." << endl;
}

void deleteEmployee(vector<Employee>& employees, int empId) {


for (auto it = employees.begin(); it != employees.end(); ++it) {
if (it->emp_id == empId) {
employees.erase(it);
cout << "Employee with ID " << empId << " deleted successfully." << endl;
return;
}
}

cout << "Employee with ID " << empId << " not found." << endl;
}

int main() {
string filename = "employee.txt";
vector<Employee> employees = readFromFile(filename);
int choice;
bool exitProgram = false;

while (!exitProgram) {
cout << "Menu:" << endl;
cout << "1. Append Employee" << endl;
cout << "2. Modify Employee" << endl;
cout << "3. Delete Employee" <<

endl;
cout << "4. Display Employees" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
Employee employee;
employee.readData();
appendToFile(filename, employee);
break;
}
case 2: {
int empId;
cout << "Enter the Employee ID to modify: ";
cin >> empId;
modifyEmployee(employees, empId);
break;
}
case 3: {
int empId;
cout << "Enter the Employee ID to delete: ";
cin >> empId;
deleteEmployee(employees, empId);
break;
}
case 4:
displayEmployees(employees);
break;
case 5:
exitProgram = true;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
}

return 0;
}

In this program, the `Employee` class represents an employee object with emp_id,
emp_name, and emp_sal as its members. The class provides member functions to
read and display employee data.

The `appendToFile()` function appends an `Employee` object's data to the specified


file. It opens the file in append mode and writes the employee data in the format
"emp_id,emp_name,emp_sal" to a new line.

The `readFromFile()` function reads data from the specified file and returns a vector
of `Employee` objects. It reads each line from the file, splits it using the comma as a
delimiter, and creates `Employee` objects from the parsed data.

The `displayEmployees()` function displays the details of all employees present in


the vector.

The `modifyEmployee()` function searches for an employee with a specific empId


and modifies their details if found.

The `deleteEmployee()` function searches for an employee with a specific empId and
removes them from the vector if found.

In the `main()` function, a menu is displayed with five options: "Append Employee",
"Modify Employee", "Delete Employee", "Display Employees", and "Exit". The user
can choose an option, and based on the input, the corresponding function is called.

The program continues to display the menu and accept user input until the user
chooses to exit by selecting the "Exit" option.

-----------------------------------------------------------------------------------------------------
------------------
Set C
1. A file contains a list of telephone numbers in the following form:
Ajay 12345
Vijay 98765
The names contain only one word and the names and telephone numbers are
separated by white spaces. Write a program to read the file and output the list
in two columns. The names should be left-justified and the numbers right-
justified.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

void formatTelephoneNumbers(const string& filename) {


ifstream inFile(filename);

if (!inFile) {
cout << "Error opening the file." << endl;
return;
}

string name, number;

while (inFile >> name >> number) {


cout << left << setw(10) << name << " " << right << setw(10) << number <<
endl;
}

inFile.close();
}

int main() {
string filename = "telephone_numbers.txt";
formatTelephoneNumbers(filename);

return 0;
}
```

In this program, the `formatTelephoneNumbers()` function takes the filename as


an argument and reads the file line by line. For each line, it extracts the name
and number using the `>>` operator and outputs them in two columns using
the `setw()` function.

The `left` and `right` manipulators are used to set the alignment of the output.
`left` ensures that the names are left-justified, while `right` ensures that the
numbers are right-justified.

In the `main()` function, the filename is provided as "telephone_numbers.txt".


You can modify this to match the actual filename or provide a different
filename. The `formatTelephoneNumbers()` function is then called to process the
file and output the formatted list of telephone numbers.
Note: Make sure to include the necessary header files (`<iostream>`,
`<fstream>`, `<iomanip>`, `<string>`) and compile the program with a C++
compiler.

2. Write an interactive, menu-driven program that will access the file created in
the above program, and implement the following tasks.
Determine the telephone number of the specified person.
Determine the name if a telephone number is known.
Update the telephone number, whenever there is a change.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

struct Contact {
string name;
string number;
};

void displayMenu() {
cout << "Menu:" << endl;
cout << "1. Determine telephone number of a person" << endl;
cout << "2. Determine name if a telephone number is known" << endl;
cout << "3. Update telephone number" << endl;
cout << "4. Exit" << endl;
}

void determinePhoneNumber(const string& filename) {


string name;
cout << "Enter the name of the person: ";
cin.ignore();
getline(cin, name);

ifstream inFile(filename);

if (!inFile) {
cout << "Error opening the file." << endl;
return;
}

string line;
bool found = false;

while (getline(inFile, line)) {


stringstream ss(line);
string storedName, number;
ss >> storedName >> number;
if (storedName == name) {
cout << "Telephone number of " << name << " is " << number << endl;
found = true;
break;
}
}

if (!found) {
cout << "Person not found." << endl;
}

inFile.close();
}

void determineName(const string& filename) {


string number;
cout << "Enter the telephone number: ";
cin >> number;

ifstream inFile(filename);

if (!inFile) {
cout << "Error opening the file." << endl;
return;
}

string line;
bool found = false;

while (getline(inFile, line)) {


stringstream ss(line);
string name, storedNumber;
ss >> name >> storedNumber;

if (storedNumber == number) {
cout << "Name associated with the telephone number " << number << " is "
<< name << endl;
found = true;
break;
}
}

if (!found) {
cout << "Telephone number not found." << endl;
}

inFile.close();
}

void updatePhoneNumber(const string& filename) {


string name;
cout << "Enter the name of the person: ";
cin.ignore();
getline(cin, name);

ifstream inFile(filename);
ofstream outFile("temp.txt");

if (!inFile || !outFile) {
cout << "Error opening the file." << endl;
return;
}

string line;
bool found = false;

while (getline(inFile, line)) {


stringstream ss(line);
string storedName, number;
ss >> storedName >> number;

if (storedName == name) {
cout << "Enter the new telephone number: ";
cin >> number;
transform(number.begin(), number.end(), number.begin(), ::toupper);
outFile << storedName << " " << number << endl;
cout << "Telephone number updated successfully." << endl;
found = true;
} else {
outFile << line << endl;
}
}

if (!found) {
cout << "Person not found." << endl;
}

inFile.close();
outFile.close();

remove(filename.c_str());
rename("temp.txt", filename.c_str());
}

int main() {
string filename = "telephone_numbers.txt";
int choice;

while (true) {
displayMenu();
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
determinePhoneNumber(filename);
break;
case 2:
determineName(filename);
break;
case 3:
updatePhoneNumber(filename);
break;
case 4:
cout << "Exiting the program. Goodbye!" << endl;
return 0;
default:
cout << "Invalid choice. Please try again." << endl;
}

cout << endl;


}

return 0;
}

In this updated program, a menu-driven approach is implemented using a `while`


loop. The `displayMenu()` function shows the available options to the user.
Depending on the user's choice, the program calls the appropriate function to
perform the desired task.

1. `determinePhoneNumber()`: Prompts the user to enter a name and searches for


the corresponding telephone number in the file.
2. `determineName()`: Prompts the user to enter a telephone number and searches
for the corresponding name in the file.
3. `updatePhoneNumber()`: Prompts the user to enter a name, searches for the
corresponding entry in the file, and allows the user to update the telephone
number associated with that name.

The program reads and writes to the file specified by the `filename` variable. Make
sure to adjust this variable to match the actual filename or provide a different
filename.

Note: Make sure to include the necessary header files (`<iostream>`, `<fstream>`,
`<string>`, `<sstream>`, `<algorithm>`) and compile the program with a C++
compiler.

You might also like