0% found this document useful (0 votes)
46 views66 pages

CPP File Program

Uploaded by

deepakkadhane85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views66 pages

CPP File Program

Uploaded by

deepakkadhane85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Q.

1) Write a C++ program to declare a class Student containing data members roll_no and
percentage. Accept this data for 2 objects and display the roll_no of the student having highest
percentage.
#include <iostream>
using namespace std;
class Student {
public:
int roll_no;
float percentage;

// Method to accept student data


void getData() {
cout << "Enter roll number: ";
cin >> roll_no;
cout << "Enter percentage: ";
cin >> percentage;
}
};

int main() {
Student s1, s2;

cout << "Enter details for Student 1:" << endl;


s1.getData();

cout << "\nEnter details for Student 2:" << endl;


s2.getData();

cout << "\nStudent with highest percentage is: ";


if (s1.percentage > s2.percentage) {
cout << "Roll No: " << s1.roll_no << endl;
} else if (s2.percentage > s1.percentage) {
cout << "Roll No: " << s2.roll_no << endl;
} else {
cout << "Both students have the same percentage." << endl;
}

return 0;
}

Q.2) Write a C++ program to create an inline function that returns the length of a given string.

#include <iostream>
#include <string>
using namespace std;
// Inline function to get the length of a string
inline int getLength(const string& str) {
return str.length();
}
int main() {
string input;
cout << "Enter a string: ";
getline(cin, input); // Read full line including spaces
int len = getLength(input);
cout << "Length of the string is: " << len << endl;
return 0;
}

Q.3) Write a C++ program that reads Book.txt file and displays Books data on the screen.

#include <iostream>
#include <fstream> // For file handling
#include <string> // For using string
using namespace std;

int main() {
ifstream file("Book.txt"); // Open the file for reading

if (!file) {
cerr << "Error: Could not open Book.txt file." << endl;
return 1; // Exit with error
}

string line;
cout << "Contents of Book.txt:" << endl;
cout << "----------------------" << endl;

while (getline(file, line)) {


cout << line << endl;
}

file.close(); // Close the file


return 0;
}

Q.4) Write a program using unordered_map to store and display the names of 3 students with their roll
numbers.

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

int main() {
unordered_map<int, string> students;

// Input data for 3 students


for (int i = 0; i < 3; ++i) {
int roll;
string name;

cout << "Enter roll number for student " << i + 1 << ": ";
cin >> roll;
cin.ignore(); // To clear the newline from the input buffer
cout << "Enter name for student " << i + 1 << ": ";
getline(cin, name);

students[roll] = name;
}

// Display student data


cout << "\nStudent Roll Numbers and Names:\n";
cout << "--------------------------------\n";
for (const auto& entry : students) {
cout << "Roll No: " << entry.first << " | Name: " << entry.second << endl;
}

return 0;
}

Q.5) Write a program to define a class Cube with following members – length, width, depth and volume
(). Write code for the function volume which calculates volume of a cube.

#include <iostream>
using namespace std;
class Cube {
private:
float length, width, depth;
public:
// Function to input dimensions
void getData() {
cout << "Enter length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
cout << "Enter depth: ";
cin >> depth;
}

// Function to calculate and return volume


float volume() {
return length * width * depth;
}
};
int main() {
Cube c;
c.getData(); // Input cube dimensions
float vol = c.volume(); // Calculate volume
cout << "Volume of the cube is: " << vol << endl;
return 0;
}

Q.6) Write a C++ program using class to calculate simple interest amount. (Use parameterized
constructor with default value for rate).

#include <iostream>
using namespace std;

class SimpleInterest {
private:
float principal;
float time;
float rate;
float interest;

public:
// Parameterized constructor with default value for rate
SimpleInterest(float p, float t, float r = 5.0) {
principal = p;
time = t;
rate = r;
interest = (principal * time * rate) / 100;
}

// Function to display interest


void display() {
cout << "Principal: " << principal << endl;
cout << "Time: " << time << " years" << endl;
cout << "Rate: " << rate << "%" << endl;
cout << "Simple Interest: " << interest << endl;
}
};

int main() {
float p, t, r;
cout << "Enter principal amount: ";
cin >> p;
cout << "Enter time (in years): ";
cin >> t;
cout << "Enter rate of interest (or press 0 to use default 5%): ";
cin >> r;
if (r == 0) {
SimpleInterest si(p, t); // Uses default rate
si.display();
} else {
SimpleInterest si(p, t, r); // Uses provided rate
si.display();
}
return 0;
}

Q.7).Design a base class Product (Product _Id, Product _Name, Price). Derive a class Discount
(Discount_In_Percentage) from Product. A customer buys ‘n’ Products. Calculate total price, total
discount and display bill using appropriate manipulators.

#include <iostream>
#include <iomanip> // For manipulators
#include <string>
using namespace std;

// Base class
class Product {
protected:
int product_id;
string product_name;
float price;

public:
void getProductData() {
cout << "Enter Product ID: ";
cin >> product_id;
cin.ignore(); // Clear newline character
cout << "Enter Product Name: ";
getline(cin, product_name);
cout << "Enter Product Price: ";
cin >> price;
}

float getPrice() const {


return price;
}
void displayProductData() const {
cout << setw(10) << product_id
<< setw(20) << product_name
<< setw(10) << fixed << setprecision(2) << price;
}
};

// Derived class
class Discount : public Product {
private:
float discount_percent;

public:
void getDiscountData() {
getProductData();
cout << "Enter Discount (%): ";
cin >> discount_percent;
}

float calculateDiscountAmount() const {


return (price * discount_percent) / 100;
}

float calculateFinalPrice() const {


return price - calculateDiscountAmount();
}

void displayBillRow() const {


displayProductData();
cout << setw(10) << discount_percent
<< setw(12) << calculateDiscountAmount()
<< setw(12) << calculateFinalPrice()
<< endl;
}
};
int main() {
int n;
cout << "Enter number of products: ";
cin >> n;
Discount* products = new Discount[n]; // Dynamically allocate array
// Input data for each product
for (int i = 0; i < n; ++i) {
cout << "\nEnter details for Product " << i + 1 << ":" << endl;
products[i].getDiscountData();
}

// Display bill
float total_price = 0, total_discount = 0;
cout << "\n\n---------------------------- BILL ----------------------------\n";
cout << setw(10) << "Prod_ID"
<< setw(20) << "Prod_Name"
<< setw(10) << "Price"
<< setw(10) << "Disc(%)"
<< setw(12) << "Discount"
<< setw(12) << "FinalPrice" << endl;
cout << "-------------------------------------------------------------\n";
for (int i = 0; i < n; ++i) {
products[i].displayBillRow();
total_price += products[i].getPrice();
total_discount += products[i].calculateDiscountAmount();
}
float total_final = total_price - total_discount;
cout << "-------------------------------------------------------------\n";
cout << setw(30) << "TOTAL"
<< setw(10) << ""
<< setw(12) << total_discount
<< setw(12) << total_final << endl;

// Clean up
delete[] products;

return 0;
}

Q.8) Write a program to define a class ‘Rectangle’ having data members length and breadth. Accept this
data for one object and display area and perimeter of rectangle.

#include <iostream>
using namespace std;
class Rectangle {
private:
float length;
float breadth;
public:
// Function to accept length and breadth
void getData() {
cout << "Enter length: ";
cin >> length;
cout << "Enter breadth: ";
cin >> breadth;
}
// Function to calculate area
float area() {
return length * breadth;
}
// Function to calculate perimeter
float perimeter() {
return 2 * (length + breadth);
}
// Function to display area and perimeter
void display() {
cout << "Area of rectangle: " << area() << endl;
cout << "Perimeter of rectangle: " << perimeter() << endl;
}
};
int main() {
Rectangle rect;
rect.getData(); // Accept input
rect.display(); // Display area and perimeter

return 0;
}

9) Write a program to declare a class Product containing data members product_code , name and price.
Accept and display this information for 2 objects.

