0% found this document useful (0 votes)
8 views119 pages

C Practical Solutions

The document contains multiple C++ programming assignments, including tasks to create programs for Floyd's triangle, multiplication tables, basic arithmetic operations using switch statements, palindrome checks, and more. It also includes class definitions for Cylinder and DISTANCE, demonstrating object-oriented programming concepts. Additionally, there are instructions for creating a District class to manage district details and a menu-driven interface for user interaction.

Uploaded by

aditithakare02
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)
8 views119 pages

C Practical Solutions

The document contains multiple C++ programming assignments, including tasks to create programs for Floyd's triangle, multiplication tables, basic arithmetic operations using switch statements, palindrome checks, and more. It also includes class definitions for Cylinder and DISTANCE, demonstrating object-oriented programming concepts. Additionally, there are instructions for creating a District class to manage district details and a menu-driven interface for user interaction.

Uploaded by

aditithakare02
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/ 119

Tab 1

Assignment 1 :
Set A :
1.
Write a C++ program to print Floyd‟s triangle.
1
23
456
7 8 9 10

#include <iostream>
using namespace std;

int main() {
int n, num = 1;

cout << "Enter the number of rows for Floyd's Triangle: ";
cin >> n;

for (int i = 1; i <= n; i++)


{
for (int j = 1; j <= i; j++)
{
cout << num << " ";
num++;
}
cout << endl;
}

return 0;
}

2. Write a C++ program to generate multiplication table


#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter the number for the multiplication table: ";
cin >> number;

for (int i = 1; i <= 10; i++)


{
cout << number << " x " << i << " = " << number * i << endl;
}

return 0;
}

3. Write a C++ program using switch statement which accepts two integers and an operator as
(+, -, *, /) and performs the corresponding operation and displays theresult

#include <iostream>
using namespace std;

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

cout << "Enter first number: ";


cin >> num1;
cout << "Enter an operator (+, -, *, /): ";
cin >> op;
cout << "Enter second number: ";
cin >> num2;

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

return 0;
}

4. Write C++ program to check whether number is palindrome or not?

#include <iostream>
using namespace std;

int main() {
int num, original, reversed = 0, digit;

cout << "Enter a number: ";


cin >> num;

original = num; // Store the original number

while (num > 0) {


digit = num % 10; // Get the last digit
reversed = reversed * 10 + digit; // Build the reversed number
num = num / 10; // Remove the last digit
}

if (original == reversed) {
cout << original << " is a palindrome." << endl;
} else {
cout << original << " is not a palindrome." << endl;
}

return 0;
}

—--------------------------------------------------------------------------------------------------------------

Set B :
1.​ Write a C++ program to display factors of a number.
#include <iostream>
using namespace std;

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

cout << "Factors of " << num << " are: ";
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
cout << i << " ";
}
}

cout << endl;


return 0;
}

2.​ Write a C++ program to calculate following series:


(1) + (1+2) + (1+2+3) + (1+2+3+4) + ... +(1+2+3+4+...+n)

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;

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


cin >> n;

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


sum += (i * (i + 1)) / 2; // Add sum of first i natural numbers
}

cout << "The result of the series is: " << sum << endl;
return 0;
}
OR

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;

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


cin >> n;

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


for (int j = 1; j <= i; j++) {
sum += j; // Add each number in the inner series
}
}

cout << "The result of the series is: " << sum << endl;
return 0;
}

3.​ Write a C++ program to convert decimal number to hexadecimal.

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

int main() {
int decimal;
string hexadecimal = "";

cout << "Enter a decimal number: ";


cin >> decimal;

while (decimal > 0) {


int remainder = decimal % 16;

// Convert remainder to hexadecimal digit


if (remainder < 10) {
hexadecimal = char(remainder + '0') + hexadecimal;
} else {
hexadecimal = char(remainder - 10 + 'A') + hexadecimal;
}

decimal /= 16; // Update decimal number


}

cout << "The hexadecimal equivalent is: " << hexadecimal << endl;
return 0;
}

Explanation :

Explanation:

1.​ The program reads a decimal number from the user.


2.​ Conversion Logic:
○​ Calculate the remainder of the number when divided by 16.
○​ If the remainder is between 0 and 9, it corresponds to characters '0' to '9'.
○​ If the remainder is between 10 and 15, it corresponds to characters 'A' to 'F'.
○​ Add the corresponding hexadecimal digit to the result string.
3.​ Divide the decimal number by 16 and repeat until the number becomes 0.
4.​ Print the hexadecimal result.

input : 255
Output : FF

What is a Decimal Number?

A decimal number is a number system based on 10, which is also known as the base-10
system. It uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. This is the most common number system
used in daily life for counting and calculations.

What is a Hexadecimal Number?

A hexadecimal number is a number system based on 16, also known as the base-16 system.
It uses 16 symbols: 0-9 for values 0 to 9, and A-F for values 10 to 15. Hexadecimal is
commonly used in computing and digital systems because it is a more compact representation
of binary data.

The digits in the hexadecimal system are:

●​ 0-9 represent values 0 to 9.


●​ A-F represent values 10 to 15, where:
○​ A = 10
○​ B = 11
○​ C = 12
○​ D = 13
○​ E = 14
○​ F = 15

How to Convert Decimal to Hexadecimal:

To convert a decimal number to hexadecimal, you divide the decimal number by 16 repeatedly,
recording the remainder at each step. The remainders form the hexadecimal equivalent when
read from bottom to top.

Example: Convert Decimal 255 to Hexadecimal

1.​ Divide 255 by 16:​


255 ÷ 16 = 15 remainder 15 (F in hexadecimal)
2.​ Divide 15 by 16:​
15 ÷ 16 = 0 remainder 15 (F in hexadecimal)

So, the hexadecimal equivalent of 255 is FF.

Conversion Steps:

1.​ Divide the decimal number by 16.


2.​ Record the remainder of each division.
3.​ Repeat the division process with the quotient.
4.​ When the quotient is 0, the remainders, read in reverse order, form the hexadecimal
number.

Conversion Example: Decimal 1234 to Hexadecimal

1.​ Divide 1234 by 16:​


1234 ÷ 16 = 77 remainder 2
2.​ Divide 77 by 16:​
77 ÷ 16 = 4 remainder 13 (13 is D in hexadecimal)
3.​ Divide 4 by 16:​
4 ÷ 16 = 0 remainder 4

So, the hexadecimal equivalent of 1234 is 4D2.

—----------------------------------------------------------------------------------------------------------------

#include <iostream>
using namespace std;

// Function to check if a number is prime


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

int main() {
int number;
bool found = false;

cout << "Enter a number: ";


cin >> number;

for (int i = 2; i <= number / 2; i++) {


if (isPrime(i) && isPrime(number - i)) {
cout << number << " = " << i << " + " << number - i << endl;
found = true;
}
}

if (!found)
cout << number << " cannot be expressed as the sum of two prime numbers." << endl;

return 0;
}

Assignment 2 :
Set A :
1. Write the definition for a class called Cylinder that contains data member’s radius and height.
The class has the following member functions: a. void setradius(float) to set the radius of data
member b. void setheight(float) to set the height of data member c. float volume( ) to calculate
and return the volume of thecylinder d. float area( ) to calculate and return the area of the
cylinder. Write a C++ program to create two cylinder objects and display each cylinder and its
area and volume.

#include <iostream>
using namespace std;

class Cylinder {
private:
float radius;
float height;

public:
// Function to set radius
void setradius(float r) {
radius = r;
}

// Function to set height


void setheight(float h) {
height = h;
}

// Function to calculate and return the volume of the cylinder


float volume() {
// Volume formula: π * r^2 * h
// Using 3.14159 as approximation for π
return 3.14159 * radius * radius * height;
}

// Function to calculate and return the surface area of the cylinder


float area() {
// Surface area formula: 2 * π * r * (r + h)
// Using 3.14159 as approximation for π
return 2 * 3.14159 * radius * (radius + height);
}
};

int main() {
Cylinder cylinder1, cylinder2;

// Setting radius and height for the first cylinder


cylinder1.setradius(3.0);
cylinder1.setheight(5.0);

// Setting radius and height for the second cylinder


cylinder2.setradius(4.0);
cylinder2.setheight(6.0);

// Displaying the results for the first cylinder


cout << "Cylinder 1:" << endl;
cout << "Radius: 3.0, Height: 5.0" << endl;
cout << "Volume: " << cylinder1.volume() << endl;
cout << "Surface Area: " << cylinder1.area() << endl;

// Displaying the results for the second cylinder


cout << "\nCylinder 2:" << endl;
cout << "Radius: 4.0, Height: 6.0" << endl;
cout << "Volume: " << cylinder2.volume() << endl;
cout << "Surface Area: " << cylinder2.area() << endl;

return 0;
}

2. Create a class named „DISTANCE‟ with: - feet and inches as data members. The class has
the following member functions: a. To input distance b. To output distance c. To add two
distanceobjects Write a C++ program to create objects of DISTANCE class. Input two distances
and output the sum

#include <iostream>
using namespace std;

// Class definition
class DISTANCE {
public:
int feet; // Public data member for feet
int inches; // Public data member for inches

// Function to input the distance


void inputDistance() {
cout << "Enter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
}
// Function to output the distance
void outputDistance() {
cout << feet << " feet, " << inches << " inches" << endl;
}

// Function to add two distances


DISTANCE addDistance(DISTANCE d) {
DISTANCE result;
result.feet = feet + d.feet;
result.inches = inches + d.inches;

// Convert inches to feet if >= 12


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

return result;
}
};

int main() {
DISTANCE d1, d2, d3;

// Input distances
cout << "Enter the first distance:" << endl;
d1.inputDistance();

cout << "Enter the second distance:" << endl;


d2.inputDistance();

// Add the distances


d3 = d1.addDistance(d2);

// Output distances
cout << "The first distance is: ";
d1.outputDistance();

cout << "The second distance is: ";


d2.outputDistance();

cout << "The total distance is: ";


d3.outputDistance();
return 0;
}

3. Write a C++ program to create a class District. Having district_code, district_name, area_sqft,
population, literacy_rate. For displaying details use appropriate manipulators. The program
should contain following menu : a. Accept details of n district b. Display details of district. c.
Display details of district having highest literacy rate. d. Display details of district having least
population.

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

class District {
private:
int district_code;
string district_name;
double area_sqft;
int population;
double literacy_rate;

public:
void acceptDetails() {
cout << "Enter district code: ";
cin >> district_code;
cout << "Enter district name: ";
cin >> district_name;
cout << "Enter area (in sqft): ";
cin >> area_sqft;
cout << "Enter population: ";
cin >> population;
cout << "Enter literacy rate (%): ";
cin >> literacy_rate;
}

void displayDetails() const {


cout << "District Code: " << district_code << endl;
cout << "District Name: " << district_name << endl;
cout << "Area (sqft): " << area_sqft << endl;
cout << "Population: " << population << endl;
cout << "Literacy Rate: " << literacy_rate << "%" << endl;
}

double getLiteracyRate() const {


return literacy_rate;
}

int getPopulation() const {


return population;
}
};

int main() {
vector<District> districts;
int n;
char choice;

do {
cout << "\nMenu:\n";
cout << "a. Accept details of n districts\n";
cout << "b. Display details of all districts\n";
cout << "c. Display details of district with highest literacy rate\n";
cout << "d. Display details of district with least population\n";
cout << "e. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 'a': {
cout << "Enter the number of districts: ";
cin >> n;
districts.resize(n);
for (int i = 0; i < n; ++i) {
cout << "\nEnter details for district " << i + 1 << ":\n";
districts[i].acceptDetails();
}
break;
}

case 'b': {
if (districts.empty()) {
cout << "No districts available.\n";
} else {
for (const auto &district : districts) {
district.displayDetails();
cout << "--------------------\n";
}
}
break;
}

case 'c': {
if (districts.empty()) {
cout << "No districts available.\n";
} else {
const District *highestLiteracy = &districts[0];
for (const auto &district : districts) {
if (district.getLiteracyRate() > highestLiteracy->getLiteracyRate()) {
highestLiteracy = &district;
}
}
cout << "\nDistrict with highest literacy rate:\n";
highestLiteracy->displayDetails();
}
break;
}

case 'd': {
if (districts.empty()) {
cout << "No districts available.\n";
} else {
const District *leastPopulation = &districts[0];
for (const auto &district : districts) {
if (district.getPopulation() < leastPopulation->getPopulation()) {
leastPopulation = &district;
}
}
cout << "\nDistrict with least population:\n";
leastPopulation->displayDetails();
}
break;
}

case 'e': {
cout << "Exiting program.\n";
break;
}

default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 'e');

