CPP File Program
CPP File Program
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;
int main() {
Student s1, s2;
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;
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;
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;
}
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;
}
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;
}
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;
}
// Derived class
class Discount : public Product {
private:
float discount_percent;
public:
void getDiscountData() {
getProductData();
cout << "Enter Discount (%): ";
cin >> discount_percent;
}
// 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;
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;
int main() {
float r1, h, r2;
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;
int main() {
int 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;
int main() {
float length1, width1;
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;
// 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;
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);
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);
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) {}
// 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();
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;
if (!file) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line;
int count = 0;
file.close();
cout << "Number of lines NOT starting with 'C': " << count << endl;
}
int main() {
string 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;
}
int main() {
// Object using default constructor
Number n1;
cout << "Using default constructor: ";
n1.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
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];
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>
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> numbers(n);
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>
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
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);
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();
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();
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;
}
int main() {
const int MAX = 100;
Person persons[MAX];
int n;
int choice;
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;
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";
}
return 0;
}
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;
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) {}
return in;
}
int main() {
Date d;
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;
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;
}
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);
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
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;
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;
}
// Clean up
delete shape;
shape = nullptr;
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
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;
}
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;
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!");
}
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;
}
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
// 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;
}
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();
}
}
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;
public:
void acceptEmployee() {
cout << "Enter Employee Name: ";
getline(cin, Name);
cout << "Enter Designation: ";
getline(cin, Designation);
}
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;
}
};
public:
void acceptData() {
acceptEmployee();
acceptProject();
cout << "Enter Project Duration (in months): ";
cin >> Duration;
cin.ignore();
}
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;
public:
void acceptFlight() {
cout << "Enter Flight Number: ";
cin >> Flight_no;
cin.ignore();
cout << "Enter Flight Name: ";
getline(cin, Flight_Name);
}
public:
void acceptRoute() {
acceptFlight();
cout << "Enter Source: ";
getline(cin, Source);
cout << "Enter Destination: ";
getline(cin, Destination);
}
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);
}
// 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);
}
}
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;
}
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();
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;
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";
}
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;
public:
void acceptTrain() {
cout << "Enter Train Number: ";
cin >> Train_no;
cin.ignore();
cout << "Enter Train Name: ";
getline(cin, Train_Name);
}
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);
}
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);
}
// 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
// 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;
}
public:
Tape(string t = "", float p = 0.0, float pt = 0.0) : Media(t, p), play_time(pt) {}
int main() {
// Create media pointers
Media* mediaList[2];
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;
}
int main() {
Point p1, p2;
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);
};
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;
}
int main() {
int n;
cout << "Enter number of employees: ";
cin >> n;
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;
}
int main() {
Student student1, student2;
highestMarks(student1, student2);
return 0;
}