C Practical Solutions
C Practical Solutions
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;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter the number for the multiplication table: ";
cin >> number;
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;
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;
}
#include <iostream>
using namespace std;
int main() {
int num, original, reversed = 0, 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 << "Factors of " << num << " are: ";
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
cout << i << " ";
}
}
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "The result of the series is: " << sum << endl;
return 0;
}
OR
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "The result of the series is: " << sum << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int decimal;
string hexadecimal = "";
cout << "The hexadecimal equivalent is: " << hexadecimal << endl;
return 0;
}
Explanation :
Explanation:
input : 255
Output : FF
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.
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.
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.
Conversion Steps:
—----------------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
int main() {
int number;
bool found = false;
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;
}
int main() {
Cylinder cylinder1, cylinder2;
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
return result;
}
};
int main() {
DISTANCE d1, d2, d3;
// Input distances
cout << "Enter the first distance:" << endl;
d1.inputDistance();
// Output distances
cout << "The first distance is: ";
d1.outputDistance();
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;
}
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
int main() {
String s1;
String s2;
// 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;
int main() {
int n, year;
cout << "Enter number of departments: ";
cin >> 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 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];
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;
}
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;
return result;
}
};
int main() {
DISTANCE d1, d2, d3;
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;
}
// 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;
}
#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);
}
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;
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];
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;
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;
}
int main() {
// Creating objects using default constructor
Number num1;
num1.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;
}
int main() {
// Creating objects using the parameterized constructor
SimpleInterest si1(10000, 2); // Default rate of 5.0% will be used
si1.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;
}
int main() {
// Creating a Mobile object using the parameterized constructor
Mobile mobile1(101, "Samsung Galaxy", 24999.99);
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;
}
int main() {
int n;
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;
}
int main() {
// Using default constructor
Point p1;
p1.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;
}
int main() {
int day, month, year;
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
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];
}
}
int main() {
int n;
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;
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;
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);
}
int main() {
int num;
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];
}
}
}
int main() {
int m, n;
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
}
int main() {
// Create two strings
String str1("Hello, ");
String str2("World!");
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;
int main() {
double radius, side, length, width;
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);
};
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
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;
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;
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 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 ;
}
int main() {
int length1, width1, length2, width2;
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;
}
int main() {
int real1, imag1, real2, imag2;
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) {}
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")
};
// Searching by name
cout << "Enter name to search: ";
cin >> name;
Telephone::searchByName(customers, 4, name);
// 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;
}
int main() {
printdata 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 DM {
float meters, centimeters;
public:
// Default Constructor
DM() {
meters = 0;
centimeters = 0;
}
// Parameterized Constructor
DM(float m, float cm) {
meters = m;
centimeters = cm;
}
class DB {
float feet, inches;
public:
// Default Constructor
DB() {
feet = 0;
inches = 0;
}
// Parameterized Constructor
DB(float ft, float in) {
feet = ft;
inches = in;
}
int main() {
DM dm;
DB db;
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;
}
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;
}
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;
}
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;
}
int main() {
Array arr;
cout << "Initial Array: ";
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;
}
int main() {
Complex c1(2, 3), c2(4, 5);
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;
}
int main() {
Vector v1, v2;
int 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];
}
}
int main() {
int r, c;
cout << "Enter dimensions for matrices (rows and columns): ";
cin >> 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);
}
// 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();
// 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;
}
};
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;
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;
}
};
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) {}
};
void display() {
cout << "Name: " << name << ", Designation: " << designation
<< ", Project ID: " << projectId << ", Title: " << title
<< ", Duration: " << duration << " months" << endl;
}
int getDuration() { return duration; }
};
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));
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) {}
};
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"));
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;
};
public:
Saving_Account(string name, string contact, int acc_no, float bal) : Account(name, contact),
s_acc_no(acc_no), balance(bal) {}
void calculateInterest() {
float interest = balance * interest_rate;
balance += interest;
cout << "Interest Added: " << interest << " New Balance: " << balance << endl;
}
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;
}
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
};
}
void display()
{
cout << "Shape: Rectangle\nLength: " << length << " Width: " << width << endl;
}
double area()
{
return length * width;
}
};
}
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);
return 0;
}
Set B
1.
#include <iostream>
using namespace std;
class Student {
public:
virtual void display() = 0; // Pure virtual function
};
int main() {
Student* students[3];
students[0] = new Engineering();
students[1] = new Medicine();
students[2] = new Science();
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>
// 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
};
int main() {
Shape* shapes[3];
// 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;
}
// 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;
}
int main() {
Media* items[10]; // Array of pointers to Media objects
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;
public:
Student(int r, string n) {
Roll_No = r;
Name = n;
}
void displayStudent() {
cout << "Roll No: " << Roll_No << "\nName: " << Name << endl;
}
};
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;
}
};
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];
}
};
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";
}
};
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];
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);
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;
public:
Student(string n, int r) {
name = n;
rollNo = r;
}
public:
Engineering(string n, int r, string b) : Student(n, r) {
branch = b;
}
public:
Medicine(string n, int r, string s) : Student(n, r) {
specialization = s;
}
public:
Science(string n, int r, string sub) : Student(n, r) {
subject = sub;
}
int main() {
// Array of Base Class Pointers
Student* students[3];
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;
public:
void store(int value) override {
data = value;
cout << "Stored in Class1: " << data << endl;
}
public:
void store(int value) override {
data = value;
cout << "Stored in Class2: " << data << endl;
}
// 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;
public:
Person(int code, string name) {
P_Code = code;
P_Name = name;
}
};
public:
Account(int code, string name, int acNo, double balance)
: Person(code, name) {
Ac_No = acNo;
Balance = balance;
}
};
public:
Official(int code, string name, string desig, int exp)
: Person(code, name) {
Designation = desig;
Experience = 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;
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;
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;
}
};
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;
}
};
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";
int main() {
Result* student = nullptr;
int choice;
do {
menu();
cin >> choice;
switch (choice) {
case 1: {
int roll, im[5], em[5];
string name, cls;
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);
—--------------------------------------------------------------------------------------------------------------------------
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>
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;
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>
int main() {
ifstream file("numbers.txt"); // Open the file
if (!file) {
cout << "Error opening file!" << endl;
return 1;
}
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;
}
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>
if (!file) {
cout << "Error opening file!" << endl;
return -1;
}
string line;
int count = 0;
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>
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;
// Close files
inputFile.close();
outputFile.close();
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>
if (!inputFile) {
cerr << "Error: Could not open FIRST.TXT!\n";
return;
}
if (!outputFile) {
cerr << "Error: Could not create SECOND.TXT!\n";
return;
}
// 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>
int main() {
int n;
cout << "Enter the number of students: ";
cin >> n;
if (!outFile) {
cerr << "Error: Could not create file!\n";
return 1;
}
outFile << rollNo << " " << name << " " << percentage << endl;
}
return 0;
}
Tab 2