return 0;
}

4. Define a class string to perform different operations: SPPU,Pune C++ Laboratory Workbook
Page 9 Set B a. To find length ofstring. b. To concatenate twostrings. c. To reverse thestring. d.
To compare two strings.

#include <iostream>
using namespace std;

class String {
public:
char str[100]; // Array to hold the string

// Function to find the length of the string


int length() {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}

// Function to concatenate two strings


void concatenate(const char* s2) {
int i = length();
int j = 0;
while (s2[j] != '\0') {
str[i] = s2[j];
i++;
j++;
}
str[i] = '\0'; // Null terminate the concatenated string
}

// Function to reverse the string


void reverse() {
int len = length();
for (int i = 0, j = len - 1; i < j; i++, j--) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}

// Function to compare two strings


bool compare(const char* s2) {
int i = 0;
while (str[i] != '\0' && s2[i] != '\0') {
if (str[i] != s2[i]) {
return false; // Strings are not the same
}
i++;
}
return str[i] == '\0' && s2[i] == '\0'; // Both strings should be of same length
}
};

int main() {
String s1;
String s2;

// Take input from user


cout << "Enter first string: ";
cin >> s1.str;

cout << "Enter second string: ";


cin >> s2.str;

// Length of first string


cout << "Length of first string: " << s1.length() << endl;

// Concatenating second string to first string


s1.concatenate(s2.str);
cout << "Concatenated string: " << s1.str << endl;

// Reversing the string


s1.reverse();
cout << "Reversed string: " << s1.str << endl;

// Comparing strings
if (s1.compare(s2.str)) {
cout << "Both strings are equal." << endl;
} else {
cout << "Strings are not equal." << endl;
}

return 0;
}

Set B :
1 . Create a class for different departments in a college containing data members as Dept_Id,
Dept_Name, Establishment_year, No_of_Faculty, No_of_students. Write a C++ program with
following member functions: a. To accept „n‟ Department details b. To display department
details of a specific Department c. To display department details according to a specified
establishment year.

#include <iostream>
using namespace std;

class Department {
public:
int Dept_Id;
char Dept_Name[50];
int Establishment_year;
int No_of_Faculty;
int No_of_students;

// Function to accept department details


void acceptDetails() {
cout << "Enter Department ID: ";
cin >> Dept_Id;
cout << "Enter Department Name: ";
cin.ignore(); // To clear the input buffer before taking string input
cin.getline(Dept_Name, 50);
cout << "Enter Establishment Year: ";
cin >> Establishment_year;
cout << "Enter Number of Faculty: ";
cin >> No_of_Faculty;
cout << "Enter Number of Students: ";
cin >> No_of_students;
}
// Function to display department details
void displayDetails() {
cout << "Department ID: " << Dept_Id << endl;
cout << "Department Name: " << Dept_Name << endl;
cout << "Establishment Year: " << Establishment_year << endl;
cout << "Number of Faculty: " << No_of_Faculty << endl;
cout << "Number of Students: " << No_of_students << endl;
}

// Function to display department details according to establishment year


void displayByEstablishmentYear(int year) {
if (Establishment_year == year) {
displayDetails();
}
}
};

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

Department dept[n]; // Array to store department objects

// Accepting department details for all departments


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

// Display details of a specific department


int deptId;
cout << "\nEnter Department ID to display details: ";
cin >> deptId;
bool found = false;
for (int i = 0; i < n; i++) {
if (dept[i].Dept_Id == deptId) {
cout << "\nDepartment details for ID " << deptId << ":\n";
dept[i].displayDetails();
found = true;
break;
}
}
if (!found) {
cout << "Department with ID " << deptId << " not found.\n";
}

// Display departments according to a specified establishment year


cout << "\nEnter establishment year to display departments: ";
cin >> year;
bool displayed = false;
for (int i = 0; i < n; i++) {
dept[i].displayByEstablishmentYear(year);
displayed = true;
}
if (!displayed) {
cout << "No departments found for the specified establishment year.\n";
}

return 0;
}

2. Write a C++ program to define a class Bus with the followingspecifications : 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 busdetails. c. Display
details of bus from specified starting and ending destinationbyuser.

#include <iostream>
#include <cstring> // For strcmp()
using namespace std;

class Bus {
public:
int Bus_No;
char Bus_Name[50];
int No_of_Seats;
char Starting_Point[50];
char Destination[50];

// Function to accept bus details


void acceptDetails() {
cout << "Enter Bus Number: ";
cin >> Bus_No;
cout << "Enter Bus Name: ";
cin >> Bus_Name; // Accepting single word bus name
cout << "Enter Number of Seats: ";
cin >> No_of_Seats;
cout << "Enter Starting Point: ";
cin >> Starting_Point; // Accepting single word starting point
cout << "Enter Destination: ";
cin >> Destination; // Accepting single word destination
}

// Function to display bus details


void displayDetails() {
cout << "Bus Number: " << Bus_No << endl;
cout << "Bus Name: " << Bus_Name << endl;
cout << "Number of Seats: " << No_of_Seats << endl;
cout << "Starting Point: " << Starting_Point << endl;
cout << "Destination: " << Destination << endl;
}

// Function to display bus details for specified starting and destination points
void displayByRoute(const char* start, const char* end) {
if (strcmp(Starting_Point, start) == 0 && strcmp(Destination, end) == 0) {
displayDetails();
}
}
};

int main() {
int n, choice;
char start[50], end[50];

cout << "Enter the number of buses: ";


cin >> n;

Bus bus[n]; // Array of bus objects

while (true) {
cout << "\nMenu:\n";
cout << "1. Accept details of buses\n";
cout << "2. Display all bus details\n";
cout << "3. Display buses by specified route\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
// Accept details for all buses
for (int i = 0; i < n; i++) {
cout << "\nEnter details for Bus " << i + 1 << ":\n";
bus[i].acceptDetails();
}
break;

case 2:
// Display details of all buses
cout << "\nDisplaying details of all buses:\n";
for (int i = 0; i < n; i++) {
bus[i].displayDetails();
cout << endl;
}
break;

case 3:
// Display buses by specified route
cout << "Enter starting point: ";
cin >> start; // Accepting single word starting point
cout << "Enter destination: ";
cin >> end; // Accepting single word destination
cout << "\nDisplaying buses with route from " << start << " to " << end << ":\n";
bool found = false;
for (int i = 0; i < n; i++) {
bus[i].displayByRoute(start, end);
}
break;

case 4:
// Exit
cout << "Exiting the program...\n";
return 0;

default:
cout << "Invalid choice! Please try again.\n";
}
}

return 0;
}

Assignment 2 :
SET A :

1. Write the definition for a class called Cylinder that contains data member’s radius and height.
The class has the following member functions: a. void setradius(float) to set the radius of data
member b. void setheight(float) to set the height of data member c. float volume( ) to calculate
and return the volume of thecylinder d. float area( ) to calculate and return the area of the
cylinder. Write a C++ program to create two cylinder objects and display each cylinder and its
area and volume.

#include <iostream>
using namespace std;

class Cylinder {
private:
float radius;
float height;

public:
// Function to set radius
void setradius(float r) {
radius = r;
}

// Function to set height


void setheight(float h) {
height = h;
}

// Function to calculate and return the volume of the cylinder


float volume() {
// Volume formula: π * r^2 * h
// Using 3.14159 as approximation for π
return 3.14159 * radius * radius * height;
}

// Function to calculate and return the surface area of the cylinder


float area() {
// Surface area formula: 2 * π * r * (r + h)
// Using 3.14159 as approximation for π
return 2 * 3.14159 * radius * (radius + height);
}
};
int main() {
Cylinder cylinder1, cylinder2;

// Setting radius and height for the first cylinder


cylinder1.setradius(3.0);
cylinder1.setheight(5.0);

// Setting radius and height for the second cylinder


cylinder2.setradius(4.0);
cylinder2.setheight(6.0);

// Displaying the results for the first cylinder


cout << "Cylinder 1:" << endl;
cout << "Radius: 3.0, Height: 5.0" << endl;
cout << "Volume: " << cylinder1.volume() << endl;
cout << "Surface Area: " << cylinder1.area() << endl;

// Displaying the results for the second cylinder


cout << "\nCylinder 2:" << endl;
cout << "Radius: 4.0, Height: 6.0" << endl;
cout << "Volume: " << cylinder2.volume() << endl;
cout << "Surface Area: " << cylinder2.area() << endl;

return 0;
}

2. Create a class named „DISTANCE‟ with: - feet and inches as data members. The class has
the following member functions: a. To input distance b. To output distance c. To add two
distanceobjects Write a C++ program to create objects of DISTANCE class. Input two distances
and output the sum.

#include <iostream>
using namespace std;