#include <iostream>
using namespace std;
class Product {
private:
string product_code;
string name;
float price;
public:
void accept() {
cout << "Enter product code: ";
cin >> product_code;
cout << "Enter product name: ";
cin.ignore(); // To clear the newline left in buffer
getline(cin, name);
cout << "Enter product price: ";
cin >> price;
}
void display() {
cout << "Product Code: " << product_code << endl;
cout << "Product Name: " << name << endl;
cout << "Product Price: ₹" << price << endl;
cout << "-----------------------------" << endl;
}
};

int main() {
Product p1, p2;
cout << "Enter details for Product 1:\n";
p1.accept();
cout << "\nEnter details for Product 2:\n";
p2.accept();
cout << "\n--- Product Details ---\n";
cout << "Product 1:\n";
p1.display();
cout << "Product 2:\n";
p2.display();
return 0;
}

10) Write a C++ program to create a class Mobile which contains data members as Mobile_Id,
Mobile_Name, Mobile_Price. Create and initialize all values of Mobile object by using parameterized
constructor. Display the values of Mobile object where Mobile_price should be right justified with a
precision of two digits.

#include <iostream>
#include <iomanip> // For formatting output
using namespace std;
class Mobile {
private:
int Mobile_Id;
string Mobile_Name;
float Mobile_Price;
public:
// Parameterized constructor
Mobile(int id, string name, float price) {
Mobile_Id = id;
Mobile_Name = name;
Mobile_Price = price;
}
// Display function
void display() {
cout << "Mobile ID : " << Mobile_Id << endl;
cout << "Mobile Name : " << Mobile_Name << endl;

// Right justify price with precision of 2 digits


cout << "Mobile Price : ₹"
<< right << fixed << setprecision(2) << setw(10)
<< Mobile_Price << endl;
}
};
int main() {
// Create object using parameterized constructor
Mobile m1(101, "Samsung Galaxy", 22999.50);
cout << "--- Mobile Details ---" << endl;
m1.display();
return 0;
}

11) WAP Create a class Person with data members name and age. Derive a class Student from Person
that adds roll_no and marks. Display all information using a function.

#include <iostream>
using namespace std;

// Base class
class Person {
protected:
string name;
int age;

public:
void acceptPersonData() {
cout << "Enter name: ";
getline(cin, name);
cout << "Enter age: ";
cin >> age;
}

void displayPersonData() {
cout << "Name: " << name << endl;
cout << "Age : " << age << endl;
}
};

// Derived class
class Student : public Person {
private:
int roll_no;
float marks;

public:
void acceptStudentData() {
acceptPersonData();
cout << "Enter roll number: ";
cin >> roll_no;
cout << "Enter marks: ";
cin >> marks;
}

void displayStudentData() {
cout << "\n--- Student Details ---\n";
displayPersonData();
cout << "Roll Number: " << roll_no << endl;
cout << "Marks : " << marks << endl;
}
};

int main() {
Student s;
cin.ignore(); // Clear input buffer before getline
s.acceptStudentData();
s.displayStudentData();

return 0;
}

12) Write a C++ program to print area of circle, square using inline function.
#include <iostream>
#define PI 3.1416
using namespace std;
// Inline function to calculate area of a circle
inline float areaOfCircle(float radius) {
return PI * radius * radius;
}
// Inline function to calculate area of a square
inline float areaOfSquare(float side) {
return side * side;
}
int main() {
float radius, side;
cout << "Enter radius of the circle: ";
cin >> radius;
cout << "Enter side of the square: ";
cin >> side;
// Call inline functions
cout << "\n--- Area Calculations ---" << endl;
cout << "Area of Circle : " << areaOfCircle(radius) << endl;
cout << "Area of Square : " << areaOfSquare(side) << endl;
return 0;
}

13) Write a C++ program to calculate area of cone, sphere and circle by using function overloading.
#include <iostream>
#include <cmath> // for sqrt()
#define PI 3.1416
using namespace std;

// Function to calculate area of circle


float area(float radius) {
return PI * radius * radius;
}

// Function to calculate surface area of sphere


float area(double radius) {
return 4 * PI * radius * radius;
}

// Function to calculate surface area of cone


float area(float radius, float height) {
float slantHeight = sqrt(radius * radius + height * height);
return PI * radius * (radius + slantHeight);
}

int main() {
float r1, h, r2;

cout << "Enter radius for circle: ";


cin >> r1;

cout << "Enter radius for cone: ";


cin >> r2;
cout << "Enter height for cone: ";
cin >> h;

double r3;
cout << "Enter radius for sphere: ";
cin >> r3;

// Function calls
cout << "\n--- Area Calculations ---" << endl;
cout << "Area of Circle : " << area(r1) << endl;
cout << "Surface Area of Cone : " << area(r2, h) << endl;
cout << "Surface Area of Sphere: " << area(r3) << endl;

return 0;
}

14) Write a program to find sum of numbers between 1 to n using constructor where value of n will be
passed to the constructor.
#include <iostream>
using namespace std;

class SumCalculator {
private:
int n;
int sum;
public:
// Constructor with parameter
SumCalculator(int number) {
n = number;
sum = 0;

// Calculate sum from 1 to n


for (int i = 1; i <= n; ++i) {
sum += i;
}
}

// Function to display the result


void displaySum() {
cout << "Sum of numbers from 1 to " << n << " is: " << sum << endl;
}
};

int main() {
int n;

cout << "Enter the value of n: ";


cin >> n;

// Create object and pass value to constructor


SumCalculator calc(n);

// Display result
calc.displaySum();

return 0;
}

15) Write a C++ program to create an inline function to calculate the area of a rectangle with default
value for width.
#include <iostream>
using namespace std;

// Inline function to calculate area of rectangle


inline float area(float length, float width = 5.0) {
return length * width;
}

int main() {
float length1, width1;

cout << "Enter length of rectangle: ";


cin >> length1;
// Optional: ask user for width or use default
char choice;
cout << "Do you want to enter width? (y/n): ";
cin >> choice;

if (choice == 'y' || choice == 'Y') {


cout << "Enter width: ";
cin >> width1;
cout << "Area of rectangle: " << area(length1, width1) << endl;
} else {
cout << "Using default width = 5.0" << endl;
cout << "Area of rectangle: " << area(length1) << endl;
}

return 0;
}
16) Write a program that counts the frequency of each character in a user-entered string using
unordered_map.
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int main() {
string input;
unordered_map<char, int> freq;

cout << "Enter a string: ";


getline(cin, input); // To allow spaces

// Count frequency of each character


for (char ch : input) {
freq[ch]++;
}

// Display frequencies
cout << "\nCharacter Frequencies:\n";
for (auto pair : freq) {
cout << "'" << pair.first << "' : " << pair.second << endl;
}

return 0;
}

17) ) Write a C++ program to count the number of words in the given file

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

int main() {
string filename = "input.txt"; // You can change this to your file name
ifstream file(filename);

if (!file) {
cout << "Failed to open the file: " << filename << endl;
return 1; // Exit with error code
}

string word;
int wordCount = 0;

// Read file word by word


while (file >> word) {
wordCount++;
}
file.close();
cout << "Number of words in the file '" << filename << "' is: " << wordCount << endl;
return 0;

18) Write a C++ program to define a class Product with data members: productCode, productName, and
weight. Accept the details of a product from the user. If weight > 100, then throw an exception and
display a proper error message. Otherwise, display the product details.
#include <iostream>
#include <string>
using namespace std;

class Product {
private:
string productCode;
string productName;
float weight;

public:
void accept() {
cout << "Enter product code: ";
getline(cin, productCode);

cout << "Enter product name: ";


getline(cin, productName);

cout << "Enter weight: ";


cin >> weight;
if (weight > 100) {
throw runtime_error("Error: Weight cannot be more than 100.");
}
}

void display() {
cout << "\nProduct Details:" << endl;
cout << "Code : " << productCode << endl;
cout << "Name : " << productName << endl;
cout << "Weight: " << weight << endl;
}
};

int main() {
Product p;

try {
p.accept();
p.display();
} catch (runtime_error& e) {
cout << e.what() << endl;
}
return 0;
}

19Write a C++ program to create a class Integer. Write a C++ program to implement necessary member
functions to overload the operator unary pre and post decrement ‘--’ for an integer number

#include <iostream>
using namespace std;

class Integer {
private:
int value;

public:
Integer(int v) : value(v) {}

// Display function
void display() {
cout << "Value = " << value << endl;
}

// Pre-decrement: --obj
Integer& operator--() {
--value; // decrement value first
return *this;
}
// Post-decrement: obj--
Integer operator--(int) {
Integer temp = *this; // save current state
value--; // decrement value after
return temp; // return old state
}
};

int main() {
Integer num(10);

cout << "Initial: ";


num.display();

cout << "After pre-decrement (--num): ";


--num;
num.display();

cout << "After post-decrement (num--): ";


num--;
num.display();

return 0;
}

20) Write a program that reads two integers and divides the first by the second. Use exception handling
to catch division by zero.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two integers (a and b): ";
cin >> a >> b;

try {
if (b == 0) {
throw runtime_error("Error: Division by zero is not allowed.");
}
int result = a / b;
cout << "Result of " << a << " / " << b << " = " << result << endl;
}
catch (runtime_error& e) {
cout << e.what() << endl;
}
return 0;
}
21) Create a C++ class Integer that contains one integer data member. Overload following binary
operators (+, -, *, /).
#include <iostream>
using namespace std;

class Integer {
private:
int value;

public:
// Constructor
Integer(int v = 0) : value(v) {}

// Getter to display value


int getValue() const {
return value;
}

// Operator overloads

// Addition
Integer operator+(const Integer& rhs) const {
return Integer(value + rhs.value);
}

// Subtraction
Integer operator-(const Integer& rhs) const {
return Integer(value - rhs.value);
}

// Multiplication
Integer operator*(const Integer& rhs) const {
return Integer(value * rhs.value);
}

// Division
Integer operator/(const Integer& rhs) const {
if (rhs.value == 0) {
throw runtime_error("Error: Division by zero.");
}
return Integer(value / rhs.value);
}
};

int main() {
try {
Integer a(20), b(5);
Integer c = a + b;
cout << "a + b = " << c.getValue() << endl;

Integer d = a - b;
cout << "a - b = " << d.getValue() << endl;

Integer e = a * b;
cout << "a * b = " << e.getValue() << endl;

Integer f = a / b;
cout << "a / b = " << f.getValue() << endl;
}
catch (runtime_error& e) {
cout << e.what() << endl;
}

return 0;
}
22) Write a C++ program to read a text file and count number of Uppercase Alphabets, Lowercase
Alphabets, Digits and Spaces in it using File Handling.
#include <iostream>
#include <fstream>
#include <cctype> // for isupper, islower, isdigit
using namespace std;

int main() {
string filename = "input.txt"; // Change as needed
ifstream file(filename);

if (!file) {
cout << "Cannot open file: " << filename << endl;
return 1;
}

char ch;
int uppercaseCount = 0, lowercaseCount = 0, digitCount = 0, spaceCount = 0;

while (file.get(ch)) {
if (isupper(static_cast<unsigned char>(ch))) {
uppercaseCount++;
} else if (islower(static_cast<unsigned char>(ch))) {
lowercaseCount++;
} else if (isdigit(static_cast<unsigned char>(ch))) {
digitCount++;
} else if (ch == ' ') {
spaceCount++;
}
}
file.close();

cout << "Uppercase letters: " << uppercaseCount << endl;


cout << "Lowercase letters: " << lowercaseCount << endl;
cout << "Digits : " << digitCount << endl;
cout << "Spaces : " << spaceCount << endl;

return 0;
}

23) Write a C++ program using function to count and display the number of lines not starting with
alphabet ‘C’ in a text file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void countLinesNotStartingWithC(const string& filename) {


ifstream file(filename);

if (!file) {
cout << "Unable to open file: " << filename << endl;
return;
}

string line;
int count = 0;

while (getline(file, line)) {


if (line.empty()) continue; // Skip empty lines
if (line[0] != 'C') {
count++;
}
}

file.close();

cout << "Number of lines NOT starting with 'C': " << count << endl;
}

int main() {
string filename;

cout << "Enter the filename: ";


getline(cin, filename);

countLinesNotStartingWithC(filename);
return 0;
}

24) Write a C++ program to create a class Number which contains two integer data members. Create
and initialize the object by using default constructor, parameterized constructor. Write a member
function to display maximum from given two numbers for all objects.
#include <iostream>
using namespace std;

class Number {
private:
int num1, num2;

public:
// Default constructor
Number() {
num1 = 0;
num2 = 0;
}

// Parameterized constructor
Number(int a, int b) {
num1 = a;
num2 = b;
}

// Member function to display the maximum number


void displayMax() {
if (num1 > num2) {
cout << "Maximum is: " << num1 << endl;
} else if (num2 > num1) {
cout << "Maximum is: " << num2 << endl;
} else {
cout << "Both numbers are equal: " << num1 << endl;
}
}
};

int main() {
// Object using default constructor
Number n1;
cout << "Using default constructor: ";
n1.displayMax();

// Object using parameterized constructor


Number n2(10, 20);
cout << "Using parameterized constructor: ";
n2.displayMax();

return 0;
}

25) Write a C++ program to create a class Employee having data members emp_id and emp_name and
basic_salary. Accept this data for 5 variables and display the details of employee having salary > 5000.
#include <iostream>
#include <string>
using namespace std;

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

void accept() {
cout << "Enter Employee ID: ";
cin >> emp_id;
cin.ignore(); // to ignore leftover newline after emp_id input

cout << "Enter Employee Name: ";


getline(cin, emp_name);

cout << "Enter Basic Salary: ";


cin >> basic_salary;
}

void display() {
cout << "Employee ID: " << emp_id << endl;
cout << "Employee Name: " << emp_name << endl;
cout << "Basic Salary: " << basic_salary << endl;
}
};

int main() {
const int SIZE = 5;
Employee employees[SIZE];

// Accept details for 5 employees


for (int i = 0; i < SIZE; i++) {
cout << "\nEnter details for Employee " << i + 1 << ":\n";
employees[i].accept();
}

// Display employees with salary > 5000


cout << "\nEmployees with salary greater than 5000:\n";
for (int i = 0; i < SIZE; i++) {
if (employees[i].basic_salary > 5000) {
employees[i].display();
cout << "---------------------------\n";
}
}

return 0;
}

**********************************************************************************

1) Write a C++ program that: a. Accepts an array of integers from the user. b. Computes the square
root of each element. c. Throws and catches an exception if a negative number is encountered
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>

using namespace std;

// Function to compute square root or throw exception


double computeSqrt(int number) {
if (number < 0) {
throw runtime_error("Negative number encountered: " + to_string(number));
}
return sqrt(number);
}

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

vector<int> numbers(n);

cout << "Enter " << n << " integers:\n";


for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}

cout << "\nSquare roots of the numbers:\n";

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


try {
double result = computeSqrt(numbers[i]);
cout << "sqrt(" << numbers[i] << ") = " << result << endl;
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
}

return 0;
}

2) Write a C++ program to define a class Bus with the following specifications:  Bus_No 
Bus_Name  No_of_Seats  Starting_point  Destination Write a menu driven program by
using appropriate manipulators to a. Accept details of ‘n’ buses. b. Display all bus details. c.
Display details of bus from specified starting and ending destination by user.

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

using namespace std;

class Bus {
private:
string Bus_No;
string Bus_Name;
int No_of_Seats;
string Starting_point;
string Destination;

public:
void acceptDetails() {
cout << "Enter Bus Number: ";
cin >> Bus_No;
cin.ignore(); // to clear newline character from input buffer

cout << "Enter Bus Name: ";


getline(cin, Bus_Name);

cout << "Enter Number of Seats: ";


cin >> No_of_Seats;
cin.ignore();

cout << "Enter Starting Point: ";


getline(cin, Starting_point);

cout << "Enter Destination: ";


getline(cin, Destination);
}
void displayDetails() const {
cout << left
<< setw(10) << Bus_No
<< setw(20) << Bus_Name
<< setw(10) << No_of_Seats
<< setw(20) << Starting_point
<< setw(20) << Destination
<< endl;
}

string getStartingPoint() const {


return Starting_point;
}

string getDestination() const {


return Destination;
}
};