class DISTANCE {
private:
int feet;
int inches;

public:
// Function to input distance
void inputDistance() {
cout << "Enter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;

// Normalize inches if >= 12


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

// Function to output distance


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

// Function to add two distances


DISTANCE addDistance(const DISTANCE &d) const {
DISTANCE result;
result.feet = feet + d.feet;
result.inches = inches + d.inches;

// Normalize inches if >= 12


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

return result;
}
};

int main() {
DISTANCE d1, d2, d3;

cout << "Enter the first distance:\n";


d1.inputDistance();

cout << "Enter the second distance:\n";


d2.inputDistance();

// Add the two distances


d3 = d1.addDistance(d2);
cout << "\nThe first distance is: ";
d1.outputDistance();

cout << "The second distance is: ";


d2.outputDistance();

cout << "The total distance is: ";


d3.outputDistance();

return 0;
}

3. Write a C++ program to create a class District. Having district_code, district_name, area_sqft,
population, literacy_rate. For displaying details use appropriate manipulators. The program
should contain following menu : a. Accept details of n district b. Display details of district. c.
Display details of district having highest literacy rate. d. Display details of district having least
population.

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

class District {
private:
int district_code;
string district_name;
float area_sqft;
int population;
float literacy_rate;

public:
// Function to accept details of a district
void acceptDetails() {
cout << "Enter district code: ";
cin >> district_code;
cout << "Enter district name: ";
cin.ignore(); // To handle newline character
getline(cin, district_name);
cout << "Enter area (in sqft): ";
cin >> area_sqft;
cout << "Enter population: ";
cin >> population;
cout << "Enter literacy rate: ";
cin >> literacy_rate;
}

// Function to display details of a district


void displayDetails() const {
cout << left << setw(15) << district_code
<< setw(20) << district_name
<< setw(15) << area_sqft
<< setw(15) << population
<< setw(10) << literacy_rate << "%" << endl;
}

// Accessor functions
float getLiteracyRate() const { return literacy_rate; }
int getPopulation() const { return population; }
};

void displayHeader() {
cout << left << setw(15) << "Code"
<< setw(20) << "Name"
<< setw(15) << "Area(sqft)"
<< setw(15) << "Population"
<< setw(10) << "Literacy(%)" << endl;
cout << string(70, '-') << endl;
}

int main() {
vector<District> districts;
int n;
char choice;

do {
cout << "\nMenu:\n";
cout << "a. Accept details of n districts\n";
cout << "b. Display details of districts\n";
cout << "c. Display district with highest literacy rate\n";
cout << "d. Display district with least population\n";
cout << "e. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 'a': {
cout << "How many districts do you want to enter? ";
cin >> n;
districts.resize(n);
for (int i = 0; i < n; ++i) {
cout << "\nEnter details for district " << i + 1 << ":\n";
districts[i].acceptDetails();
}
break;
}
case 'b': {
if (districts.empty()) {
cout << "No districts to display.\n";
} else {
cout << "\nDistrict Details:\n";
displayHeader();
for (const auto& district : districts) {
district.displayDetails();
}
}
break;
}
case 'c': {
if (districts.empty()) {
cout << "No districts to evaluate.\n";
} else {
const District* highest = &districts[0];
for (const auto& district : districts) {
if (district.getLiteracyRate() > highest->getLiteracyRate()) {
highest = &district;
}
}
cout << "\nDistrict with Highest Literacy Rate:\n";
displayHeader();
highest->displayDetails();
}
break;
}
case 'd': {
if (districts.empty()) {
cout << "No districts to evaluate.\n";
} else {
const District* least = &districts[0];
for (const auto& district : districts) {
if (district.getPopulation() < least->getPopulation()) {
least = &district;
}
}
cout << "\nDistrict with Least Population:\n";
displayHeader();
least->displayDetails();
}
break;
}
case 'e':
cout << "Exiting the program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 'e');

return 0;
}

4. Define a class string to perform different operations: a. To find length ofstring. b. To


concatenate twostrings. c. To reverse thestring. d. To compare two strings. give me simple
codes for beginer

#include <iostream>
using namespace std;

class String {
private:
char str[100]; // Array to store the string (maximum length 99)

public:
// Function to input a string
void inputString() {
cout << "Enter a string: ";
cin.ignore();
cin.getline(str, 100);
}

// Function to display the string


void displayString() const {
cout << str << endl;
}

// Function to find the length of the string


int length() const {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}

// Function to concatenate another string


void concatenate(const String& s) {
int len1 = length();
int len2 = s.length();
for (int i = 0; i <= len2; ++i) { // Include '\0' at the end
str[len1 + i] = s.str[i];
}
}

// Function to reverse the string


void reverse() {
int len = length();
for (int i = 0; i < len / 2; ++i) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}

// Function to compare two strings


bool compare(const String& s) const {
int i = 0;
while (str[i] != '\0' && s.str[i] != '\0') {
if (str[i] != s.str[i]) {
return false; // Strings are not equal
}
i++;
}
// Check if both strings ended at the same length
return str[i] == '\0' && s.str[i] == '\0';
}
};
int main() {
String s1, s2;
char choice;

do {
cout << "\nMenu:\n";
cout << "a. Find length of string\n";
cout << "b. Concatenate two strings\n";
cout << "c. Reverse the string\n";
cout << "d. Compare two strings\n";
cout << "e. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 'a': {
s1.inputString();
cout << "The length of the string is: " << s1.length() << endl;
break;
}
case 'b': {
cout << "Enter the first string:\n";
s1.inputString();
cout << "Enter the second string:\n";
s2.inputString();
s1.concatenate(s2);
cout << "Concatenated string: ";
s1.displayString();
break;
}
case 'c': {
s1.inputString();
s1.reverse();
cout << "Reversed string: ";
s1.displayString();
break;
}
case 'd': {
cout << "Enter the first string:\n";
s1.inputString();
cout << "Enter the second string:\n";
s2.inputString();
if (s1.compare(s2)) {
cout << "The strings are equal.\n";
} else {
cout << "The strings are not equal.\n";
}
break;
}
case 'e':
cout << "Exiting the program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 'e');

return 0;
}

SET B :

1.​ create a class for different departments in a college containing data members as
Dept_Id, Dept_Name, Establishment_year, No_of_Faculty, No_of_students. Write a C++
program with following member functions: a. To accept „n‟ Department details b. To
display department details of a specific Department c. To display department details
according to a specified establishment year

#include <iostream>
using namespace std;

class Department {
public:
int Dept_Id;
char Dept_Name[50];
int Establishment_year;
int No_of_Faculty;
int No_of_Students;

// Function to accept department details


void acceptDetails() {
cout << "Enter Department ID: ";
cin >> Dept_Id;
cout << "Enter Department Name: ";
cin.ignore(); // Clear input buffer
cin.getline(Dept_Name, 50);
cout << "Enter Establishment Year: ";
cin >> Establishment_year;
cout << "Enter Number of Faculty: ";
cin >> No_of_Faculty;
cout << "Enter Number of Students: ";
cin >> No_of_Students;
}

// Function to display department details


void displayDetails() {
cout << "Department ID: " << Dept_Id << endl;
cout << "Department Name: " << Dept_Name << endl;
cout << "Establishment Year: " << Establishment_year << endl;
cout << "Number of Faculty: " << No_of_Faculty << endl;
cout << "Number of Students: " << No_of_Students << endl;
}
};

int main() {
Department departments[100]; // Fixed array for storing departments
int n = 0; // Number of departments
char choice;

do {
cout << "\nMenu:\n";
cout << "a. Accept 'n' Department details\n";
cout << "b. Display department details of a specific Department\n";
cout << "c. Display department details according to a specified establishment year\n";
cout << "d. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 'a': {
cout << "How many departments do you want to enter? ";
cin >> n;
for (int i = 0; i < n; ++i) {
cout << "\nEnter details for Department " << i + 1 << ":\n";
departments[i].acceptDetails();
}
break;
}
case 'b': {
if (n == 0) {
cout << "No departments available.\n";
} else {
int id;
cout << "Enter Department ID to search: ";
cin >> id;
bool found = false;
for (int i = 0; i < n; ++i) {
if (departments[i].Dept_Id == id) {
cout << "\nDepartment Details:\n";
departments[i].displayDetails();
found = true;
break;
}
}
if (!found) {
cout << "Department with ID " << id << " not found.\n";
}
}
break;
}
case 'c': {
if (n == 0) {
cout << "No departments available.\n";
} else {
int year;
cout << "Enter Establishment Year to search: ";
cin >> year;
bool found = false;
for (int i = 0; i < n; ++i) {
if (departments[i].Establishment_year == year) {
cout << "\nDepartment Details:\n";
departments[i].displayDetails();
cout << endl;
found = true;
}
}
if (!found) {
cout << "No departments found for the year " << year << ".\n";
}
}
break;
}
case 'd':
cout << "Exiting the program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 'd');

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 busdetails.
c. Display details of bus from specified starting and ending destinationbyuse

#include <iostream>
using namespace std;

class Bus {
public:
int Bus_No;
char Bus_Name[50];
int No_of_Seats;
char Starting_Point[50];
char Destination[50];

// Function to accept bus details


void acceptDetails() {
cout << "Enter Bus Number: ";
cin >> Bus_No;
cout << "Enter Bus Name: ";
cin >> Bus_Name; // Input single-word names
cout << "Enter Number of Seats: ";
cin >> No_of_Seats;
cout << "Enter Starting Point: ";
cin >> Starting_Point;
cout << "Enter Destination: ";
cin >> Destination;
}

// Function to display bus details


void displayDetails() const {
cout << "Bus Number: " << Bus_No << endl;
cout << "Bus Name: " << Bus_Name << endl;
cout << "Number of Seats: " << No_of_Seats << endl;
cout << "Starting Point: " << Starting_Point << endl;
cout << "Destination: " << Destination << endl;
}

// Function to compare strings manually


bool compareStrings(const char str1[], const char str2[]) const {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return false;
}
i++;
}
return (str1[i] == '\0' && str2[i] == '\0');
}
};

int main() {
Bus buses[100]; // Array to store up to 100 buses
int n = 0; // Number of buses
char choice;

do {
cout << "\nMenu:\n";
cout << "a. Accept details of 'n' buses\n";
cout << "b. Display all bus details\n";
cout << "c. Display bus details for a specified starting and ending destination\n";
cout << "d. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 'a': {
cout << "How many buses do you want to enter? ";
cin >> n;
for (int i = 0; i < n; ++i) {
cout << "\nEnter details for Bus " << i + 1 << ":\n";
buses[i].acceptDetails();
}
break;
}
case 'b': {
if (n == 0) {
cout << "No buses available.\n";
} else {
cout << "\nBus Details:\n";
for (int i = 0; i < n; ++i) {
cout << "\nDetails of Bus " << i + 1 << ":\n";
buses[i].displayDetails();
}
}
break;
}
case 'c': {
if (n == 0) {
cout << "No buses available.\n";
} else {
char start[50], end[50];
cout << "Enter Starting Point: ";
cin >> start;
cout << "Enter Destination: ";
cin >> end;

bool found = false;


for (int i = 0; i < n; ++i) {
if (buses[i].compareStrings(buses[i].Starting_Point, start) &&
buses[i].compareStrings(buses[i].Destination, end)) {
cout << "\nBus Details:\n";
buses[i].displayDetails();
found = true;
}
}
if (!found) {
cout << "No buses found for the specified route.\n";
}
}
break;
}
case 'd':
cout << "Exiting the program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 'd');

return 0;
}
ASSIGNMENT 3 :

SET A :

1.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; // Data members

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

// Parameterized constructor
Number(int n1, int n2) {
num1 = n1;
num2 = n2;
}

// Member function to display the maximum of the two numbers


void displayMax() {
if (num1 > num2) {
cout << "Maximum number is: " << num1 << endl;
} else {
cout << "Maximum number is: " << num2 << endl;
}
}
};

int main() {
// Creating objects using default constructor
Number num1;
num1.displayMax();

// Creating objects using parameterized constructor


Number num2(5, 10);
num2.displayMax();

Number num3(15, 8);


num3.displayMax();

return 0;
}

2.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:
double principal, rate, time; // Data members

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

// Member function to calculate and display simple interest


void calculateAndDisplay() {
double interest = (principal * rate * time) / 100;
cout << "Simple Interest is: " << interest << endl;
}
};

int main() {
// Creating objects using the parameterized constructor
SimpleInterest si1(10000, 2); // Default rate of 5.0% will be used
si1.calculateAndDisplay();

SimpleInterest si2(15000, 3, 7.5); // Custom rate of 7.5%


si2.calculateAndDisplay();

return 0;
}

3.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; // Data member for mobile ID
string Mobile_Name; // Data member for mobile name
double Mobile_Price; // Data member for mobile price

public:
// Parameterized constructor
Mobile(int id, string name, double price) {
Mobile_Id = id;
Mobile_Name = name;
Mobile_Price = price;
}

// Member function to display mobile details


void displayDetails() {
cout << "Mobile ID: " << Mobile_Id << endl;
cout << "Mobile Name: " << Mobile_Name << endl;
cout << "Mobile Price: "
<< right << setw(10) << fixed << setprecision(2)
<< Mobile_Price << endl; // Right justified with 2 decimal precision
}
};

int main() {
// Creating a Mobile object using the parameterized constructor
Mobile mobile1(101, "Samsung Galaxy", 24999.99);

// Displaying the details of the Mobile object


mobile1.displayDetails();
return 0;
}

4.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; // Data member to store the value of n

public:
// Parameterized constructor
SumCalculator(int num) {
n = num;
}

// Member function to calculate the sum


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

// Member function to display the result


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

int main() {
int n;

// Asking user for the value of n


cout << "Enter the value of n: ";
cin >> n;
// Creating an object of SumCalculator
SumCalculator calculator(n);

// Displaying the result


calculator.displaySum();

return 0;
}

Set B :

1. 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; // Data members

public:
// Default constructor
Point() {
x = 0;
y = 0;
}

// Parameterized constructor
Point(int xValue, int yValue) {
x = xValue;
y = yValue;
}

// Copy constructor
Point(const Point &p) {
x = p.x;
y = p.y;
}

// Member function to display point coordinates


void display() {
cout << "Point coordinates: (" << x << ", " << y << ")" << endl;
}
};

int main() {
// Using default constructor
Point p1;
p1.display();

// Using parameterized constructor


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

// Using copy constructor to create a new object


Point p3(p2);
p3.display();

return 0;
}

2 .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-2014 Output: 19-Dec-2014) Perform validation for month.


#include <iostream>
using namespace std;

class Date {
private:
int dd, mm, yyyy; // Data members for day, month, and year

public:
// Parameterized constructor
Date(int day, int month, int year) {
dd = day;
if (month >= 1 && month <= 12) {
mm = month;
} else {
mm = 1; // Default to January if invalid
cout << "Invalid month! Setting month to 1 (January)." << endl;
}
yyyy = year;
}

// Member function to display the date in dd-mm-yyyy format


void displayDate() {
cout << dd << "-" << mm << "-" << yyyy << endl;
}
};

int main() {
int day, month, year;

// Input the date components


cout << "Enter day: ";
cin >> day;
cout << "Enter month: ";
cin >> month;
cout << "Enter year: ";
cin >> year;

// Create Date object and display the date


Date date(day, month, year);
date.displayDate();

return 0;
}

—----------------------------------------------------------------------------------------------------------------------------

Assignment 4 :
SET A :

1. Write a C++ program to create a class which contains single dimensional integer array of
given size.Define member function to display median of a given array. (Use Dynamic
Constructor to allocate and
Destructor to free memory of anobject)
—>

#include <iostream>
using namespace std;