void displayHeader() {
cout << left
<< setw(10) << "Bus_No"
<< setw(20) << "Bus_Name"
<< setw(10) << "Seats"
<< setw(20) << "Starting Point"
<< setw(20) << "Destination"
<< endl;
cout << string(80, '-') << endl;
}

int main() {
vector<Bus> buses;
int choice;

do {
cout << "\n--- Bus Management Menu ---\n";
cout << "1. Accept Bus Details\n";
cout << "2. Display All Buses\n";
cout << "3. Display Buses by Route\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
int n;
cout << "Enter number of buses to add: ";
cin >> n;
for (int i = 0; i < n; ++i) {
cout << "\nEntering details for bus #" << (i + 1) << ":\n";
Bus b;
b.acceptDetails();
buses.push_back(b);
}
break;
}
case 2: {
if (buses.empty()) {
cout << "No bus records available.\n";
} else {
displayHeader();
for (const auto& b : buses) {
b.displayDetails();
}
}
break;
}
case 3: {
if (buses.empty()) {
cout << "No bus records available.\n";
} else {
string start, end;
cin.ignore(); // clear input buffer
cout << "Enter Starting Point: ";
getline(cin, start);
cout << "Enter Destination: ";
getline(cin, end);

bool found = false;


displayHeader();
for (const auto& b : buses) {
if (b.getStartingPoint() == start && b.getDestination() == end) {
b.displayDetails();
found = true;
}
}
if (!found) {
cout << "No buses found for the given route.\n";
}
}
break;
}
case 4:
cout << "Exiting program. Goodbye!\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}

} while (choice != 4);

return 0;
}

3) Write the definition for a class called ‘Point’ that has x & y as integer data members. Use copy
constructor to copy one object to another. (Use Default and parameterized constructor to
initialize the appropriate objects).
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Default constructor
Point() {
x = 0;
y = 0;
cout << "Default constructor called\n";
}

// Parameterized constructor
Point(int xVal, int yVal) {
x = xVal;
y = yVal;
cout << "Parameterized constructor called\n";
}

// Copy constructor
Point(const Point &p) {
x = p.x;
y = p.y;
cout << "Copy constructor called\n";
}

// Display function
void display() const {
cout << "Point coordinates: (" << x << ", " << y << ")\n";
}
};
int main() {
cout << "--- Creating point1 using default constructor ---\n";
Point point1;
point1.display();

cout << "\n--- Creating point2 using parameterized constructor ---\n";


Point point2(5, 10);
point2.display();

cout << "\n--- Creating point3 as a copy of point2 ---\n";


Point point3 = point2; // invokes copy constructor
point3.display();

return 0;
}

4) Create class Person which contains data members as Passport_Id, Person_name, Nationality,
Gender, Date_of_Birth, Date_of_Issue, Date_of_expiry. Write a C++ program to perform
following member functions: a. Enter details of all persons b. Display passport details of one
person c. Display passport details of all persons (Use Function overloading and Array of object).

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

class Person {
private:
string Passport_Id;
string Person_name;
string Nationality;
string Gender;
string Date_of_Birth;
string Date_of_Issue;
string Date_of_Expiry;

public:
// Member function to enter details
void enterDetails() {
cout << "Enter Passport ID: ";
cin >> Passport_Id;
cin.ignore();

cout << "Enter Name: ";


getline(cin, Person_name);

cout << "Enter Nationality: ";


getline(cin, Nationality);
cout << "Enter Gender: ";
getline(cin, Gender);

cout << "Enter Date of Birth (DD/MM/YYYY): ";


getline(cin, Date_of_Birth);

cout << "Enter Date of Issue (DD/MM/YYYY): ";


getline(cin, Date_of_Issue);

cout << "Enter Date of Expiry (DD/MM/YYYY): ";


getline(cin, Date_of_Expiry);

cout << "-----------------------------\n";


}

// Overloaded function to display one person's details


void displayDetails(string id) const {
if (Passport_Id == id) {
displayHeader();
displayRow();
}
}

// Overloaded function to display all persons' details


void displayDetails() const {
displayRow();
}

// Static function to display table header


static void displayHeader() {
cout << left
<< setw(15) << "Passport_ID"
<< setw(20) << "Name"
<< setw(15) << "Nationality"
<< setw(10) << "Gender"
<< setw(15) << "DOB"
<< setw(15) << "Issue Date"
<< setw(15) << "Expiry Date"
<< endl;
cout << string(105, '-') << endl;
}

private:
// Helper to display one person's data
void displayRow() const {
cout << left
<< setw(15) << Passport_Id
<< setw(20) << Person_name
<< setw(15) << Nationality
<< setw(10) << Gender
<< setw(15) << Date_of_Birth
<< setw(15) << Date_of_Issue
<< setw(15) << Date_of_Expiry
<< endl;
}

// Helper to access Passport ID for search


public:
string getPassportId() const {
return Passport_Id;
}
};

int main() {
const int MAX = 100;
Person persons[MAX];
int n;
int choice;

cout << "Enter number of persons: ";


cin >> n;

cout << "\n--- Enter Details for " << n << " Persons ---\n";
for (int i = 0; i < n; ++i) {
cout << "Person #" << i + 1 << ":\n";
persons[i].enterDetails();
}

do {
cout << "\n--- Passport Management Menu ---\n";
cout << "1. Display details of one person\n";
cout << "2. Display details of all persons\n";
cout << "3. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
string searchId;
cin.ignore();
cout << "Enter Passport ID to search: ";
getline(cin, searchId);
bool found = false;

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


if (persons[i].getPassportId() == searchId) {
Person::displayHeader();
persons[i].displayDetails(searchId);
found = true;
break;
}
}

if (!found) {
cout << "No record found with Passport ID: " << searchId << endl;
}
break;
}

case 2:
Person::displayHeader();
for (int i = 0; i < n; ++i) {
persons[i].displayDetails();
}
break;

case 3:
cout << "Exiting program.\n";
break;

default:
cout << "Invalid choice. Try again.\n";
}

} while (choice != 3);

return 0;
}

5) Write C++ program of Simple Calculator a. Implement a calculator with operations: +, −, *, /.


b. Throw an exception for division by zero or invalid operator.
#include <iostream>
#include <stdexcept>
using namespace std;

// Function to perform calculation


double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;

case '-':
return a - b;
case '*':
return a * b;

case '/':
if (b == 0)
throw runtime_error("Error: Division by zero!");
return a / b;

default:
throw invalid_argument("Error: Invalid operator!");
}
}

int main() {
double num1, num2, result;
char op;

cout << "--- Simple Calculator ---\n";


cout << "Enter first number: ";
cin >> num1;

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


cin >> op;

cout << "Enter second number: ";


cin >> num2;

try {
result = calculate(num1, num2, op);
cout << "Result: " << num1 << " " << op << " " << num2 << " = " << result << endl;
} catch (const exception &e) {
cerr << e.what() << endl;
}

return 0;
}

6) Create a class Date with members as dd, mm, yyyy. Write a C++ program for overloading
operators >> and << to accept and display a Date.
#include <iostream>
using namespace std;

class Date {
private:
int dd, mm, yyyy;

public:
// Default constructor (optional)
Date() : dd(0), mm(0), yyyy(0) {}

// Friend function to overload >> (input)


friend istream& operator>>(istream& in, Date& d);

// Friend function to overload << (output)


friend ostream& operator<<(ostream& out, const Date& d);
};

// Overload >> operator to input date


istream& operator>>(istream& in, Date& d) {
cout << "Enter day (dd): ";
in >> d.dd;

cout << "Enter month (mm): ";


in >> d.mm;

cout << "Enter year (yyyy): ";


in >> d.yyyy;

return in;
}

// Overload << operator to display date


ostream& operator<<(ostream& out, const Date& d) {
out << (d.dd < 10 ? "0" : "") << d.dd << "/"
<< (d.mm < 10 ? "0" : "") << d.mm << "/"
<< d.yyyy;
return out;
}

int main() {
Date d;

cout << "--- Date Input ---" << endl;


cin >> d;

cout << "\n--- Displaying Date ---" << endl;


cout << "Date: " << d << endl;

return 0;
}

7) Write a C++ program that appends the contents of one file to another file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
string sourceFile, destFile;

cout << "Enter source filename: ";


cin >> sourceFile;

cout << "Enter destination filename: ";


cin >> destFile;

ifstream src(sourceFile);
ofstream dest(destFile, ios::app); // open in append mode

if (!src) {
cerr << "Error: Cannot open source file '" << sourceFile << "'." << endl;
return 1;
}

if (!dest) {
cerr << "Error: Cannot open destination file '" << destFile << "'." << endl;
return 1;
}

string line;
while (getline(src, line)) {
dest << line << endl;
}

cout << "Contents of '" << sourceFile << "' appended to '" << destFile << "' successfully." <<
endl;

src.close();
dest.close();

return 0;
}

8)Write a program for combining two strings also show the execution of dynamic
constructor. For this declare a class ‘Mystring’ with data members as name and length.
#include <iostream>
#include <cstring> // For strlen and strcpy
using namespace std;

class Mystring {
private:
char* name;
int length;

public:
// Dynamic constructor
Mystring(const char* str) {
length = strlen(str);
name = new char[length + 1]; // allocate memory dynamically
strcpy(name, str);
cout << "Dynamic constructor called for: " << name << endl;
}

// Copy constructor
Mystring(const Mystring& other) {
length = other.length;
name = new char[length + 1];
strcpy(name, other.name);
cout << "Copy constructor called for: " << name << endl;
}

// Function to combine two Mystring objects


Mystring combine(const Mystring& other) {
int newLength = length + other.length;
char* combined = new char[newLength + 1];

strcpy(combined, name);
strcat(combined, other.name);

Mystring result(combined);
delete[] combined; // temporary combined string no longer needed

return result;
}

// Display function
void display() const {
cout << "String: " << name << ", Length: " << length << endl;
}

// Destructor
~Mystring() {
delete[] name;
cout << "Destructor called for: " << name << endl;
}
};

int main() {
char str1[50], str2[50];
cout << "Enter first string: ";
cin.getline(str1, 50);

cout << "Enter second string: ";


cin.getline(str2, 50);

Mystring s1(str1); // calls dynamic constructor


Mystring s2(str2); // calls dynamic constructor

cout << "\n--- Individual Strings ---\n";


s1.display();
s2.display();

Mystring s3 = s1.combine(s2); // combining and returning new object

cout << "\n--- Combined String ---\n";


s3.display();

return 0;
}

9) Write a C++ program to merge two files into a single file using file handling. Assuming
that a text file named FIRST.TXT contains some text written into it, write a function
named vowelwords(), that reads the file FIRST.TXT and creates a new file named
SECOND.TXT, to contain only those words from the file FIRST.TXT which start with a
lower-case vowel (i.e., with 'a','e','i','o','u'). For example, if the file FIRST.TXT contains
Carry umbrella and overcoat when it rains. Then the file SECOND.TXT shall contain
umbrella, and, overcoat, it.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cctype> // for isalpha

using namespace std;

bool startsWithVowel(const string& word) {


if (word.empty()) return false;

char ch = word[0];
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}

void vowelwords() {
ifstream inFile("C:\\Users\\ADMIN\Desktop\\file prograsm(20 M)\\FIRST.txt");
ofstream outFile("C:\tUsers\tADMIN\tDesktop\tfile prograsm(20 M)\\SECOND.txt");
if (!inFile) {
cerr << "Error: Cannot open FIRST.TXT for reading." << endl;
return;
}

if (!outFile) {
cerr << "Error: Cannot open SECOND.TXT for writing." << endl;
return;
}

string word;
while (inFile >> word) {
// Remove punctuation at the end of word
if (!word.empty() && ispunct(word.back())) {
word.pop_back();
}

if (startsWithVowel(word)) {
outFile << word << endl;
}
}

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

cout << "Words starting with lowercase vowels written to SECOND.TXT successfully." <<
endl;
}

int main() {
// Run the function
vowelwords();

return 0;
}

10) Create a base class Shape. Derive three different classes Circle, Rectangle and Triangle
from Shape class. Write a C++ program to calculate area of Circle, Rectangle and
Triangle. (Use pure virtual function).
#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;

// Base class with pure virtual function


class Shape {
public:
virtual void input() = 0; // Pure virtual function for input
virtual double area() = 0; // Pure virtual function for area
virtual ~Shape() {} // Virtual destructor
};

// Derived class: Circle


class Circle : public Shape {
private:
double radius;
public:
void input() override {
cout << "Enter radius of circle: ";
cin >> radius;
}

double area() override {


return M_PI * radius * radius;
}
};

// Derived class: Rectangle


class Rectangle : public Shape {
private:
double length, width;
public:
void input() override {
cout << "Enter length and width of rectangle: ";
cin >> length >> width;
}

double area() override {


return length * width;
}
};

// Derived class: Triangle


class Triangle : public Shape {
private:
double base, height;
public:
void input() override {
cout << "Enter base and height of triangle: ";
cin >> base >> height;
}

double area() override {


return 0.5 * base * height;
}
};
int main() {
Shape* shape = nullptr;

int choice;
do {
cout << "\n--- Area Calculator ---\n";
cout << "1. Circle\n";
cout << "2. Rectangle\n";
cout << "3. Triangle\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
shape = new Circle();
break;
case 2:
shape = new Rectangle();
break;
case 3:
shape = new Triangle();
break;
case 4:
cout << "Exiting program.\n";
continue;
default:
cout << "Invalid choice. Try again.\n";
continue;
}

// Input and calculate area


shape->input();
cout << "Area = " << shape->area() << endl;

// Clean up
delete shape;
shape = nullptr;

} while (choice != 4);

return 0;
}

11) Write a C++ program to read Item information such as Itemno, Itemname , Itemprice,
Quantity of ‘n’ Items. Write the Item information using file handling.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Item {
public:
int Itemno;
string Itemname;
double Itemprice;
int Quantity;

void input() {
cout << "Enter Item number: ";
cin >> Itemno;
cin.ignore(); // to ignore leftover newline

cout << "Enter Item name: ";


getline(cin, Itemname);

cout << "Enter Item price: ";


cin >> Itemprice;

cout << "Enter Quantity: ";


cin >> Quantity;
}

void writeToFile(ofstream& outFile) {


outFile << Itemno << endl;
outFile << Itemname << endl;
outFile << Itemprice << endl;
outFile << Quantity << endl;
}
};

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

ofstream outFile("items.txt");
if (!outFile) {
cerr << "Error opening file for writing." << endl;
return 1;
}

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


cout << "\nEnter details for item " << (i + 1) << ":\n";
Item item;
item.input();
item.writeToFile(outFile);
}

outFile.close();
cout << "\nItem information saved to 'items.txt' successfully.\n";

return 0;
}

12) Write a C++ program to create a class Date which contains three data members as dd,
mm, and yyyy. Create and initialize the object by using parameterized constructor and
display date in dd Mon-yyyy format. (Input: 19-12-2025 Output: 19-Dec-2025) Perform
validation for month
#include <iostream>
#include <string>
using namespace std;

class Date {
private:
int dd, mm, yyyy;
string months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

public:
// Parameterized constructor with validation
Date(int day, int month, int year) {
dd = day;
if (month < 1 || month > 12) {
cout << "Invalid month (" << month << ")! Setting month to 1 (Jan).\n";
mm = 1;
} else {
mm = month;
}
yyyy = year;
}

void display() {
cout << (dd < 10 ? "0" : "") << dd << "-"
<< months[mm - 1] << "-"
<< yyyy << endl;
}
};

int main() {
int day, month, year;
char dash1, dash2;

cout << "Enter date (dd-mm-yyyy): ";


cin >> day >> dash1 >> month >> dash2 >> year;

if (dash1 != '-' || dash2 != '-') {


cout << "Invalid date format! Please use dd-mm-yyyy format.\n";
return 1;
}

Date d(day, month, year);


cout << "Formatted date: ";
d.display();

return 0;
}

13) Write a C++ program on Student Grading System a. Accept student data (name, marks).
b. Throw exceptions for:  Marks > 100 or < 0  Empty name.
#include <iostream>
#include <string>
#include <stdexcept> // for std::invalid_argument
using namespace std;