class Array {
private:
int* arr; // Pointer for dynamic array
int size; // Size of the array

// Helper function to sort the array manually


void sortArray() {
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
// Swap elements
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

public:
// Constructor to allocate memory dynamically
Array(int s) {
size = s;
arr = new int[size];
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
}

// Function to calculate and display the median


void displayMedian() {
// Sort the array manually
sortArray();

// Calculate and display the median


if (size % 2 == 0) {
// Even size: Median is average of two middle elements
float median = (arr[size / 2 - 1] + arr[size / 2]) / 2.0;
cout << "Median: " << median << endl;
} else {
// Odd size: Median is the middle element
cout << "Median: " << arr[size / 2] << endl;
}
}

// Destructor to free allocated memory


~Array() {
delete[] arr;
cout << "Memory freed for the array." << endl;
}
};

int main() {
int n;

cout << "Enter the size of the array: ";


cin >> n;

// Create an object of Array class


Array myArray(n);

// Display the median


myArray.displayMedian();

return 0;
}

2. Writea programto create memory space using the new keyword and to destroy it using delete
keyword.

#include <iostream>
using namespace std;

int main() {
// Create memory space dynamically for an integer
int* ptr = new int;

// Assign a value to the dynamically allocated memory


cout << "Enter an integer: ";
cin >> *ptr;
// Display the value stored in the memory
cout << "You entered: " << *ptr << endl;

// Free the allocated memory


delete ptr;

cout << "Memory has been freed." << endl;

return 0;
}

3.​ Write a C++ Program to store GPA of a number of students and display it where n is the
number of students entered by the user .

#include <iostream>
using namespace std;

int main() {
int n;

// Ask the user for the number of students


cout << "Enter the number of students: ";
cin >> n;

// Dynamically allocate memory to store GPAs


float* gpa = new float[n];

// Input GPAs for all students


cout << "Enter the GPA of " << n << " students:" << endl;
for (int i = 0; i < n; i++) {
cout << "Student " << i + 1 << ": ";
cin >> gpa[i];
}

// Display the GPAs


cout << "\nGPAs of students:" << endl;
for (int i = 0; i < n; i++) {
cout << "Student " << i + 1 << ": " << gpa[i] << endl;
}

// Free the allocated memory


delete[] gpa;
cout << "Memory has been freed." << endl;

return 0;
}

4.​ Write a c++ program that determines a given number is prime or nor .(use Dynamic
Constructor to allocate and estructor to free memory of an object).

—>

#include <iostream>
using namespace std;

class PrimeChecker {
private:
int* number; // Pointer to dynamically store the number

public:
// Dynamic constructor to allocate memory
PrimeChecker(int num) {
number = new int(num);
}

// Function to check if the number is prime


void checkPrime() const {
if (*number < 2) {
cout << *number << " is not a prime number." << endl;
return;
}

for (int i = 2; i <= *number / 2; i++) {


if (*number % i == 0) {
cout << *number << " is not a prime number." << endl;
return;
}
}
cout << *number << " is a prime number." << endl;
}

// Destructor to free allocated memory


~PrimeChecker() {
delete number;
cout << "Memory has been freed." << endl;
}
};

int main() {
int num;

// Get the number from the user


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

// Create an object of PrimeChecker


PrimeChecker prime(num);

// Check if the number is prime


prime.checkPrime();

return 0;
}

SET B :

1.​ Write a C++ program to create a class which contains two dimensional integer
array of size mXn. Write a member function to display transpose of entered
matrix. (Use Dynamic Constructor for allocating memory and Destructor to free
memory of an object).

—--->

#include <iostream>
using namespace std;

class Matrix {
private:
int** mat; // Pointer to dynamically allocate 2D array
int rows, cols; // Dimensions of the matrix

public:
// Dynamic constructor to allocate memory
Matrix(int m, int n) {
rows = m;
cols = n;
mat = new int*[rows]; // Allocate memory for rows
for (int i = 0; i < rows; i++) {
mat[i] = new int[cols]; // Allocate memory for columns in each row
}
cout << "Enter elements of the matrix (" << rows << "x" << cols << "):" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> mat[i][j];
}
}
}

// Function to display the transpose of the matrix


void displayTranspose() const {
cout << "\nTranspose of the matrix:" << endl;
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}

// Destructor to free allocated memory


~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] mat[i]; // Free memory for each row
}
delete[] mat; // Free memory for row pointers
cout << "Memory has been freed." << endl;
}
};

int main() {
int m, n;

// Get dimensions of the matrix from the user


cout << "Enter the number of rows: ";
cin >> m;
cout << "Enter the number of columns: ";
cin >> n;
// Create an object of Matrix class
Matrix matrix(m, n);

// Display the transpose of the matrix


matrix.displayTranspose();

return 0;
}

2. Write a program for combining two strings also show the execution of dynamic
constructor.For this declare a class string with data members as name and length.

#include <iostream>
#include <cstring> // For strlen and strcat
using namespace std;

class String {
private:
char* name; // Pointer for dynamically storing the string

public:
// Constructor to dynamically allocate memory and initialize the string
String(const char* str) {
name = new char[strlen(str) + 1]; // Allocate memory
strcpy(name, str); // Copy the string
}

// Function to combine two strings


String combine(const String& other) {
char* combinedName = new char[strlen(name) + strlen(other.name) + 1];
strcpy(combinedName, name);
strcat(combinedName, other.name);
return String(combinedName);
}

// Function to display the string


void display() const {
cout << name << endl;
}
// Destructor to free allocated memory
~String() {
delete[] name;
}
};

int main() {
// Create two strings
String str1("Hello, ");
String str2("World!");

// Combine the two strings


String combined = str1.combine(str2);

// Display the combined string


cout << "Combined String: ";
combined.display();

return 0;
}

—-------------------------------------------------------------------------------------------------------------------------
Assignment 5 :
SET A :

1.​ Write a C++ program to print area of circle, square and rectangle using inline function.

#include <iostream>
using namespace std;

// Inline function to calculate the area of a circle


inline double areaOfCircle(double radius) {
return 3.14159 * radius * radius;
}

// Inline function to calculate the area of a square


inline double areaOfSquare(double side) {
return side * side;
}

// Inline function to calculate the area of a rectangle


inline double areaOfRectangle(double length, double width) {
return length * width;
}

int main() {
double radius, side, length, width;

// Input and calculate area of circle


cout << "Enter radius of the circle: ";
cin >> radius;
cout << "Area of the circle: " << areaOfCircle(radius) << endl;

// Input and calculate area of square


cout << "Enter side of the square: ";
cin >> side;
cout << "Area of the square: " << areaOfSquare(side) << endl;

// Input and calculate area of rectangle


cout << "Enter length and width of the rectangle: ";
cin >> length >> width;
cout << "Area of the rectangle: " << areaOfRectangle(length, width) << endl;

return 0;
}

2. Write a C++ programto subtract two integer numbers of two different classes using friend
function.

#include <iostream>
using namespace std;

class Subtraction {
private:
int num1, num2;

public:
// Constructor to initialize numbers
Subtraction(int a, int b) {
num1 = a;
num2 = b;
}
// Friend function declaration
friend int subtract(Subtraction s);
};

// Friend function definition


int subtract(Subtraction s) {
return s.num1 - s.num2;
}

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

Subtraction obj(a, b);


cout << "Subtraction result: " << subtract(obj) << endl;

return 0;
}

3. Write a C++ program to overload function volume and find volume of cube, cylinder and
sphere.

#include <iostream>
using namespace std;

class VolumeCalculator {
public:
// Volume of cube
double volume(double side) {
return side * side * side;
}

// Volume of cylinder
double volume(double radius, double height) {
return 3.14159 * radius * radius * height;
}

// Volume of sphere
double volumeSphere(double radius) {
return (4.0 / 3.0) * 3.14159 * radius * radius * radius;
}
};

int main() {
VolumeCalculator vc;
double side, radius, height;

cout << "Enter side length of cube: ";


cin >> side;
cout << "Volume of cube: " << vc.volume(side) << endl;

cout << "Enter radius and height of cylinder: ";


cin >> radius >> height;
cout << "Volume of cylinder: " << vc.volume(radius, height) << endl;

cout << "Enter radius of sphere: ";


cin >> radius;
cout << "Volume of sphere: " << vc.volumeSphere(radius) << endl;

return 0;
}

4. Write a C++ program to calculate function to determine simple interest byusing default
arguments as
follows
int calculate(int p,int n=10,int r=7)- Returns SI by specifying no of years and rate of interest

#include <iostream>
using namespace std;

class SimpleInterest
{
public:
// Function to calculate simple interest with default arguments
int calculate(int p, int n = 10, int r = 7) {
return (p * n * r) / 100; // Simple Interest formula
}
};

int main() {
int principal, years, rate;

SimpleInterest siObj; // Object of the SimpleInterest class


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

// Calculate with default values for n and r


int si1 = siObj.calculate(principal);
cout << "Simple Interest (default years=10, rate=7%): " << si1 << endl;

// Calculate by specifying the number of years and rate


cout << "Enter the number of years: ";
cin >> years;
cout << "Enter the rate of interest: ";
cin >> rate;

int si2 = siObj.calculate(principal, years, rate);


cout << "Simple Interest (specified years and rate): " << si2 << endl;

return 0;
}

SET B :

1. Write a C++ program to create two classes Rectangle1 and Rectangle2.Compare area of
both the
rectangles using friend function.

#include <iostream>
using namespace std;

class Rectangle2; // Forward declaration of Rectangle2

class Rectangle1 {
int length, width;

public:
// Constructor to initialize Rectangle1 dimensions
Rectangle1(int l, int w)
{
length = l;
width = w ;
}
// Friend function declaration to compare areas
friend void compareArea(Rectangle1 r1, Rectangle2 r2);
};

class Rectangle2 {
int length, width;

public:
// Constructor to initialize Rectangle2 dimensions
Rectangle2(int l, int w)
{
length = l;
width = w ;
}

// Friend function declaration to compare areas


friend void compareArea(Rectangle1 r1, Rectangle2 r2);
};

// Friend function definition to compare areas of both rectangles


void compareArea(Rectangle1 r1, Rectangle2 r2) {
int area1 = r1.length * r1.width; // Area of Rectangle1
int area2 = r2.length * r2.width; // Area of Rectangle2

cout << "Area of Rectangle1: " << area1 << endl;


cout << "Area of Rectangle2: " << area2 << endl;

// Compare the areas


if (area1 > area2) {
cout << "Rectangle1 has a larger area." << endl;
} else if (area1 < area2) {
cout << "Rectangle2 has a larger area." << endl;
} else {
cout << "Both rectangles have the same area." << endl;
}
}

int main() {
int length1, width1, length2, width2;

// Input dimensions for Rectangle1


cout << "Enter length and width of Rectangle1: ";
cin >> length1 >> width1;
// Input dimensions for Rectangle2
cout << "Enter length and width of Rectangle2: ";
cin >> length2 >> width2;

// Create objects of Rectangle1 and Rectangle2


Rectangle1 r1(length1, width1);
Rectangle2 r2(length2, width2);

// Compare areas using the friend function


compareArea(r1, r2);

return 0;
}

2. 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:
int real, imag; // Real and imaginary parts of a complex number

public:
// Constructor to initialize the complex number
Complex(int r = 0, int i = 0)
{
real = r ;
imag = i;
}

// Function to display the complex number


void display() const {
cout << real << " + " << imag << "i" << endl;
}
// Friend function declaration to add two complex numbers
friend Complex addComplex(const Complex &c1, const Complex &c2);
};

// Friend function to add two complex numbers


Complex addComplex(const Complex &c1, const Complex &c2) {
int sumReal = c1.real + c2.real; // Adding real parts
int sumImag = c1.imag + c2.imag; // Adding imaginary parts
return Complex(sumReal, sumImag); // Returning the sum as a new Complex object
}

int main() {
int real1, imag1, real2, imag2;

// Input for first complex number


cout << "Enter real and imaginary part of first complex number: ";
cin >> real1 >> imag1;

// Input for second complex number


cout << "Enter real and imaginary part of second complex number: ";
cin >> real2 >> imag2;

// Create two Complex objects


Complex c1(real1, imag1);
Complex c2(real2, imag2);

// Display the two complex numbers


cout << "First Complex Number: ";
c1.display();
cout << "Second Complex Number: ";
c2.display();

// Add the complex numbers using the friend function


Complex sum = addComplex(c1, c2);

// Display the sum of the two complex numbers


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

return 0;
}
3. Create a class telephone containing name, telephone number and city as a data member and
write
necessary member functions for the following (use functionoverloading).
a. Search the telephone number with givenname
b. Search the name with given telephone number
c. Search all customer in a givencity

#include <iostream>
using namespace std;