class Student {
private:
string name;
int marks;

public:
void input() {
cout << "Enter student name: ";
getline(cin, name);
if (name.empty()) {
throw invalid_argument("Error: Name cannot be empty!");
}

cout << "Enter marks (0-100): ";


cin >> marks;
if (marks < 0 || marks > 100) {
throw out_of_range("Error: Marks should be between 0 and 100!");
}

// Clear input buffer after reading marks


cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

void display() {
cout << "Student Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
Student s;

try {
s.input();
cout << "\n--- Student Details ---\n";
s.display();
} catch (const invalid_argument& e) {
cerr << e.what() << endl;
} catch (const out_of_range& e) {
cerr << e.what() << endl;
} catch (...) {
cerr << "Unknown error occurred." << endl;
}

return 0;
}

14) Create class College containing data members as College_Id, College_Name,


Establishment_ year, University_Name. Write a C++ program with following functions a.
Accept n College details b. Display College details of specified University c. Display
College details according to Establishment year (Use Array of Objects and Function
Overloading).
#include <iostream>
#include <string>
using namespace std;

class College {
private:
int College_Id;
string College_Name;
int Establishment_year;
string University_Name;

public:
void accept() {
cout << "Enter College ID: ";
cin >> College_Id;
cin.ignore(); // clear newline

cout << "Enter College Name: ";


getline(cin, College_Name);

cout << "Enter Establishment Year: ";


cin >> Establishment_year;
cin.ignore();
cout << "Enter University Name: ";
getline(cin, University_Name);
}

// Display details
void display() const {
cout << "College ID: " << College_Id << endl;
cout << "College Name: " << College_Name << endl;
cout << "Establishment Year: " << Establishment_year << endl;
cout << "University Name: " << University_Name << endl;
cout << "-----------------------------" << endl;
}

// Getter for University_Name


string getUniversity() const {
return University_Name;
}

// Getter for Establishment_year


int getYear() const {
return Establishment_year;
}
};

class CollegeSystem {
private:
College* colleges;
int n;

public:
CollegeSystem(int count) {
n = count;
colleges = new College[n];
}

~CollegeSystem() {
delete[] colleges;
}

void acceptDetails() {
for (int i = 0; i < n; i++) {
cout << "\nEnter details for college " << (i + 1) << ":\n";
colleges[i].accept();
}
}

// Overloaded display for University Name


void display(const string& university) {
cout << "\nColleges under University: " << university << endl;
cout << "-------------------------------------\n";
bool found = false;
for (int i = 0; i < n; i++) {
if (colleges[i].getUniversity() == university) {
colleges[i].display();
found = true;
}
}
if (!found)
cout << "No colleges found under this university.\n";
}

// Overloaded display for Establishment Year


void display(int year) {
cout << "\nColleges established in year: " << year << endl;
cout << "-------------------------------------\n";
bool found = false;
for (int i = 0; i < n; i++) {
if (colleges[i].getYear() == year) {
colleges[i].display();
found = true;
}
}
if (!found)
cout << "No colleges found established in this year.\n";
}
};

int main() {
int n;
cout << "Enter number of colleges: ";
cin >> n;
cin.ignore();

CollegeSystem cs(n);

cs.acceptDetails();

string university;
cout << "\nEnter University Name to display colleges: ";
getline(cin, university);
cs.display(university);

int year;
cout << "\nEnter Establishment Year to display colleges: ";
cin >> year;
cs.display(year);

return 0;
}
15) Design a two base classes Employee (Name, Designation) and Project(Project_Id, title).
Derive a class Emp_Proj(Duration) from Employee and Project. Write a menu driven
program to a. Build a master table. b. Display a master table. c. Display Project details in
the ascending order of duration.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // for sort
using namespace std;

// Base class Employee


class Employee {
protected:
string Name;
string Designation;

public:
void acceptEmployee() {
cout << "Enter Employee Name: ";
getline(cin, Name);
cout << "Enter Designation: ";
getline(cin, Designation);
}

void displayEmployee() const {


cout << "Name: " << Name << ", Designation: " << Designation;
}
};

// Base class Project


class Project {
protected:
int Project_Id;
string Title;

public:
void acceptProject() {
cout << "Enter Project ID: ";
cin >> Project_Id;
cin.ignore();
cout << "Enter Project Title: ";
getline(cin, Title);
}
void displayProject() const {
cout << "Project ID: " << Project_Id << ", Title: " << Title;
}
};

// Derived class Emp_Proj (multiple inheritance)


class Emp_Proj : public Employee, public Project {
private:
int Duration; // Duration in months

public:
void acceptData() {
acceptEmployee();
acceptProject();
cout << "Enter Project Duration (in months): ";
cin >> Duration;
cin.ignore();
}

void displayData() const {


displayEmployee();
cout << ", ";
displayProject();
cout << ", Duration: " << Duration << " months" << endl;
}

int getDuration() const {


return Duration;
}
};

void buildMasterTable(vector<Emp_Proj>& records) {


int n;
cout << "Enter number of employee-project records: ";
cin >> n;
cin.ignore();

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


cout << "\nEnter details for record " << i + 1 << ":\n";
Emp_Proj ep;
ep.acceptData();
records.push_back(ep);
}
}

void displayMasterTable(const vector<Emp_Proj>& records) {


cout << "\n--- Master Table ---\n";
if (records.empty()) {
cout << "No records to display.\n";
return;
}
for (const auto& rec : records) {
rec.displayData();
}
}

void displaySortedByDuration(vector<Emp_Proj> records) {


if (records.empty()) {
cout << "No records to display.\n";
return;
}
// Sort based on Duration (ascending)
sort(records.begin(), records.end(), [](const Emp_Proj& a, const Emp_Proj& b) {
return a.getDuration() < b.getDuration();
});

cout << "\n--- Projects Sorted by Duration (Ascending) ---\n";


for (const auto& rec : records) {
rec.displayData();
}
}

int main() {
vector<Emp_Proj> masterTable;
int choice;

do {
cout << "\nMenu:\n";
cout << "1. Build Master Table\n";
cout << "2. Display Master Table\n";
cout << "3. Display Projects Sorted by Duration\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore();

switch (choice) {
case 1:
buildMasterTable(masterTable);
break;
case 2:
displayMasterTable(masterTable);
break;
case 3:
displaySortedByDuration(masterTable);
break;
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 4);

return 0;
}

16) Create a C++ class Employee with data members E_no, E_Name, Designation and
Salary. Accept two employee’s information and display information of employee having
maximum salary. (Use this pointer).
#include <iostream>
#include <string>
using namespace std;

class Employee {
private:
int E_no;
string E_Name;
string Designation;
float Salary;
public:
// Member function to accept employee details
void accept() {
cout << "Enter Employee Number: ";
cin >> E_no;
cin.ignore();
cout << "Enter Employee Name: ";
getline(cin, E_Name);
cout << "Enter Designation: ";
getline(cin, Designation);
cout << "Enter Salary: ";
cin >> Salary;
cin.ignore();
}
// Member function to display employee details
void display() const {
cout << "Employee Number : " << E_no << endl;
cout << "Name : " << E_Name << endl;
cout << "Designation : " << Designation << endl;
cout << "Salary : " << Salary << endl;
}

// Function that returns the employee with maximum salary using 'this' pointer
Employee* maxSalary(Employee* other) {
return (this->Salary >= other->Salary) ? this : other;
}
};
int main() {
Employee emp1, emp2;
cout << "Enter details for Employee 1:\n";
emp1.accept();
cout << "\nEnter details for Employee 2:\n";
emp2.accept();
// Compare salaries using maxSalary and this pointer
Employee* highestPaid = emp1.maxSalary(&emp2);
cout << "\nEmployee with highest salary:\n";
highestPaid->display();

return 0;
}
17) Create a Base class Flight containing protected data members as Flight_no,
Flight_Name. Derive a class Route (Source, Destination) from class Flight. Also derive a
class Reservation (Number_Of_Seats, Class, Fare, Travel_Date) from Route. Write a C++
program to perform following necessary functions: a. Enter details of n reservations b.
Display details of all reservations c. Display reservation details of a Business class.
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;

// Base class: Flight