class Telephone {
private:
string name;
string telephoneNumber;
string city;

public:
// Constructor to initialize Telephone object
Telephone(string n, string t, string c) : name(n), telephoneNumber(t), city(c) {}

// Function to display the details of the customer


void display() const {
cout << "Name: " << name << ", Telephone Number: " << telephoneNumber << ", City: " <<
city << endl;
}

// Function to search by name (function overloading)


static void searchByName(Telephone customers[], int size, string searchName) {
bool found = false;
for (int i = 0; i < size; i++) {
if (customers[i].name == searchName) {
customers[i].display();
found = true;
}
}
if (!found) {
cout << "No customer found with the name: " << searchName << endl;
}
}

// Function to search by telephone number (function overloading)


static void searchByTelephone(Telephone customers[], int size, string searchTelephone) {
bool found = false;
for (int i = 0; i < size; i++) {
if (customers[i].telephoneNumber == searchTelephone) {
customers[i].display();
found = true;
}
}
if (!found) {
cout << "No customer found with the telephone number: " << searchTelephone << endl;
}
}

// Function to search by city (function overloading)


static void searchByCity(Telephone customers[], int size, string searchCity) {
bool found = false;
for (int i = 0; i < size; i++) {
if (customers[i].city == searchCity) {
customers[i].display();
found = true;
}
}
if (!found) {
cout << "No customers found in the city: " << searchCity << endl;
}
}
};

int main() {
// Define a fixed array of customers
Telephone customers[4] = {
Telephone("Alice", "12345", "New York"),
Telephone("Bob", "67890", "Los Angeles"),
Telephone("Charlie", "11223", "New York"),
Telephone("David", "44556", "Chicago")
};

string name, telephone, city;

// Searching by name
cout << "Enter name to search: ";
cin >> name;
Telephone::searchByName(customers, 4, name);

// Searching by telephone number


cout << "Enter telephone number to search: ";
cin >> telephone;
Telephone::searchByTelephone(customers, 4, telephone);

// Searching by city
cout << "Enter city to search: ";
cin >> city;
Telephone::searchByCity(customers, 4, city);

return 0;
}

SET C :

1. Write a C++ program to implement a class „printdata‟ to overload „print‟ function asfollows:
void print(int) - outputs value - <int>, that is, value followed by the value of the integer. eg.
print(10)
outputs value -<10>
void print(char *) – outputs value –“char*”, that is, value followed by the string in double quotes.
eg
print(“hi”) outputs value-“hi”
void print(int n, char *)- display first n characters from the given string. eg print(3,”Object”)-
outputs
value –“Obj”

—>

#include <iostream>
#include <cstring> // For strncpy function
using namespace std;

class printdata {
public:
// Overloaded function to print an integer
void print(int num) {
cout << "value - <" << num << ">" << endl;
}

// Overloaded function to print a string


void print(const char* str) {
cout << "value - \"" << str << "\"" << endl;
}

// Overloaded function to print first n characters of a string


void print(int n, const char* str) {
cout << "value - \"";
for (int i = 0; i < n && str[i] != '\0'; i++) {
cout << str[i];
}
cout << "\"" << endl;
}
};

int main() {
printdata obj;

obj.print(10); // Outputs: value - <10>


obj.print("hi"); // Outputs: value - "hi"
obj.print(3, "Object"); // Outputs: value - "Obj"

return 0;
}

2. Write a C++ program to create two classes DM and DB which stores the value of distances.
DM stores
distance in m and cm and DB stores distance in feet and inches. Write a program that can read
valuefor
the class objects and add oneobject of DM with the other object of DB by using friend function.

#include <iostream>
using namespace std;

class DB; // Forward declaration

class DM {
float meters, centimeters;
public:
// Default Constructor
DM() {
meters = 0;
centimeters = 0;
}

// Parameterized Constructor
DM(float m, float cm) {
meters = m;
centimeters = cm;
}

// Function to input distance


void input() {
cout << "Enter distance in meters and centimeters: ";
cin >> meters >> centimeters;
}

// Friend function to add DM and DB


friend DM addDistance(DM, DB);

// Function to display distance


void display() {
cout << "Distance: " << meters << " meters and " << centimeters << " centimeters" << endl;
}
};

class DB {
float feet, inches;
public:
// Default Constructor
DB() {
feet = 0;
inches = 0;
}

// Parameterized Constructor
DB(float ft, float in) {
feet = ft;
inches = in;
}

// Function to input distance


void input() {
cout << "Enter distance in feet and inches: ";
cin >> feet >> inches;
}

// Friend function to add DM and DB


friend DM addDistance(DM, DB);
};
// Friend function to add DM and DB distances
DM addDistance(DM d1, DB d2) {
// Convert feet and inches to meters and centimeters
float totalMeters = d1.meters + (d2.feet * 0.3048);
float totalCentimeters = d1.centimeters + (d2.inches * 2.54);

// Adjust meters and centimeters properly


while (totalCentimeters >= 100) {
totalMeters += 1;
totalCentimeters -= 100;
}

return DM(totalMeters, totalCentimeters);


}

int main() {
DM dm;
DB db;

dm.input(); // Input for DM object


db.input(); // Input for DB object

DM result = addDistance(dm, db); // Add distances

result.display(); // Display result

return 0;
}

—-----------------------------------------------

SET C :
1. A book shop maintains the inventory of books that are being sold at the shop. The list
includes details
such as author_name, title, price, publisher, and stock position.If customer wants to purchase a
book he
gives details of book along with the number of copies required. If requested copies are available
the total
cost of requested copies is displayed; otherwise the message “Required copies not in stock” is
displayed.
Design a system using a class called Bookshop with suitable member functions and constructor.
(Use new
operator to allocate memory)

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

class Bookshop {
char *author_name;
char *title;
float price;
char *publisher;
int stock;

public:
// Constructor
Bookshop(const char *a, const char *t, float p, const char *pub, int s) {
author_name = new char[strlen(a) + 1];
strcpy(author_name, a);
title = new char[strlen(t) + 1];
strcpy(title, t);
price = p;
publisher = new char[strlen(pub) + 1];
strcpy(publisher, pub);
stock = s;
}

// Destructor to free allocated memory


~Bookshop() {
delete[] author_name;
delete[] title;
delete[] publisher;
}

// Function to display book details


void display() {
cout << "Author: " << author_name << "\nTitle: " << title
<< "\nPrice: " << price << "\nPublisher: " << publisher
<< "\nStock: " << stock << endl;
}

// Function to check availability and purchase books


void purchase(int copies) {
if (copies <= stock) {
cout << "Total cost: " << (copies * price) << endl;
stock -= copies;
} else {
cout << "Required copies not in stock" << endl;
}
}
};

int main() {
Bookshop book("J.K. Rowling", "Harry Potter", 499.99, "Bloomsbury", 10);
book.display();

int copies;
cout << "Enter number of copies to purchase: ";
cin >> copies;
book.purchase(copies);

return 0;
}

—-------------------------------------------------------------------------------------------------------------------------

ASSIGNMENT 6 :

SET A :

1. Write a C++ program to create a class Number. Write necessary member functions to
overload the operator unary pre and post increment „++ ‟ for an integernumber.

Sol :

#include <iostream>
using namespace std;

class Number {
private:
int value;

public:
// Simple Constructor
Number(int v) { value = v; }
// Display function
void display() {
cout << "Value: " << value << endl;
}

// Overloading pre-increment (++num)


Number operator++() {
++value;
return *this;
}

// Overloading post-increment (num++)


Number operator++(int) {
Number temp = *this; // Save current state
value++;
return temp; // Return old state
}
};

int main() {
Number num(5);
cout << "Initial: ";
num.display();

++num; // Pre-increment
cout << "After Pre-Increment: ";
num.display();

num++; // Post-increment
cout << "After Post-Increment: ";
num.display();

return 0;
}

2. Write a C++ program to create a class employee containing salary as a data member. Write
necessary member functions to overload the operator unary pre and post decrement “- -“ for
incrementing and decrementing salary.

Sol :

#include <iostream>
using namespace std;
class Employee {
private:
int salary;

public:
// Constructor
Employee(int s) { salary = s; }

// Display function
void display() {
cout << "Salary: " << salary << endl;
}

// Overloading pre-decrement (--emp)


Employee operator--() {
--salary;
return *this;
}

// Overloading post-decrement (emp--)


Employee operator--(int) {
Employee temp = *this; // Save current state
salary--;
return temp; // Return old state
}
};

int main() {
Employee emp(5000);
cout << "Initial: ";
emp.display();

--emp; // Pre-decrement
cout << "After Pre-Decrement: ";
emp.display();

emp--; // Post-decrement
cout << "After Post-Decrement: ";
emp.display();

return 0;
}
3 . Write a C++ program to create a class Array that contains one float array as member.
Overload the Unary ++ and -- operators to increase or decrease the value of each element of an
array. Use friend function for operator function.

Sol :

#include <iostream>
using namespace std;

class Array {
private:
float arr[5];

public:
// Constructor to initialize array
Array() {
for (int i = 0; i < 5; i++) {
arr[i] = i + 1.0; // Initialize with values 1.0, 2.0, 3.0, ...
}
}

// Display function
void display() {
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

// Friend function to overload pre-increment operator


friend void operator++(Array &a);

// Friend function to overload pre-decrement operator


friend void operator--(Array &a);
};

// Definition of overloaded pre-increment operator


void operator++(Array &a) {
for (int i = 0; i < 5; i++) {
a.arr[i]++;
}
}
// Definition of overloaded pre-decrement operator
void operator--(Array &a) {
for (int i = 0; i < 5; i++) {
a.arr[i]--;
}
}

int main() {
Array arr;
cout << "Initial Array: ";
arr.display();

++arr; // Increment each element


cout << "After Increment: ";
arr.display();

--arr; // Decrement each element


cout << "After Decrement: ";
arr.display();

return 0;
}

4. Write a program to design a class representing complex number and having the functionality
of performing addition & multiplication of two complex number using operatoroverloading

Sol :

#include <iostream>
using namespace std;

class Complex {
private:
float real, imag;

public:
// Constructor
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}

// Display function
void display() {
cout << real << " + " << imag << "i" << endl;
}

// Overloading + operator for addition


Complex operator+(const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}

// Overloading * operator for multiplication


Complex operator*(const Complex &c) {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
};

int main() {
Complex c1(2, 3), c2(4, 5);

cout << "First Complex Number: ";


c1.display();
cout << "Second Complex Number: ";
c2.display();

Complex sum = c1 + c2; // Addition


cout << "Addition: ";
sum.display();

Complex product = c1 * c2; // Multiplication


cout << "Multiplication: ";
product.display();

return 0;
}

SET B

1. Write a program to overload operators like *, <<, >>using friend functions .the following
overloaded operators should work for a class vector.

#include <iostream>
using namespace std;

class Vector {
private:
int x, y;

public:
// Constructor
Vector(int a = 0, int b = 0) {
x = a;
y = b;
}

// Friend function to overload * for scalar multiplication


friend Vector operator*(const Vector &v, int scalar);

// Friend function to overload << for output stream


friend ostream& operator<<(ostream &out, const Vector &v);

// Friend function to overload >> for input stream


friend istream& operator>>(istream &in, Vector &v);
};

// Overload * for scalar multiplication


Vector operator*(const Vector &v, int scalar) {
return Vector(v.x * scalar, v.y * scalar);
}

// Overload << for output stream


ostream& operator<<(ostream &out, const Vector &v) {
out << "(" << v.x << ", " << v.y << ")";
return out;
}

// Overload >> for input stream


istream& operator>>(istream &in, Vector &v) {
cout << "Enter x and y coordinates: ";
in >> v.x >> v.y;
return in;
}

int main() {
Vector v1, v2;
int scalar;

// Taking user input for vector


cin >> v1;
cout << "Enter scalar value: ";
cin >> scalar;

// Scalar multiplication
v2 = v1 * scalar;

// Displaying results
cout << "Original Vector: " << v1 << endl;
cout << "Vector after multiplication: " << v2 << endl;

return 0;
}

2 . Write a program for developing matrix classes which can handle integer matrices of different
dimensions. Also overload the operator for addition, multiplication and comparison of matrices.

#include <iostream>
using namespace std;

class Matrix {
private:
int rows, cols;
int **data; // Pointer for dynamic memory allocation

public:
// Constructor to initialize matrix with given dimensions
Matrix(int r = 2, int c = 2) {
rows = r;
cols = c;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}

// Destructor to free memory


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

// Overloaded >> operator for input


friend istream& operator>>(istream &in, Matrix &m) {
cout << "Enter elements of " << m.rows << "x" << m.cols << " matrix:\n";
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j++) {
in >> m.data[i][j];
}
}
return in;
}

// Overloaded << operator for output


friend ostream& operator<<(ostream &out, const Matrix &m) {
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j++) {
out << m.data[i][j] << " ";
}
out << endl;
}
return out;
}

// Overloaded + operator for matrix addition


Matrix operator+(const Matrix &m) {
if (rows != m.rows || cols != m.cols) {
cout << "Error: Matrices must have the same dimensions for addition.\n";
return Matrix(0, 0);
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] + m.data[i][j];
}
}
return result;
}

// Overloaded * operator for matrix multiplication


Matrix operator*(const Matrix &m) {
if (cols != m.rows) {
cout << "Error: Matrices cannot be multiplied (cols of A != rows of B).\n";
return Matrix(0, 0);
}
Matrix result(rows, m.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < m.cols; j++) {
result.data[i][j] = 0;
for (int k = 0; k < cols; k++) {
result.data[i][j] += data[i][k] * m.data[k][j];
}
}
}
return result;
}

// Overloaded == operator for matrix comparison


bool operator==(const Matrix &m) {
if (rows != m.rows || cols != m.cols) return false;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (data[i][j] != m.data[i][j])
return false;
}
}
return true;
}
};

int main() {
int r, c;
cout << "Enter dimensions for matrices (rows and columns): ";
cin >> r >> c;

Matrix A(r, c), B(r, c);

// Input matrices
cin >> A;
cin >> B;

// Addition
Matrix sum = A + B;
cout << "Matrix Addition Result:\n" << sum;

// Multiplication
Matrix product = A * B;
cout << "Matrix Multiplication Result:\n" << product;
// Comparison
if (A == B)
cout << "Matrices are equal.\n";
else
cout << "Matrices are not equal.\n";

return 0;
}

3 . Create a class String which contains a character pointer (Use new and delete operator).
Write a C++ program to overload following operators: ! To reverse the case of each alphabet
from given string [ ] To print a character present at specified index < To compare length of two
strings == To check equality of two strings + To concatenate twostrings

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

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

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

// Destructor to free allocated memory


~String() {
delete[] str;
}

// Overloading ! (Reverse case of each character)


void operator!() {
for (int i = 0; i < length; i++) {
if (isupper(str[i]))
str[i] = tolower(str[i]);
else if (islower(str[i]))
str[i] = toupper(str[i]);
}
}

// Overloading [] (Access character at index)


char operator[](int index) {
if (index < 0 || index >= length) {
cout << "Index out of bounds!" << endl;
return '\0';
}
return str[index];
}

// Overloading < (Compare lengths)


bool operator<(const String &s) {
return length < s.length;
}

// Overloading == (Check equality)


bool operator==(const String &s) {
return strcmp(str, s.str) == 0;
}

// Overloading + (Concatenation)
String operator+(const String &s) {
char *newStr = new char[length + s.length + 1]; // Allocating memory
strcpy(newStr, str);
strcat(newStr, s.str);
return String(newStr);
}

// Display function
void display() {
cout << str << endl;
}
};

// Main function
int main() {
String s1("Hello"), s2("World"), s3;

// Concatenation
s3 = s1 + s2;
cout << "Concatenated String: ";
s3.display();

// Reverse case
!s1;
cout << "String after case reversal: ";
s1.display();

// Accessing character at index


cout << "Character at index 1 in s1: " << s1[1] << endl;

// Comparing lengths
if (s1 < s2)
cout << "String 1 is shorter than String 2.\n";
else
cout << "String 1 is not shorter than String 2.\n";

// Checking equality
if (s1 == s2)
cout << "Strings are equal.\n";
else
cout << "Strings are not equal.\n";

return 0;
}

—------------------------------------------------------------------------------------------------------------------------

Assignment 7
Set A

1 . 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 appropriatemanipulators.

#include <iostream>
#include <iomanip>
using namespace std;
class Product {
protected:
int productId;
string productName;
float price;

public:
Product() {
productId = 0;
productName = "";
price = 0.0;
}
void setProduct(int id, string name, float p) {
productId = id;
productName = name;
price = p;
}
float getPrice() { return price; }
void display() {
cout << left << setw(10) << productId << setw(20) << productName << setw(10) << price;
}
};

class Discount : public Product {


private:
float discountPercentage;

public:
Discount() { discountPercentage = 0.0; }
void setDiscount(float d) { discountPercentage = d; }
float getDiscount() { return (price * discountPercentage) / 100; }
float getFinalPrice() { return price - getDiscount(); }
};

int main() {
int n;
cout << "Enter number of products: ";
cin >> n;
Discount products[n];
float totalPrice = 0, totalDiscount = 0;

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


int id;
string name;
float price, discount;
cout << "Enter Product ID, Name, Price and Discount: ";
cin >> id >> name >> price >> discount;
products[i].setProduct(id, name, price);
products[i].setDiscount(discount);
totalPrice += price;
totalDiscount += products[i].getDiscount();
}

cout << "\nBILL:\n";


cout << left << setw(10) << "ID" << setw(20) << "Name" << setw(10) << "Price" << endl;
cout << "-------------------------------------------\n";
for (int i = 0; i < n; i++) {
products[i].display();
cout << endl;
}
cout << "-------------------------------------------\n";
cout << "Total Price: " << totalPrice << endl;
cout << "Total Discount: " << totalDiscount << endl;
cout << "Final Price: " << totalPrice - totalDiscount << endl;
return 0;
}

2. Create three classes Car, Maruti and Maruti800.Class Maruti extends Car and Class Maruti80
0 extends Maruti.Maruti800 class is able to use the methods of both the classes (Car and
Maruti).

#include <iostream>
using namespace std;

class Car {
public:
void showCar() {
cout << "This is a Car." << endl;
}
};

class Maruti : public Car {


public:
void showMaruti() {
cout << "This is a Maruti Car." << endl;
}
};

class Maruti800 : public Maruti {


public:
void showMaruti800() {
cout << "This is a Maruti 800." << endl;
}
};

int main() {
Maruti800 m800;
m800.showCar();
m800.showMaruti();
m800.showMaruti800();
return 0;
}

3. . 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 drivenprogramto
Build a master table. Display a master table Display Project details in the ascending order of
duration.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Employee {
protected:
string name, designation;
public:
Employee(string n, string d) : name(n), designation(d) {}
};

class Project {
protected:
int projectId;
string title;
public:
Project(int id, string t) : projectId(id), title(t) {}
};

class Emp_Proj : public Employee, public Project {


private:
int duration;
public:
Emp_Proj(string n, string d, int id, string t, int dur) : Employee(n, d), Project(id, t),
duration(dur) {}

void display() {
cout << "Name: " << name << ", Designation: " << designation
<< ", Project ID: " << projectId << ", Title: " << title
<< ", Duration: " << duration << " months" << endl;
}
int getDuration() { return duration; }
};

bool compareDuration(Emp_Proj* a, Emp_Proj* b) {


return a->getDuration() < b->getDuration();
}

int main() {
vector<Emp_Proj*> records;
records.push_back(new Emp_Proj("Alice", "Manager", 101, "AI Project", 12));
records.push_back(new Emp_Proj("Bob", "Developer", 102, "Web App", 8));
records.push_back(new Emp_Proj("Charlie", "Designer", 103, "UI Design", 10));

cout << "Master Table:\n";


for (auto emp : records) emp->display();

sort(records.begin(), records.end(), compareDuration);

cout << "\nProjects sorted by duration:\n";


for (auto emp : records) emp->display();

return 0;
}

4. . 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: Enter details of „n‟ reservations Display details of all
reservations Display reservation details of a Business class

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

class Flight {
protected:
int flightNo;
string flightName;
public:
Flight(int no, string name) : flightNo(no), flightName(name) {}
};

class Route : public Flight {


protected:
string source, destination;
public:
Route(int no, string name, string src, string dest) : Flight(no, name), source(src),
destination(dest) {}
};

class Reservation : public Route {


private:
int numberOfSeats;
string seatClass;
float fare;
string travelDate;
public:
Reservation(int no, string name, string src, string dest, int seats, string sClass, float f, string
date)
: Route(no, name, src, dest), numberOfSeats(seats), seatClass(sClass), fare(f),
travelDate(date) {}

void display() {
cout << "Flight No: " << flightNo << ", Flight Name: " << flightName
<< "\nRoute: " << source << " to " << destination
<< "\nSeats: " << numberOfSeats << ", Class: " << seatClass
<< "\nFare: " << fare << ", Date: " << travelDate << "\n\n";
}
string getClass() { return seatClass; }
};

int main() {
vector<Reservation*> reservations;
reservations.push_back(new Reservation(101, "Air India", "Mumbai", "Delhi", 2, "Business",
15000, "10-02-2025"));
reservations.push_back(new Reservation(102, "Indigo", "Pune", "Bangalore", 1, "Economy",
5000, "12-02-2025"));
reservations.push_back(new Reservation(103, "Vistara", "Chennai", "Kolkata", 3, "Business",
18000, "15-02-2025"));

cout << "All Reservations:\n";


for (auto res : reservations) res->display();

cout << "\nBusiness Class Reservations:\n";


for (auto res : reservations) {
if (res->getClass() == "Business") res->display();
}

return 0;
}

SET B :

1.

#include <iostream>
using namespace std;

class Account {
protected:
string acc_holder_name;
string acc_holder_contact_no;

public:
Account(string name, string contact) {
acc_holder_name = name;
acc_holder_contact_no = contact;
}
virtual void deposit(float amount) = 0;
virtual void withdraw(float amount) = 0;
virtual void display() = 0;
};

class Saving_Account : public Account {


int s_acc_no;
float balance;
static constexpr float interest_rate = 0.10;
static constexpr float min_balance = 2000;
static constexpr float service_charge = 500;

public:
Saving_Account(string name, string contact, int acc_no, float bal) : Account(name, contact),
s_acc_no(acc_no), balance(bal) {}

void deposit(float amount) override {


balance += amount;
cout << "Amount Deposited Successfully. New Balance: " << balance << endl;
}

void withdraw(float amount) override {


if (balance - amount < min_balance) {
balance -= service_charge;
cout << "Balance fell below minimum. Service charge of " << service_charge << "
imposed." << endl;
} else {
balance -= amount;
cout << "Withdrawal Successful. New Balance: " << balance << endl;
}
}

void calculateInterest() {
float interest = balance * interest_rate;
balance += interest;
cout << "Interest Added: " << interest << " New Balance: " << balance << endl;
}

void display() override {


cout << "Saving Account Holder: " << acc_holder_name << " | Contact: " <<
acc_holder_contact_no << " | Acc No: " << s_acc_no << " | Balance: " << balance << endl;
}
};

class Current_Account : public Account {


int c_acc_no;
float balance;
static constexpr float min_balance = 5000;
static constexpr float service_charge = 1000;

public:
Current_Account(string name, string contact, int acc_no, float bal) : Account(name, contact),
c_acc_no(acc_no), balance(bal) {}
void deposit(float amount) override {
balance += amount;
cout << "Amount Deposited Successfully. New Balance: " << balance << endl;
}

void withdraw(float amount) override {


if (balance - amount < min_balance) {
balance -= service_charge;
cout << "Balance fell below minimum. Service charge of " << service_charge << "
imposed." << endl;
} else {
balance -= amount;
cout << "Withdrawal Successful. New Balance: " << balance << endl;
}
}

void display() override {


cout << "Current Account Holder: " << acc_holder_name << " | Contact: " <<
acc_holder_contact_no << " | Acc No: " << c_acc_no << " | Balance: " << balance << endl;
}
};

int main() {
Saving_Account sa("John Doe", "9876543210", 101, 3000);
Current_Account ca("Jane Doe", "1234567890", 201, 6000);
int choice;
do {
cout << "\nBank Menu:\n1. Deposit\n2. Withdraw\n3. Calculate Interest (Savings Only)\n4.
Display Account Info\n5. Exit\nEnter choice: ";
cin >> choice;
float amount;
switch (choice) {
case 1:
cout << "Enter amount to deposit: ";
cin >> amount;
sa.deposit(amount);
ca.deposit(amount);
break;
case 2:
cout << "Enter amount to withdraw: ";
cin >> amount;
sa.withdraw(amount);
ca.withdraw(amount);
break;
case 3:
sa.calculateInterest();
break;
case 4:
sa.display();
ca.display();
break;
case 5:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice! Try again." << endl;
}
} while (choice != 5);
return 0;
}

—----------------------------------------------------

Assignment 8 :

1.

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

class Shape {
public:
virtual void display() {
cout << "This is a shape." << endl;
}
virtual double area() = 0; // Pure virtual function
};

class Circle : public Shape