class Flight {
protected:
int Flight_no;
string Flight_Name;

public:
void acceptFlight() {
cout << "Enter Flight Number: ";
cin >> Flight_no;
cin.ignore();
cout << "Enter Flight Name: ";
getline(cin, Flight_Name);
}

void displayFlight() const {


cout << "Flight No: " << Flight_no
<< ", Flight Name: " << Flight_Name << endl;
}
};
// Derived class: Route from Flight
class Route : public Flight {
protected:
string Source;
string Destination;

public:
void acceptRoute() {
acceptFlight();
cout << "Enter Source: ";
getline(cin, Source);
cout << "Enter Destination: ";
getline(cin, Destination);
}

void displayRoute() const {


displayFlight();
cout << "Source: " << Source
<< ", Destination: " << Destination << endl;
}
};

// Derived class: Reservation from Route


class Reservation : public Route {
private:
int Number_Of_Seats;
string Travel_Class; // "Business", "Economy"
float Fare;
string Travel_Date;

public:
void acceptReservation() {
acceptRoute();
cout << "Enter Number of Seats: ";
cin >> Number_Of_Seats;
cin.ignore();
cout << "Enter Travel Class (Economy/Business): ";
getline(cin, Travel_Class);
cout << "Enter Fare: ";
cin >> Fare;
cin.ignore();
cout << "Enter Travel Date (dd-mm-yyyy): ";
getline(cin, Travel_Date);
}

void displayReservation() const {


displayRoute();
cout << "Class: " << Travel_Class
<< ", Seats: " << Number_Of_Seats
<< ", Fare: " << fixed << setprecision(2) << Fare
<< ", Date: " << Travel_Date << endl;
cout << "------------------------------------------\n";
}

string getClass() const {


return Travel_Class;
}
};

// Function declarations
void enterReservations(vector<Reservation>& reservations, int n);
void displayAll(const vector<Reservation>& reservations);
void displayBusinessClass(const vector<Reservation>& reservations);

// Main Program
int main() {
vector<Reservation> reservations;
int choice, n;

do {
cout << "\n==== Flight Reservation System ====\n";
cout << "1. Enter Reservation Details\n";
cout << "2. Display All Reservations\n";
cout << "3. Display Business Class Reservations\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Clear newline

switch (choice) {
case 1:
cout << "Enter number of reservations: ";
cin >> n;
cin.ignore();
enterReservations(reservations, n);
break;
case 2:
displayAll(reservations);
break;
case 3:
displayBusinessClass(reservations);
break;
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Try again.\n";
}
} while (choice != 4);

return 0;
}

// Accept n reservations
void enterReservations(vector<Reservation>& reservations, int n) {
for (int i = 0; i < n; ++i) {
cout << "\n--- Enter Reservation " << (i + 1) << " ---\n";
Reservation r;
r.acceptReservation();
reservations.push_back(r);
}
}

// Display all reservations


void displayAll(const vector<Reservation>& reservations) {
if (reservations.empty()) {
cout << "No reservations to display.\n";
return;
}

cout << "\n--- All Reservations ---\n";


for (const auto& r : reservations) {
r.displayReservation();
}
}

// Display only business class reservations


void displayBusinessClass(const vector<Reservation>& reservations) {
bool found = false;
cout << "\n--- Business Class Reservations ---\n";
for (const auto& r : reservations) {
if (r.getClass() == "Business" || r.getClass() == "business") {
r.displayReservation();
found = true;
}
}
if (!found) {
cout << "No Business class reservations found.\n";
}
}

18) Create a class Distance with feet and inches as private members. Write a friend function
to add two Distance objects.
#include <iostream>
using namespace std;

class Distance {
private:
int feet;
int inches;

public:
// Constructor to initialize values
Distance(int f = 0, int i = 0) {
feet = f;
inches = i;
}

// Friend function to add two Distance objects


friend Distance addDistance(Distance d1, Distance d2);

// Function to display distance


void display() {
cout << feet << " feet " << inches << " inches" << endl;
}
};

// Friend function definition


Distance addDistance(Distance d1, Distance d2) {
Distance result;
result.inches = d1.inches + d2.inches;
result.feet = d1.feet + d2.feet;

// Convert inches to feet if >= 12


if (result.inches >= 12) {
result.feet += result.inches / 12;
result.inches %= 12;
}

return result;
}

int main() {
Distance d1(5, 9); // 5 feet 9 inches
Distance d2(6, 8); // 6 feet 8 inches
cout << "First Distance: ";
d1.display();
cout << "Second Distance: ";
d2.display();

Distance sum = addDistance(d1, d2);


cout << "Sum of Distances: ";
sum.display();

return 0;
}

19) Create a dictionary using unordered_map to store country-capital pairs. Allow the user
to: a. Add entries b. Search for capital by country name c. Display all entries.
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

void addEntry(unordered_map<string, string>& dictionary) {


string country, capital;
cout << "Enter Country Name: ";
getline(cin, country);
cout << "Enter Capital: ";
getline(cin, capital);
dictionary[country] = capital;
cout << "Entry added successfully.\n";
}

void searchCapital(const unordered_map<string, string>& dictionary) {


string country;
cout << "Enter Country to search: ";
getline(cin, country);

auto it = dictionary.find(country);
if (it != dictionary.end()) {
cout << "Capital of " << country << " is: " << it->second << endl;
} else {
cout << "Country not found in dictionary.\n";
}
}
void displayAll(const unordered_map<string, string>& dictionary) {
if (dictionary.empty()) {
cout << "Dictionary is empty.\n";
return;
}
cout << "\n--- Country-Capital List ---\n";
for (const auto& pair : dictionary) {
cout << "Country: " << pair.first << ", Capital: " << pair.second << endl;
}
}
int main() {
unordered_map<string, string> dictionary;
int choice;
do {
cout << "\n=== Country-Capital Dictionary ===\n";
cout << "1. Add Entry\n";
cout << "2. Search Capital by Country\n";
cout << "3. Display All Entries\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // clear newline from input buffer

switch (choice) {
case 1:
addEntry(dictionary);
break;
case 2:
searchCapital(dictionary);
break;
case 3:
displayAll(dictionary);
break;
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}

} while (choice != 4);


return 0;
}

20) Create a Base class Train containing protected data members as Train_no,Train_Name.
Derive a class Route (Route_id, Source, Destination) from Train class. Also derive a class
Reservation (Number_of_Seats, Train_Class, Fare, Travel_Date) from Route. Write a
C++ program to perform following necessary functions: a. Enter details of ‘n’
reservations b. Display details of all reservations c. Display reservation details of a
specified Train class.
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;

// Base class: Train


class Train {
protected:
int Train_no;
string Train_Name;

public:
void acceptTrain() {
cout << "Enter Train Number: ";
cin >> Train_no;
cin.ignore();
cout << "Enter Train Name: ";
getline(cin, Train_Name);
}

void displayTrain() const {


cout << "Train No: " << Train_no << ", Train Name: " << Train_Name << endl;
}
};

// Derived class: Route from Train


class Route : public Train {
protected:
int Route_id;
string Source;
string Destination;

public:
void acceptRoute() {
acceptTrain();
cout << "Enter Route ID: ";
cin >> Route_id;
cin.ignore();
cout << "Enter Source: ";
getline(cin, Source);
cout << "Enter Destination: ";
getline(cin, Destination);
}

void displayRoute() const {


displayTrain();
cout << "Route ID: " << Route_id
<< ", Source: " << Source
<< ", Destination: " << Destination << endl;
}
};

// Derived class: Reservation from Route


class Reservation : public Route {
private:
int Number_of_Seats;
string Train_Class; // e.g., AC, Sleeper, General
float Fare;
string Travel_Date;

public:
void acceptReservation() {
acceptRoute();
cout << "Enter Number of Seats: ";
cin >> Number_of_Seats;
cin.ignore();
cout << "Enter Train Class (e.g., AC/Sleeper/General): ";
getline(cin, Train_Class);
cout << "Enter Fare: ";
cin >> Fare;
cin.ignore();
cout << "Enter Travel Date (dd-mm-yyyy): ";
getline(cin, Travel_Date);
}

void displayReservation() const {


displayRoute();
cout << "Train Class: " << Train_Class
<< ", Seats: " << Number_of_Seats
<< ", Fare: " << fixed << setprecision(2) << Fare
<< ", Travel Date: " << Travel_Date << endl;
cout << "-----------------------------------\n";
}

string getTrainClass() const {


return Train_Class;
}
};