{
double radius;
public:
Circle(double r)
{
radius = r;
}
void display() {
cout << "Shape: Circle\nRadius: " << radius << endl;
}
double area()
{
return M_PI * radius * radius;
}
};

class Rectangle : public Shape


{
double length, width;
public:
Rectangle(double l, double w)
{
length = l;
width = w;

}
void display()
{
cout << "Shape: Rectangle\nLength: " << length << " Width: " << width << endl;
}
double area()
{
return length * width;
}
};

class Trapezoid : public Shape


{
double base1, base2, height;
public:
Trapezoid(double b1, double b2, double h)
{ base1 = b1;
base2 = b2;
height = h;

}
void display() {
cout << "Shape: Trapezoid\nBase1: " << base1 << " Base2: " << base2 << " Height: " <<
height << endl;
}
double area()
{
return 0.5 * (base1 + base2) * height;
}
};

int main()
{
Shape* shapes[3];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
shapes[2] = new Trapezoid(3, 5, 4);

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


shapes[i]->display();
cout << "Area: " << shapes[i]->area() << "\n\n";
}

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


delete shapes[i];
}

return 0;
}

Set B

1.

#include <iostream>
using namespace std;

class Student {
public:
virtual void display() = 0; // Pure virtual function
};

class Engineering : public Student {


public:
void display() {
cout << "Engineering Student" << endl;
}
};

class Medicine : public Student {


public:
void display() {
cout << "Medicine Student" << endl;
}
};

class Science : public Student {


public:
void display() {
cout << "Science Student" << endl;
}
};

int main() {
Student* students[3];
students[0] = new Engineering();
students[1] = new Medicine();
students[2] = new Science();

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


students[i]->display();
}

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


delete students[i];
}

return 0;
}

—----------------------------------------------------------------------------------------------------------------------------

Assignment 8
Set A

1.​ Write a C++ program to create a class shape with functions to find area of the shapes
and display the name of the shape and other essential component of the class. Create
derived classes circle, rectangle and trapezoid each having overridden functions area
and display. Write a suitable program to illustrate virtual functions.
Sol:

#include <iostream>
#include <cmath>

using namespace std;

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

// Derived class - Circle


class Circle : public Shape
{
private:
double radius;
public:
Circle(double r)
{
radius = r;
}

void display() const override {


cout << "Shape: Circle\n";
}

double area() const override {


return M_PI * radius * radius;
}
};

// Derived class - Rectangle


class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w)
{
length = l;
width = w;
}

void display() const override {


cout << "Shape: Rectangle\n";
}

double area() const override {


return length * width;
}
};

// Derived class - Trapezoid


class Trapezoid : public Shape {
private:
double base1, base2, height;
public:
Trapezoid(double b1, double b2, double h)
{
base1 = b1;
base2 = b2;
height = h;
}
void display() const override {
cout << "Shape: Trapezoid\n";
}

double area() const override {


return 0.5 * (base1 + base2) * height;
}
};

int main() {
Shape* shapes[3];

shapes[0] = new Circle(5.0);


shapes[1] = new Rectangle(4.0, 6.0);
shapes[2] = new Trapezoid(3.0, 5.0, 4.0);

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


shapes[i]->display();
cout << "Area: " << shapes[i]->area() << "\n\n";
}

// Clean up memory
for (int i = 0; i < 3; ++i) {
delete shapes[i];
}

return 0;
}

2 .A book (ISBN) and CD (data capacity) are both types of media (id, title) objects. A
person buys 10 media items, each of which can be either book or CD. Display the list of
all books and CD‟s bought. Define the classes and appropriate member functions to
accept and display data. Use pointers and concepts of polymorphism (virtualfunctions).

Soln :

#include <iostream>
using namespace std;

// Base class
class Media {
protected:
int id;
string title;
public:
Media(int i, string t) {
id = i;
title = t;
}

virtual void display() {


cout << "ID: " << id << "\nTitle: " << title << endl;
}

virtual ~Media() {} // Virtual destructor


};

// Derived class - Book


class Book : public Media {
private:
string ISBN;
public:
Book(int i, string t, string isbn) : Media(i, t) {
ISBN = isbn;
}
void display() override {
cout << "Book Details:\n";
Media::display();
cout << "ISBN: " << ISBN << "\n\n";
}
};

// Derived class - CD
class CD : public Media {
private:
int capacity; // Capacity in MB
public:
CD(int i, string t, int cap) : Media(i, t) {
capacity = cap;
}

void display() override {


cout << "CD Details:\n";
Media::display();
cout << "Capacity: " << capacity << " MB\n\n";
}
};

int main() {
Media* items[10]; // Array of pointers to Media objects

items[0] = new Book(101, "C++ Programming", "978-316-1484100");


items[1] = new CD(102, "Classic Hits", 700);
items[2] = new Book(103, "Data Structures", "978-123-4567897");
items[3] = new CD(104, "Rock Collection", 650);
items[4] = new Book(105, "Artificial Intelligence", "978-012-3456789");
items[5] = new CD(106, "Jazz Essentials", 800);
items[6] = new Book(107, "Machine Learning", "978-099-8765432");
items[7] = new CD(108, "Pop Anthems", 750);
items[8] = new Book(109, "Deep Learning", "978-345-6789012");
items[9] = new CD(110, "Hip-Hop Beats", 900);

cout << "Media Items Purchased:\n\n";


for (int i = 0; i < 10; i++) {
items[i]->display();
}

// Free allocated memory


for (int i = 0; i < 10; i++) {
delete items[i];
}

return 0;
}

3. Create a base class Student (Roll_No, Name) which derives two classes Theory and
Practical. Theory class contains marks of five Subjects and Practical class contains
marks of two practical subjects. Class Result (Total_Marks, Class) inherits both Theory
and Practical classes. (Use concept of Virtual Base Class) Write a C++ menu driven
program to perform the following functions: Build a master table Display a master table
Calculate Total_marks and class obtained.

Soln :

#include <iostream>
using namespace std;

// Base class: Student


class Student {
protected:
int Roll_No;
string Name;

public:
Student(int r, string n) {
Roll_No = r;
Name = n;
}

void displayStudent() {
cout << "Roll No: " << Roll_No << "\nName: " << Name << endl;
}
};

// Derived class: Theory (Virtual Base Class)


class Theory : virtual public Student {
protected:
int theoryMarks[5];

public:
Theory(int r, string n, int marks[]) : Student(r, n) {
for (int i = 0; i < 5; i++) {
theoryMarks[i] = marks[i];
}
}

void displayTheory() {
cout << "Theory Marks: ";
for (int i = 0; i < 5; i++) {
cout << theoryMarks[i] << " ";
}
cout << endl;
}

int getTheoryTotal() {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += theoryMarks[i];
}
return sum;
}
};

// Derived class: Practical (Virtual Base Class)


class Practical : virtual public Student {
protected:
int practicalMarks[2];

public:
Practical(int r, string n, int marks[]) : Student(r, n) {
for (int i = 0; i < 2; i++) {
practicalMarks[i] = marks[i];
}
}

void displayPractical() {
cout << "Practical Marks: ";
for (int i = 0; i < 2; i++) {
cout << practicalMarks[i] << " ";
}
cout << endl;
}

int getPracticalTotal() {
return practicalMarks[0] + practicalMarks[1];
}
};

// Derived class: Result (Inherits Theory & Practical)


class Result : public Theory, public Practical {
private:
int Total_Marks;
string ClassObtained;

public:
Result(int r, string n, int tMarks[], int pMarks[]) : Student(r, n), Theory(r, n, tMarks),
Practical(r, n, pMarks) {
Total_Marks = getTheoryTotal() + getPracticalTotal();
if (Total_Marks >= 400)
ClassObtained = "First Class";
else if (Total_Marks >= 300)
ClassObtained = "Second Class";
else
ClassObtained = "Fail";
}

void displayResult() {
displayStudent();
displayTheory();
displayPractical();
cout << "Total Marks: " << Total_Marks << "\nClass Obtained: " << ClassObtained
<< "\n\n";
}
};

// Main Function (Menu-Driven)


int main() {
int choice, n;
cout << "Enter number of students: ";
cin >> n;
Result* students[n];

do {
cout << "\nMenu:\n1. Build Master Table\n2. Display Master Table\n3. Exit\nEnter
your choice: ";
cin >> choice;

switch (choice) {
case 1:
for (int i = 0; i < n; i++) {
int roll;
string name;
int tMarks[5], pMarks[2];

cout << "Enter Roll No: ";


cin >> roll;
cout << "Enter Name: ";
cin.ignore();
getline(cin, name);

cout << "Enter 5 Theory Marks: ";


for (int j = 0; j < 5; j++) cin >> tMarks[j];

cout << "Enter 2 Practical Marks: ";


for (int j = 0; j < 2; j++) cin >> pMarks[j];

students[i] = new Result(roll, name, tMarks, pMarks);


}
cout << "\nMaster Table Created Successfully!\n";
break;

case 2:
cout << "\nMaster Table:\n";
for (int i = 0; i < n; i++) {
students[i]->displayResult();
}
break;

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

default:
cout << "Invalid Choice! Try Again.\n";
}
} while (choice != 3);

// Free allocated memory


for (int i = 0; i < n; i++) {
delete students[i];
}

return 0;
}
Set B :

1.​ Write a program with Student as abstract class and create derive classes
Engineering, Medicine and Science from base class Student. Create the objects
of the derived classes and process them and access them using array of pointer
of type base classStudent.

Soln :

​ ​ #include <iostream>
using namespace std;

// Abstract Base Class


class Student {
protected:
string name;
int rollNo;

public:
Student(string n, int r) {
name = n;
rollNo = r;
}

virtual void display() = 0; // Pure virtual function (Abstract Class)


virtual ~Student() {} // Virtual destructor
};

// Derived Class: Engineering


class Engineering : public Student {
private:
string branch;

public:
Engineering(string n, int r, string b) : Student(n, r) {
branch = b;
}

void display() override {


cout << "Engineering Student\n";
cout << "Name: " << name << "\nRoll No: " << rollNo << "\nBranch: " << branch << "\n\n";
}
};
// Derived Class: Medicine
class Medicine : public Student {
private:
string specialization;

public:
Medicine(string n, int r, string s) : Student(n, r) {
specialization = s;
}

void display() override {


cout << "Medicine Student\n";
cout << "Name: " << name << "\nRoll No: " << rollNo << "\nSpecialization: " <<
specialization << "\n\n";
}
};

// Derived Class: Science


class Science : public Student {
private:
string subject;

public:
Science(string n, int r, string sub) : Student(n, r) {
subject = sub;
}

void display() override {


cout << "Science Student\n";
cout << "Name: " << name << "\nRoll No: " << rollNo << "\nSubject: " << subject << "\n\n";
}
};

int main() {
// Array of Base Class Pointers
Student* students[3];

// Creating objects of derived classes and storing in base class pointers


students[0] = new Engineering("Alice", 101, "Computer Science");
students[1] = new Medicine("Bob", 102, "Cardiology");
students[2] = new Science("Charlie", 103, "Physics");

// Displaying Student Information


cout << "Student Details:\n\n";
for (int i = 0; i < 3; i++) {
students[i]->display();
}

// Free allocated memory


for (int i = 0; i < 3; i++) {
delete students[i];
}

return 0;
}

2. Create a class called LIST with two pure virtual function store() and retrieve(). To store a
value call store and to retrieve call retrieves function. Derive two classes stack and queue from it
and orverride store and retrieve.

#include <iostream>
using namespace std;

// Abstract Base Class


class LIST {
public:
virtual void store(int value) = 0; // Pure virtual function
virtual int retrieve() = 0; // Pure virtual function
virtual ~LIST() {} // Virtual destructor
};

// Derived Class: Class1


class stack : public LIST {
private:
int data;

public:
void store(int value) override {
data = value;
cout << "Stored in Class1: " << data << endl;
}

int retrieve() override {


cout << "Retrieved from Class1: " << data << endl;
return data;
}
};

// Derived Class: Class2


class queue : public LIST {
private:
int data;

public:
void store(int value) override {
data = value;
cout << "Stored in Class2: " << data << endl;
}

int retrieve() override {


cout << "Retrieved from Class2: " << data << endl;
return data;
}
};

// Main Function
int main() {
LIST* obj1 = new stack(); // Pointer to Class1
LIST* obj2 = new queue(); // Pointer to Class2

obj1->store(10);
obj2->store(20);

obj1->retrieve();
obj2->retrieve();

// Free memory
delete obj1;
delete obj2;

return 0;
}

3 . Create a base class Person ( P_Code, P_Name). Derive two classes Account(Ac_No.,
Balance) and Official(Designation, Experience) from Person. Further derive another class
Employee from both Account and Official classes. (Use Concept of VirtualBaseClass) Write a
C++ menu driven program to perform the following functions: Build a master table for „n‟
employees. Display a master table of „n‟ employees. Display employees whose designation is
H.O.D

Sol :

#include <iostream>
using namespace std;

// Base Class: Person (Virtual Base Class)


class Person {
protected:
int P_Code;
string P_Name;

public:
Person(int code, string name) {
P_Code = code;
P_Name = name;
}
};

// Derived Class: Account (Virtual Base Class)


class Account : virtual public Person {
protected:
int Ac_No;
double Balance;

public:
Account(int code, string name, int acNo, double balance)
: Person(code, name) {
Ac_No = acNo;
Balance = balance;
}
};

// Derived Class: Official (Virtual Base Class)


class Official : virtual public Person {
protected:
string Designation;
int Experience;

public:
Official(int code, string name, string desig, int exp)
: Person(code, name) {
Designation = desig;
Experience = exp;
}
};

// Derived Class: Employee (Inheriting from Account & Official)


class Employee : public Account, public Official {
public:
Employee(int code, string name, int acNo, double balance, string desig, int exp)
: Person(code, name), Account(code, name, acNo, balance), Official(code, name, desig,
exp) {}

void display() {
cout << "P_Code: " << P_Code << ", P_Name: " << P_Name
<< ", Ac_No: " << Ac_No << ", Balance: " << Balance
<< ", Designation: " << Designation << ", Experience: " << Experience << " years\n";
}

bool isHOD() {
return Designation == "H.O.D";
}
};

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

Employee* employees[n]; // Array of pointers to Employee objects

// Input Employee Data


for (int i = 0; i < n; i++) {
int code, acNo, exp;
string name, desig;
double balance;

cout << "Enter P_Code, P_Name, Ac_No, Balance, Designation, Experience:\n";


cin >> code >> name >> acNo >> balance >> desig >> exp;

employees[i] = new Employee(code, name, acNo, balance, desig, exp);


}
// Display Master Table
cout << "\nMaster Table of Employees:\n";
for (int i = 0; i < n; i++) {
employees[i]->display();
}

// Display Employees with Designation "H.O.D"


cout << "\nEmployees with Designation 'H.O.D':\n";
for (int i = 0; i < n; i++) {
if (employees[i]->isHOD()) {
employees[i]->display();
}
}

// Free allocated memory


for (int i = 0; i < n; i++) {
delete employees[i];
}

return 0;
}

4 . Create a base class Student(Roll_No, Name, Class) which derives two classes
Internal_Marks(IntM1, IntM2, IntM3, IntM4, IntM5) and External_Marks(ExtM1 ExtM2, ExtM3,
ExtM4, ExtM5). Class Result(T1, T2, T3, T4, T5) inherits both Internal_Marks and
External_Marks classes. (Use Virtual Base Class) Write a C++ menu driven program to perform
the following functions: To Accept and display student details Calculate Subject wise total marks
obtained. Check whether student has passed in Internal and External Exam of each subject.
Also check whether he has passed in respective subject or not and display result accordingly.

Sol :

#include <iostream>
using namespace std;

// Base Class: Student (Virtual Base Class)


class Student {
protected:
int Roll_No;
string Name;
string ClassName;

public:
Student(int roll, string name, string cls) {
Roll_No = roll;
Name = name;
ClassName = cls;
}

void displayStudentDetails() {
cout << "Roll No: " << Roll_No << ", Name: " << Name << ", Class: " << ClassName <<
endl;
}
};

// Derived Class: Internal_Marks (Virtual Base Class)


class Internal_Marks : virtual public Student {
protected:
int IntM[5]; // Internal marks for 5 subjects

public:
Internal_Marks(int roll, string name, string cls, int m1, int m2, int m3, int m4, int m5)
: Student(roll, name, cls) {
IntM[0] = m1;
IntM[1] = m2;
IntM[2] = m3;
IntM[3] = m4;
IntM[4] = m5;
}
};

// Derived Class: External_Marks (Virtual Base Class)


class External_Marks : virtual public Student {
protected:
int ExtM[5]; // External marks for 5 subjects

public:
External_Marks(int roll, string name, string cls, int m1, int m2, int m3, int m4, int m5)
: Student(roll, name, cls) {
ExtM[0] = m1;
ExtM[1] = m2;
ExtM[2] = m3;
ExtM[3] = m4;
ExtM[4] = m5;
}
};
// Derived Class: Result (Inheriting from Internal_Marks & External_Marks)
class Result : public Internal_Marks, public External_Marks {
private:
int Total[5]; // Total marks per subject

public:
Result(int roll, string name, string cls, int im1, int im2, int im3, int im4, int im5,
int em1, int em2, int em3, int em4, int em5)
: Student(roll, name, cls), Internal_Marks(roll, name, cls, im1, im2, im3, im4, im5),
External_Marks(roll, name, cls, em1, em2, em3, em4, em5) {
for (int i = 0; i < 5; i++) {
Total[i] = IntM[i] + ExtM[i];
}
}

void displayResult() {
displayStudentDetails();
cout << "----------------------------------------------------\n";
cout << "Subject | Internal | External | Total | Status\n";
cout << "----------------------------------------------------\n";

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


string status = (IntM[i] >= 10 && ExtM[i] >= 10 && Total[i] >= 35) ? "Pass" : "Fail";
cout << "Sub " << i + 1 << " | " << IntM[i] << " | " << ExtM[i] << " | " << Total[i] <<
" | " << status << endl;
}

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


}
};

// Function to display menu


void menu() {
cout << "\nMenu:\n";
cout << "1. Accept Student Details\n";
cout << "2. Display Student Result\n";
cout << "3. Exit\n";
cout << "Enter your choice: ";
}

int main() {
Result* student = nullptr;
int choice;
do {
menu();
cin >> choice;

switch (choice) {
case 1: {
int roll, im[5], em[5];
string name, cls;

cout << "Enter Roll No, Name, Class: ";


cin >> roll >> name >> cls;

cout << "Enter 5 Internal Marks: ";


for (int i = 0; i < 5; i++) cin >> im[i];

cout << "Enter 5 External Marks: ";


for (int i = 0; i < 5; i++) cin >> em[i];

// Creating student object dynamically


student = new Result(roll, name, cls, im[0], im[1], im[2], im[3], im[4],
em[0], em[1], em[2], em[3], em[4]);
break;
}

case 2:
if (student) {
student->displayResult();
} else {
cout << "No student data available. Please enter details first.\n";
}
break;

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

default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != 3);

// Free allocated memory


delete student;
return 0;
}

—--------------------------------------------------------------------------------------------------------------------------

Assignment 9
Set A

1 . Write a C++ program to read a text file and count number of Upper case Alphabets, Lower
Case Alphabets Digits and Spaces using File Handling.

Sol :

#include <iostream>
#include <fstream>

using namespace std;

int main() {
ifstream file("input.txt"); // Open the file

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

char ch;
int upperCase = 0, lowerCase = 0, digits = 0, spaces = 0;

while (file.get(ch)) { // Read character by character


if (isupper(ch)) {
upperCase++;
} else if (islower(ch)) {
lowerCase++;
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
spaces++;
}
}

file.close(); // Close the file

// Display the counts


cout << "Uppercase Letters: " << upperCase << endl;
cout << "Lowercase Letters: " << lowerCase << endl;
cout << "Digits: " << digits << endl;
cout << "Spaces: " << spaces << endl;

return 0;
}

2 . Write a C++ program to read integers from a text file and display sum of all integers in that
file.

#include <iostream>
#include <fstream>

using namespace std;

int main() {
ifstream file("numbers.txt"); // Open the file

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

int num, sum = 0;

while (file >> num) { // Read integers from file


sum += num;
}

file.close(); // Close the file

// Display the sum


cout << "Sum of all integers: " << sum << endl;

return 0;
}

3. Write a C++ program to count the occurrence of a word in a file using filehandling.

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

int main() {
ifstream file("input.txt"); // Open the file

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

string word, searchWord;


int count = 0;

cout << "Enter the word to search: ";


cin >> searchWord;

while (file >> word) { // Read words from file


if (word == searchWord) {
count++;
}
}

file.close(); // Close the file

// Display the count


cout << "The word '" << searchWord << "' appears " << count << " times in the file." << endl;

return 0;
}

4. . Write a C++ program using function to count and display the number of lines not starting
with alphabet “A” in a text file

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

using namespace std;

int countLinesNotStartingWithA(const string& filename) {


ifstream file(filename); // Open the file

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

string line;
int count = 0;

while (getline(file, line)) { // Read lines from file


if (line.empty() || line[0] != 'A' && line[0] != 'a') {
count++;
}
}

file.close(); // Close the file


return count;
}

int main() {
string filename = "input.txt";
int result = countLinesNotStartingWithA(filename);

if (result != -1) {
cout << "Number of lines not starting with 'A': " << result << endl;
}

return 0;
}

Set B

1.​ Write a C++ program that copies the contents of one file to another.

Sol :

#include <iostream>
#include <fstream>

using namespace std; // Importing the standard namespace

int main() {
​ string sourceFile, destinationFile;
​ // Ask user for file names
​ cout << "Enter the source file name: ";
​ cin >> sourceFile;
​ cout << "Enter the destination file name: ";
​ cin >> destinationFile;

​ // Open source file for reading (text mode by default)


​ ifstream inputFile(sourceFile);

​ // Check if source file opened successfully


​ if (!inputFile) {
​ cerr << "Error: Could not open source file!\n";
​ return 1; // Exit with error
​ }

​ // Open destination file for writing (text mode by default)


​ ofstream outputFile(destinationFile);

​ // Check if destination file opened successfully


​ if (!outputFile) {
​ cerr << "Error: Could not create destination file!\n";
​ return 1; // Exit with error
​ }

​ // Copy line by line


​ string line;
​ while (getline(inputFile, line)) {
​ outputFile << line << endl; // Write line to output file
​ }

​ // Close files
​ inputFile.close();
​ outputFile.close();

​ cout << "File copied successfully!\n";


​ return 0; // Exit successfully
}

2. 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>

using namespace std;

// Function to check if a word starts with a lowercase vowel


bool startsWithVowel(const string& word) {
​ char firstChar = word[0]; // Get the first character of the word
​ return (firstChar == 'a' || firstChar == 'e' || firstChar == 'i' ||
​ firstChar == 'o' || firstChar == 'u');
}

// Function to process FIRST.TXT and create SECOND.TXT


void vowelwords() {
​ ifstream inputFile("FIRST.TXT"); // Open the source file for reading
​ ofstream outputFile("SECOND.TXT"); // Open the destination file for writing

​ if (!inputFile) {
​ cerr << "Error: Could not open FIRST.TXT!\n";
​ return;
​ }

​ if (!outputFile) {
​ cerr << "Error: Could not create SECOND.TXT!\n";
​ return;
​ }

​ string line, word;

​ // Read the file line by line


​ while (getline(inputFile, line)) {
​ stringstream ss(line); // Convert line into stream for word extraction
​ while (ss >> word) { // Extract words one by one
​ if (startsWithVowel(word)) {
​ outputFile << word << " "; // Write the word to SECOND.TXT
​ }
​ }
​ }

​ // Close files
​ inputFile.close();
​ outputFile.close();

​ cout << "Words starting with lowercase vowels have been saved in SECOND.TXT\n";
}

// Main function
int main() {
​ vowelwords(); // Call the function to process files
​ return 0;
}

3 . Write a C++ program to read student information such as rollno, name and percentage of n
students. Write the student information using file handling.

Sol :

#include <iostream>
#include <fstream>

using namespace std;

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

​ // Open file in write mode


​ ofstream outFile("students.txt");

​ if (!outFile) {
​ cerr << "Error: Could not create file!\n";
​ return 1;
​ }

​ // Input student details and write to file


​ for (int i = 0; i < n; i++) {
​ int rollNo;
​ string name;
​ float percentage;

​ cout << "Enter Roll No: ";


​ cin >> rollNo;
​ cin.ignore(); // Ignore newline character
​ cout << "Enter Name: ";
​ getline(cin, name);
​ cout << "Enter Percentage: ";
​ cin >> percentage;

​ outFile << rollNo << " " << name << " " << percentage << endl;
​ }

​ // Close the file


​ outFile.close();

​ cout << "Student details saved to students.txt successfully!\n";

​ return 0;
}
Tab 2

You might also like