// Function prototypes
void enterReservations(vector<Reservation>& resList, int n);
void displayAllReservations(const vector<Reservation>& resList);
void displayByTrainClass(const vector<Reservation>& resList, const string& tclass);

// Main function
int main() {
vector<Reservation> reservations;
int choice, n;
string tclass;

do {
cout << "\n=== Train Reservation System ===\n";
cout << "1. Enter Reservation Details\n";
cout << "2. Display All Reservations\n";
cout << "3. Display Reservations by Train Class\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // clear newline

switch (choice) {
case 1:
cout << "Enter number of reservations: ";
cin >> n;
cin.ignore();
enterReservations(reservations, n);
break;
case 2:
displayAllReservations(reservations);
break;
case 3:
cout << "Enter Train Class to filter (AC/Sleeper/etc): ";
getline(cin, tclass);
displayByTrainClass(reservations, tclass);
break;
case 4:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 4);

return 0;
}

// Function Definitions

void enterReservations(vector<Reservation>& resList, int n) {


for (int i = 0; i < n; ++i) {
cout << "\n--- Entering details for Reservation " << (i + 1) << " ---\n";
Reservation r;
r.acceptReservation();
resList.push_back(r);
}
}

void displayAllReservations(const vector<Reservation>& resList) {


if (resList.empty()) {
cout << "No reservations found.\n";
return;
}
cout << "\n--- All Reservation Details ---\n";
for (const auto& r : resList) {
r.displayReservation();
}
}

void displayByTrainClass(const vector<Reservation>& resList, const string& tclass) {


bool found = false;
cout << "\n--- Reservations in '" << tclass << "' Class ---\n";
for (const auto& r : resList) {
if (r.getTrainClass() == tclass) {
r.displayReservation();
found = true;
}
}
if (!found) {
cout << "No reservations found in '" << tclass << "' class.\n";
}
}
21) Write a C++ program to create a base class Media with data members title and price.
Derive two classes Book and Tape from Media. Use virtual functions to display details of
each media.
#include <iostream>
#include <string>
using namespace std;

// Base class
class Media {
protected:
string title;
float price;

public:
Media(string t = "", float p = 0.0) : title(t), price(p) {}

// Virtual function
virtual void display() {
cout << "Title: " << title << ", Price: " << price << endl;
}

// Virtual destructor for safety


virtual ~Media() {}
};

// Derived class: Book


class Book : public Media {
private:
int pages;
public:
Book(string t = "", float p = 0.0, int pg = 0) : Media(t, p), pages(pg) {}

void display() override {


cout << "--- Book Details ---" << endl;
cout << "Title: " << title << "\nPrice: " << price << "\nPages: " << pages << endl;
}
};

// Derived class: Tape


class Tape : public Media {
private:
float play_time; // in minutes

public:
Tape(string t = "", float p = 0.0, float pt = 0.0) : Media(t, p), play_time(pt) {}

void display() override {


cout << "--- Tape Details ---" << endl;
cout << "Title: " << title << "\nPrice: " << price << "\nPlay Time: " << play_time << "
minutes" << endl;
}
};

int main() {
// Create media pointers
Media* mediaList[2];

// Create Book and Tape objects


Book b("C++ Programming", 299.99, 500);
Tape t("C++ Audio Guide", 149.99, 90.5);

// Assign base class pointers to derived objects


mediaList[0] = &b;
mediaList[1] = &t;

// Display media details using virtual function


cout << "\nDisplaying Media Details:\n";
for (int i = 0; i < 2; ++i) {
mediaList[i]->display();
cout << endl;
}

return 0;
}
22) Consider a class Point containing x and y coordinates. Write a C++ program to
implement necessary functions to accept a point, to display a point and to find distance
between two points using operator overloading (-). (Use friend function)
#include <iostream>
#include <cmath> // For sqrt and pow
using namespace std;

class Point {
private:
float x, y;

public:
// Constructor with default values
Point(float x_val = 0.0, float y_val = 0.0) {
x = x_val;
y = y_val;
}

// Function to accept point


void accept() {
cout << "Enter x-coordinate: ";
cin >> x;
cout << "Enter y-coordinate: ";
cin >> y;
}

// Function to display point


void display() const {
cout << "(" << x << ", " << y << ")";
}

// Friend function to overload '-' operator to find distance


friend float operator-(const Point& p1, const Point& p2);
};

// Operator overloading to compute distance between two points


float operator-(const Point& p1, const Point& p2) {
float dx = p1.x - p2.x;
float dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}

int main() {
Point p1, p2;

cout << "Enter coordinates for Point 1:\n";


p1.accept();
cout << "Enter coordinates for Point 2:\n";
p2.accept();

cout << "\nPoint 1: ";


p1.display();

cout << "\nPoint 2: ";


p2.display();

float distance = p1 - p2;


cout << "\n\nDistance between two points: " << distance << endl;

return 0;
}

23) Write a program to design a class Complex to represent complex number. The Complex
class should use an external function (use it as a friend function) to add two complex
number. The function should return an object of type complex representing the sum of
two complex numbers.
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor with default values
Complex(float r = 0.0, float i = 0.0) {
real = r;
imag = i;
}
// Function to accept complex number
void accept() {
cout << "Enter real part: ";
cin >> real;
cout << "Enter imaginary part: ";
cin >> imag;
}
// Function to display complex number
void display() const {
cout << real;
if (imag >= 0)
cout << " + " << imag << "i";
else
cout << " - " << -imag << "i";
cout << endl;
}
// Friend function declaration
friend Complex addComplex(const Complex& c1, const Complex& c2);
};

// Friend function definition


Complex addComplex(const Complex& c1, const Complex& c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
// Main function
int main() {
Complex c1, c2, sum;
cout << "Enter first complex number:\n";
c1.accept();
cout << "\nEnter second complex number:\n";
c2.accept();
sum = addComplex(c1, c2);
cout << "\nFirst complex number: ";
c1.display();
cout << "Second complex number: ";
c2.display();
cout << "Sum of the complex numbers: ";
sum.display();
return 0;
}

24) Create a class Employee and use a friend function to calculate the average salary from
an array of employees.
#include <iostream>
using namespace std;

class Employee {
private:
float salary;

public:
void accept() {
cout << "Enter salary: ";
cin >> salary;
}

// Declare friend function


friend float averageSalary(Employee empArr[], int n);
};

// Friend function definition


float averageSalary(Employee empArr[], int n) {
float sum = 0;
for (int i = 0; i < n; ++i) {
sum += empArr[i].salary; // Access private member salary
}
return (n > 0) ? (sum / n) : 0;
}

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

Employee* employees = new Employee[n];

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


cout << "Employee " << (i + 1) << ":\n";
employees[i].accept();
}

float avg = averageSalary(employees, n);


cout << "\nAverage salary of " << n << " employees is: " << avg << endl;

delete[] employees;
return 0;
}

25) Write a C++ program to create a class Student with data members roll_no, name and
marks. Use a friend function to find and display the student with the highest marks
among two students.
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int roll_no;
string name;
float marks;

public:
void accept() {
cout << "Enter roll number: ";
cin >> roll_no;
cin.ignore(); // Clear input buffer before getline
cout << "Enter name: ";
getline(cin, name);
cout << "Enter marks: ";
cin >> marks;
}

void display() const {


cout << "Roll No: " << roll_no << ", Name: " << name << ", Marks: " << marks << endl;
}

// Friend function declaration


friend void highestMarks(Student s1, Student s2);
};

// Friend function definition


void highestMarks(Student s1, Student s2) {
cout << "\nStudent with highest marks:\n";
if (s1.marks > s2.marks)
s1.display();
else if (s2.marks > s1.marks)
s2.display();
else {
cout << "Both students have the same marks.\n";
cout << "Student 1: ";
s1.display();
cout << "Student 2: ";
s2.display();
}
}

int main() {
Student student1, student2;

cout << "Enter details for Student 1:\n";


student1.accept();

cout << "\nEnter details for Student 2:\n";


student2.accept();

highestMarks(student1, student2);

return 0;
}

You might also like