You are on page 1of 92

s1] Write the definition for a class Cylinder that contains data members 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 the cylinder. Write a C++ program to create cylinder
object and display its volume.

Ans- #include <iostream>

class Cylinder {

private:

float radius;

float height;

public:

// Constructor

Cylinder() {

radius = 0.0f;

height = 0.0f;

// Member functions to set radius and height

void setRadius(float r) {

radius = r;

void setHeight(float h) {

height = h;

}
// Member function to calculate volume

float volume() {

return 3.14159f * radius * radius * height;

};

int main() {

// Create an object of Cylinder class

Cylinder myCylinder;

// Set the radius and height

myCylinder.setRadius(5.0f);

myCylinder.setHeight(10.0f);

// Calculate and display volume

std::cout << "Volume of the cylinder: " << myCylinder.volume() << std::endl;

return 0;

S1].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.

Ans- #include <iostream>

class Array {
private:

float arr[5]; // Assuming array size is 5 for simplicity

public:

// Constructor

Array(float values[]) {

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

arr[i] = values[i];

// Overloading unary ++ operator (prefix)

friend Array& operator++(Array &obj) {

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

++obj.arr[i];

return obj;

// Overloading unary -- operator (prefix)

friend Array& operator--(Array &obj) {

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

--obj.arr[i];

return obj;

}
// Display function to show array elements

void display() {

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

std::cout << arr[i] << " ";

std::cout << std::endl;

};

int main() {

float values[] = {1.1, 2.2, 3.3, 4.4, 5.5};

Array myArray(values);

std::cout << "Original Array: ";

myArray.display();

++myArray;

std::cout << "After increment: ";

myArray.display();

--myArray;

std::cout << "After decrement: ";

myArray.display();

return 0;
}

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

Ans- #include <iostream>

class Rectangle2; // Forward declaration

class Rectangle1 {

private:

float length;

float width;

public:

// Constructor

Rectangle1(float l, float w) : length(l), width(w) {}

// Friend function to compare areas

friend void compareAreas(const Rectangle1& rect1, const Rectangle2& rect2);

// Getter functions

float getLength() const {

return length;

float getWidth() const {

return width;
}

// Function to calculate area

float area() const {

return length * width;

};

class Rectangle2 {

private:

float length;

float width;

public:

// Constructor

Rectangle2(float l, float w) : length(l), width(w) {}

// Friend function to compare areas

friend void compareAreas(const Rectangle1& rect1, const Rectangle2& rect2);

// Getter functions

float getLength() const {

return length;

float getWidth() const {


return width;

// Function to calculate area

float area() const {

return length * width;

};

// Friend function to compare areas

void compareAreas(const Rectangle1& rect1, const Rectangle2& rect2) {

float area1 = rect1.area();

float area2 = rect2.area();

if (area1 > area2) {

std::cout << "Area of Rectangle1 is greater than Rectangle2." << std::endl;

} else if (area1 < area2) {

std::cout << "Area of Rectangle2 is greater than Rectangle1." << std::endl;

} else {

std::cout << "Areas of Rectangle1 and Rectangle2 are equal." << std::endl;

int main() {

// Creating objects of Rectangle1 and Rectangle2

Rectangle1 rect1(4, 5);


Rectangle2 rect2(3, 6);

// Comparing areas

compareAreas(rect1, rect2);

return 0;

S2] Write a C++ program to copy the contents of one file to another

Ans- #include <iostream>

#include <fstream>

int main() {

std::ifstream inputFile("input.txt"); // Open input file

std::ofstream outputFile("output.txt"); // Open output file

// Check if both files are open

if (!inputFile.is_open()) {

std::cerr << "Error: Unable to open input file." << std::endl;

return 1;

if (!outputFile.is_open()) {

std::cerr << "Error: Unable to open output file." << std::endl;

return 1;

}
// Copy contents from input to output

char ch;

while (inputFile.get(ch)) {

outputFile.put(ch);

// Close files

inputFile.close();

outputFile.close();

std::cout << "Contents copied successfully from input.txt to output.txt." << std::endl;

return 0;

S3] [uncompiled]Write a C++ program to overload function Volume and find Volume of
Cube, Cylinder and Sphere.

Ans- #include <iostream>

#include <cmath>

const double PI = 3.14159265358979323846;

// Function to calculate volume of a cube

double volume(double sideLength) {

return sideLength * sideLength * sideLength;

}
// Function to calculate volume of a cylinder

double volume(double radius, double height) {

return PI * radius * radius * height;

// Function to calculate volume of a sphere

double volume(double radius) {

return (4.0 / 3.0) * PI * pow(radius, 3);

int main() {

double cubeSideLength = 3.0;

double cylinderRadius = 2.0;

double cylinderHeight = 4.0;

double sphereRadius = 5.0;

// Calculate volumes using overloaded functions

double cubeVolume = volume(cubeSideLength);

double cylinderVolume = volume(cylinderRadius, cylinderHeight);

double sphereVolume = volume(sphereRadius);

// Display volumes

std::cout << "Volume of Cube: " << cubeVolume << std::endl;

std::cout << "Volume of Cylinder: " << cylinderVolume << std::endl;

std::cout << "Volume of Sphere: " << sphereVolume << std::endl;


return 0;

S3] Write a C++ program with Student as abstract class and create derive classes
Engineering, Medicine and Science having data member rollno and name from base class
Student. Create objects of the derived classes and access them using array of pointer of
base class Student

Ans- #include <iostream>

#include <string>

// Abstract base class Student

class Student {

protected:

int rollno;

std::string name;

public:

// Pure virtual function to make Student class abstract

virtual void display() = 0;

};

// Derived class Engineering from Student

class Engineering : public Student {

public:

// Constructor

Engineering(int r, const std::string& n) {

rollno = r;

name = n;
}

// Implementation of display function

void display() override {

std::cout << "Engineering Student - Roll No: " << rollno << ", Name: " << name <<
std::endl;

};

// Derived class Medicine from Student

class Medicine : public Student {

public:

// Constructor

Medicine(int r, const std::string& n) {

rollno = r;

name = n;

// Implementation of display function

void display() override {

std::cout << "Medicine Student - Roll No: " << rollno << ", Name: " << name <<
std::endl;

};

// Derived class Science from Student


class Science : public Student {

public:

// Constructor

Science(int r, const std::string& n) {

rollno = r;

name = n;

// Implementation of display function

void display() override {

std::cout << "Science Student - Roll No: " << rollno << ", Name: " << name << std::endl;

};

int main() {

// Array of pointers to base class Student

Student* students[3];

// Creating objects of derived classes

Engineering engStudent(101, "John");

Medicine medStudent(102, "Alice");

Science sciStudent(103, "Bob");

// Assigning addresses of objects to array elements

students[0] = &engStudent;

students[1] = &medStudent;
students[2] = &sciStudent;

// Accessing objects through array of pointers

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

students[i]->display();

return 0;

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

Ans- #include <iostream>

// Inline function to calculate area of a circle

inline double areaCircle(double radius) {

return 3.14159 * radius * radius;

// Inline function to calculate area of a square

inline double areaSquare(double side) {

return side * side;

// Inline function to calculate area of a rectangle

inline double areaRectangle(double length, double width) {

return length * width;

}
int main() {

double radius = 3.0;

double side = 4.0;

double length = 5.0;

double width = 6.0;

// Print area of circle

std::cout << "Area of Circle with radius " << radius << " is: " << areaCircle(radius) <<
std::endl;

// Print area of square

std::cout << "Area of Square with side " << side << " is: " << areaSquare(side) << std::endl;

// Print area of rectangle

std::cout << "Area of Rectangle with length " << length << " and width " << width << " is: "
<< areaRectangle(length, width) << std::endl;

return 0;

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

Ans- #include <iostream>

class Matrix {

private:
int **matrix;

int m, n;

public:

// Constructor to allocate memory for the matrix

Matrix(int rows, int cols) : m(rows), n(cols) {

// Allocate memory for the matrix

matrix = new int*[m];

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

matrix[i] = new int[n];

// Destructor to free allocated memory

~Matrix() {

// Free memory for each row

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

delete[] matrix[i];

// Free memory for the array of pointers

delete[] matrix;

// Function to input matrix elements

void inputMatrix() {

std::cout << "Enter matrix elements:" << std::endl;


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

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

std::cin >> matrix[i][j];

// Function to display the transpose of the matrix

void displayTranspose() {

std::cout << "Transpose of the entered matrix:" << std::endl;

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

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

std::cout << matrix[i][j] << " ";

std::cout << std::endl;

};

int main() {

int rows, cols;

std::cout << "Enter the number of rows and columns for the matrix: ";

std::cin >> rows >> cols;

// Create an object of Matrix class with dynamic memory allocation

Matrix myMatrix(rows, cols);


// Input matrix elements

myMatrix.inputMatrix();

// Display transpose of the matrix

myMatrix.displayTranspose();

return 0;

S5] 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.

ANS- #include <iostream>

#include <string>

class Mobile {

private:

int Mobile_Id;

std::string Mobile_Name;

double Mobile_Price;

public:

// Parameterized constructor to initialize data members

Mobile(int id, const std::string& name, double price)

: Mobile_Id(id), Mobile_Name(name), Mobile_Price(price) {}


// Function to display the values of Mobile object

void display() {

std::cout << "Mobile ID: " << Mobile_Id << std::endl;

std::cout << "Mobile Name: " << Mobile_Name << std::endl;

std::cout << "Mobile Price: " << Mobile_Price << std::endl;

};

int main() {

// Create a Mobile object and initialize it using parameterized constructor

Mobile mobile1(101, "iPhone 13", 999.99);

// Display the values of Mobile object

mobile1.display();

return 0;

S5] 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 menu driven program to
perform the following functions: a. Build a master table. b. Display master table.

ANS- #include <iostream>

#include <string>

#include <iomanip>

// Base class Student


class Student {

protected:

int Roll_No;

std::string Name;

public:

// Parameterized constructor

Student(int rollNo, const std::string& name)

: Roll_No(rollNo), Name(name) {}

// Function to display student details

void display() {

std::cout << "Roll No: " << Roll_No << ", Name: " << Name << std::endl;

};

// Derived class Theory

class Theory : virtual public Student {

protected:

int theoryMarks[5];

public:

// Parameterized constructor

Theory(int rollNo, const std::string& name, int marks[])

: Student(rollNo, name) {

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


theoryMarks[i] = marks[i];

};

// Derived class Practical

class Practical : virtual public Student {

protected:

int practicalMarks[2];

public:

// Parameterized constructor

Practical(int rollNo, const std::string& name, int marks[])

: Student(rollNo, name) {

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

practicalMarks[i] = marks[i];

};

// Derived class Result

class Result : public Theory, public Practical {

private:

int Total_Marks;

std::string Class;
public:

// Parameterized constructor

Result(int rollNo, const std::string& name, int theoryMarks[], int practicalMarks[], int
totalMarks, const std::string& studentClass)

: Student(rollNo, name), Theory(rollNo, name, theoryMarks), Practical(rollNo, name,


practicalMarks), Total_Marks(totalMarks), Class(studentClass) {}

// Function to display student result

void display() {

Student::display();

std::cout << "Total Marks: " << Total_Marks << ", Class: " << Class << std::endl;

};

int main() {

const int MAX_STUDENTS = 100;

Result* masterTable[MAX_STUDENTS];

int choice = 0;

int numStudents = 0;

while (true) {

std::cout << "\nMenu:\n";

std::cout << "1. Build a master table\n";

std::cout << "2. Display master table\n";

std::cout << "3. Exit\n";

std::cout << "Enter your choice: ";


std::cin >> choice;

switch (choice) {

case 1: {

// Build a master table

int rollNo, theoryMarks[5], practicalMarks[2], totalMarks;

std::string name, studentClass;

std::cout << "Enter Roll No: ";

std::cin >> rollNo;

std::cout << "Enter Name: ";

std::cin.ignore();

std::getline(std::cin, name);

std::cout << "Enter Theory Marks for 5 Subjects: ";

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

std::cin >> theoryMarks[i];

std::cout << "Enter Practical Marks for 2 Subjects: ";

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

std::cin >> practicalMarks[i];

std::cout << "Enter Total Marks: ";

std::cin >> totalMarks;

std::cout << "Enter Class: ";

std::cin >> studentClass;


masterTable[numStudents++] = new Result(rollNo, name, theoryMarks,
practicalMarks, totalMarks, studentClass);

std::cout << "Student added to master table.\n";

break;

case 2: {

// Display master table

std::cout << "\nMaster Table:\n";

std::cout << std::left << std::setw(15) << "Roll No" << std::setw(20) << "Name" <<
std::setw(15) << "Total Marks" << std::setw(10) << "Class" << std::endl;

std::cout << "---------------------------------------------------------\n";

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

masterTable[i]->display();

break;

case 3: {

// Exit program

std::cout << "Exiting program.\n";

return 0;

default:

std::cout << "Invalid choice. Please enter a valid choice.\n";

}
return 0;

S6] Write a C++ program to implement a class printdata to overload print function as
follows: void print(int) - outputs value followed by the value of the integer. Eg. print(10)
outputs - value 10 void print(char *) – outputs value followed by the string in double quotes.
Eg. print(“hi”) outputs value “hi

ANS- #include <iostream>

#include <cstring>

class printdata {

public:

// Overloaded function to print an integer value

void print(int value) {

std::cout << "value " << value << std::endl;

// Overloaded function to print a string value

void print(const char *value) {

std::cout << "value \"" << value << "\"" << std::endl;

};

int main() {

printdata obj;

// Calling the overloaded functions

obj.print(10);
obj.print("hi");

return 0;

S6] Write a C++ program to design a class complex to represent complex number. The
complex class uses an external function (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.

ANS- #include <iostream>

class Complex {

private:

double real;

double imaginary;

public:

// Constructor to initialize complex number

Complex(double realPart, double imaginaryPart) : real(realPart),


imaginary(imaginaryPart) {}

// Getter functions

double getReal() const {

return real;

double getImaginary() const {

return imaginary;
}

// Friend function to add two complex numbers

friend Complex add(const Complex& c1, const Complex& c2);

};

// Friend function definition to add two complex numbers

Complex add(const Complex& c1, const Complex& c2) {

double realSum = c1.real + c2.real;

double imaginarySum = c1.imaginary + c2.imaginary;

return Complex(realSum, imaginarySum);

int main() {

// Create two complex numbers

Complex c1(2.0, 3.0);

Complex c2(4.0, 5.0);

// Add two complex numbers using friend function

Complex sum = add(c1, c2);

// Display the result

std::cout << "Sum: " << sum.getReal() << " + " << sum.getImaginary() << "i" << std::endl;

return 0;

}
S7] Write a C++ program using class which contains two data members as type integer.
Create and initialize the objects using default constructor, parameterized constructor with
default value. Write a member function to display maximum from given two numbers for all
objects. [10]

ANS- #include <iostream>

class Numbers {

private:

int num1;

int num2;

public:

// Default constructor

Numbers() : num1(0), num2(0) {}

// Parameterized constructor with default values

Numbers(int n1, int n2 = 0) : num1(n1), num2(n2) {}

// Function to display maximum of the two numbers

void displayMax() {

std::cout << "Maximum of " << num1 << " and " << num2 << " is: " << (num1 > num2 ?
num1 : num2) << std::endl;

};

int main() {

// Creating objects using default constructor


Numbers obj1;

obj1.displayMax();

// Creating objects using parameterized constructor with default values

Numbers obj2(5);

obj2.displayMax();

Numbers obj3(10, 7);

obj3.displayMax();

return 0;

S7] Create a class College containing data members as College_Id, College_Name,


Establishment_year, University_Name. Write a C++ program with following functions a.
Accept n College details b. Display College details of specified University c. Display
College details according to Establishment year (Use Array of Objects and Function
Overloading)

ANS- #include <iostream>

#include <string>

class College {

private:

int College_Id;

std::string College_Name;

int Establishment_year;

std::string University_Name;
public:

// Default constructor

College() {}

// Parameterized constructor

College(int id, const std::string& name, int year, const std::string& university)

: College_Id(id), College_Name(name), Establishment_year(year),


University_Name(university) {}

// Function to accept college details

void acceptDetails() {

std::cout << "Enter College Id: ";

std::cin >> College_Id;

std::cout << "Enter College Name: ";

std::cin.ignore();

std::getline(std::cin, College_Name);

std::cout << "Enter Establishment Year: ";

std::cin >> Establishment_year;

std::cout << "Enter University Name: ";

std::cin.ignore();

std::getline(std::cin, University_Name);

// Function to display college details

void displayDetails() {

std::cout << "College Id: " << College_Id << std::endl;


std::cout << "College Name: " << College_Name << std::endl;

std::cout << "Establishment Year: " << Establishment_year << std::endl;

std::cout << "University Name: " << University_Name << std::endl;

// Function to display college details of specified university

void displayDetails(const std::string& university) {

if (University_Name == university) {

displayDetails();

// Function to display college details according to establishment year

void displayDetails(int year) {

if (Establishment_year == year) {

displayDetails();

};

int main() {

const int MAX_COLLEGES = 100;

College colleges[MAX_COLLEGES];

int n;

std::cout << "Enter the number of colleges: ";


std::cin >> n;

// Accepting college details

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

std::cout << "\nEnter details of College " << i + 1 << ":\n";

colleges[i].acceptDetails();

// Display college details of specified university

std::string searchUniversity;

std::cout << "\nEnter the university name to search: ";

std::cin.ignore();

std::getline(std::cin, searchUniversity);

std::cout << "\nColleges under " << searchUniversity << ":\n";

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

colleges[i].displayDetails(searchUniversity);

// Display college details according to establishment year

int searchYear;

std::cout << "\nEnter the establishment year to search: ";

std::cin >> searchYear;

std::cout << "\nColleges established in " << searchYear << ":\n";

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

colleges[i].displayDetails(searchYear);

}
return 0;

S8] Write a C++ program to subtract two integer numbers of two different classes using
friend function

ANS- #include <iostream>

// Forward declaration of class B

class B;

// Class A

class A {

private:

int numA;

public:

// Constructor

A(int num) : numA(num) {}

// Friend function declaration

friend int subtract(const A& a, const B& b);

};

// Class B

class B {

private:
int numB;

public:

// Constructor

B(int num) : numB(num) {}

// Friend function declaration

friend int subtract(const A& a, const B& b);

};

// Friend function definition to subtract numB from numA

int subtract(const A& a, const B& b) {

return a.numA - b.numB;

int main() {

// Create objects of classes A and B

A objA(20);

B objB(10);

// Call the friend function to subtract numB from numA

int result = subtract(objA, objB);

// Display the result

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


return 0;

S8] Write a C++ program to create a class Date which contains three data members as
dd,mm,yyyy. Create and initialize the object by using parameterized constructor and
display date in dd-monthyyyy format. (Input: 19-12-2014 Output: 19-Dec-2014) Perform
validation for month.

ANS- #include <iostream>

#include <string>

class Date {

private:

int dd;

int mm;

int yyyy;

public:

// Parameterized constructor

Date(int day, int month, int year) : dd(day), mm(month), yyyy(year) {}

// Function to display date in dd-month-yyyy format

void displayDate() {

std::string monthNames[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",

"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

if (mm >= 1 && mm <= 12) {

std::cout << dd << "-" << monthNames[mm - 1] << "-" << yyyy << std::endl;
} else {

std::cout << "Invalid month!" << std::endl;

};

int main() {

int day, month, year;

// Input date from the user

std::cout << "Enter date in dd-mm-yyyy format: ";

std::cin >> day >> month >> year;

// Create Date object and initialize it using parameterized constructor

Date date(day, month, year);

// Display date in dd-month-yyyy format

date.displayDate();

return 0;

S9] Write a C++ program to create a class Item with data members Item_code, Item_name,
Item_Price. Write member functions to accept and display item information and also
display number of objects created for a class. (Use Static data member and Static member
function)

ANS- #include <iostream>

#include <string>
class Item {

private:

int Item_code;

std::string Item_name;

float Item_Price;

static int count; // Static data member to count number of objects created

public:

// Constructor to initialize data members

Item(int code, const std::string& name, float price)

: Item_code(code), Item_name(name), Item_Price(price) {

count++; // Increment count each time an object is created

// Function to accept item information

void acceptItem() {

std::cout << "Enter Item code: ";

std::cin >> Item_code;

std::cout << "Enter Item name: ";

std::cin.ignore();

std::getline(std::cin, Item_name);

std::cout << "Enter Item price: ";

std::cin >> Item_Price;

count++; // Increment count after accepting item information

}
// Function to display item information

void displayItem() {

std::cout << "Item code: " << Item_code << std::endl;

std::cout << "Item name: " << Item_name << std::endl;

std::cout << "Item price: " << Item_Price << std::endl;

// Static member function to display number of objects created

static void displayCount() {

std::cout << "Number of objects created: " << count << std::endl;

};

// Initialize static data member

int Item::count = 0;

int main() {

// Creating objects of class Item

Item item1(101, "Book", 10.50);

Item item2(102, "Pen", 2.25);

// Displaying item information

std::cout << "Item 1 details:\n";

item1.displayItem();

std::cout << "\nItem 2 details:\n";


item2.displayItem();

// Displaying number of objects created

Item::displayCount();

return 0;

S9] Create a class Time which contains data members as: Hours, Minutes and Seconds.
Write a C++ program to perform following necessary member functions: a. To read time b.
To display time in format like: hh:mm:ss c. To add two different times (Use Objects as
argument)

ANS- #include <iostream>

class Time {

private:

int Hours;

int Minutes;

int Seconds;

public:

// Function to read time

void readTime() {

std::cout << "Enter hours: ";

std::cin >> Hours;

std::cout << "Enter minutes: ";

std::cin >> Minutes;

std::cout << "Enter seconds: ";


std::cin >> Seconds;

// Function to display time in hh:mm:ss format

void displayTime() {

std::cout << "Time: ";

if (Hours < 10) std::cout << "0";

std::cout << Hours << ":";

if (Minutes < 10) std::cout << "0";

std::cout << Minutes << ":";

if (Seconds < 10) std::cout << "0";

std::cout << Seconds << std::endl;

// Function to add two different times

Time addTime(const Time& t1, const Time& t2) {

Time result;

result.Seconds = t1.Seconds + t2.Seconds;

result.Minutes = t1.Minutes + t2.Minutes + result.Seconds / 60;

result.Hours = t1.Hours + t2.Hours + result.Minutes / 60;

result.Seconds %= 60;

result.Minutes %= 60;

return result;

}
};

int main() {

Time time1, time2, sum;

// Read time for two instances

std::cout << "Enter time for first instance:\n";

time1.readTime();

std::cout << "Enter time for second instance:\n";

time2.readTime();

// Display the entered times

std::cout << "\nEntered times:\n";

time1.displayTime();

time2.displayTime();

// Add two times

sum = sum.addTime(time1, time2);

// Display the sum of times

std::cout << "\nSum of times:\n";

sum.displayTime();

return 0;

}
S10] 1.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 decrementing salary.

ANS- #include <iostream>

class Employee {

private:

double salary;

public:

// Constructor

Employee(double s) : salary(s) {}

// Overloading unary pre-decrement operator (--var)

Employee& operator--() {

--salary;

return *this;

// Overloading unary post-decrement operator (var--)

Employee operator--(int) {

Employee temp(*this);

--salary;

return temp;

}
// Function to display salary

void displaySalary() const {

std::cout << "Salary: " << salary << std::endl;

};

int main() {

// Create an employee object with salary 5000

Employee emp(5000);

std::cout << "Initial salary: ";

emp.displaySalary();

// Pre-decrement salary

--emp;

std::cout << "Salary after pre-decrement: ";

emp.displaySalary();

// Post-decrement salary

emp--;

std::cout << "Salary after post-decrement: ";

emp.displaySalary();

return 0;

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

ANS- #include <iostream>

#include <vector>

#include <iomanip>

class Product {

protected:

int Product_Id;

std::string Product_Name;

double Price;

public:

// Parameterized constructor

Product(int id, const std::string& name, double price)

: Product_Id(id), Product_Name(name), Price(price) {}

// Function to calculate total price

virtual double calculateTotalPrice() const {

return Price;

// Function to display product details

virtual void display() const {

std::cout << std::setw(10) << Product_Id << std::setw(20) << Product_Name <<
std::setw(10) << Price;
}

};

class Discount : public Product {

private:

double Discount_In_Percentage;

public:

// Parameterized constructor

Discount(int id, const std::string& name, double price, double discount)

: Product(id, name, price), Discount_In_Percentage(discount) {}

// Function to calculate total price with discount

double calculateTotalPrice() const override {

double discountAmount = Price * (Discount_In_Percentage / 100);

return Price - discountAmount;

// Function to display product details with discount

void display() const override {

std::cout << std::setw(10) << Product_Id << std::setw(20) << Product_Name <<
std::setw(10) << Price << std::setw(10) << Discount_In_Percentage << "%";

};

int main() {
int n;

std::cout << "Enter the number of products: ";

std::cin >> n;

std::vector<Product*> products;

double totalPrice = 0.0;

double totalDiscount = 0.0;

std::cout << "Enter product details for " << n << " products:\n";

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

int id;

std::string name;

double price;

double discount;

std::cout << "Product " << i + 1 << ":\n";

std::cout << "Enter Product ID: ";

std::cin >> id;

std::cout << "Enter Product Name: ";

std::cin.ignore();

std::getline(std::cin, name);

std::cout << "Enter Price: ";

std::cin >> price;

std::cout << "Enter Discount in Percentage: ";

std::cin >> discount;


// Create product based on discount

if (discount > 0) {

products.push_back(new Discount(id, name, price, discount));

} else {

products.push_back(new Product(id, name, price));

totalPrice += products.back()->calculateTotalPrice();

totalDiscount += (price - products.back()->calculateTotalPrice());

// Display bill

std::cout << "\n---------------------------BILL---------------------------\n";

std::cout << std::setw(10) << "ID" << std::setw(20) << "Name" << std::setw(10) << "Price"
<< std::setw(10) << "Discount" << std::endl;

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

products[i]->display();

std::cout << std::endl;

std::cout << "\nTotal Price: " << totalPrice << std::endl;

std::cout << "Total Discount: " << totalDiscount << std::endl;

// Cleanup

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

delete products[i];

}
return 0;

S11] Write a C++ program to read two float numbers. Perform arithmetic binary operations
+,-,*,/ on these numbers using inline function. Display the resultant value.

ANS- #include <iostream>

// Inline function for addition

inline float add(float a, float b) {

return a + b;

// Inline function for subtraction

inline float subtract(float a, float b) {

return a - b;

// Inline function for multiplication

inline float multiply(float a, float b) {

return a * b;

// Inline function for division

inline float divide(float a, float b) {

if (b != 0) {

return a / b;
} else {

std::cerr << "Error: Division by zero!" << std::endl;

return 0;

int main() {

float num1, num2;

// Input two float numbers

std::cout << "Enter two float numbers: ";

std::cin >> num1 >> num2;

// Perform arithmetic operations

std::cout << "Addition: " << add(num1, num2) << std::endl;

std::cout << "Subtraction: " << subtract(num1, num2) << std::endl;

std::cout << "Multiplication: " << multiply(num1, num2) << std::endl;

std::cout << "Division: " << divide(num1, num2) << std::endl;

return 0;

S11] Write a C++ program to create a class Person that contains data members as
Person_Name, City, Mob_No. Write a C++ program to perform following functions: a. To
accept and display Person information b. To search the Person details of a given mobile
number c. To search the Person details of a given city. (Use Function Overloading)

ANS- #include <iostream>

#include <string>
class Person {

private:

std::string Person_Name;

std::string City;

std::string Mob_No;

public:

// Function to accept person information

void acceptPersonInfo() {

std::cout << "Enter Person Name: ";

std::getline(std::cin >> std::ws, Person_Name);

std::cout << "Enter City: ";

std::getline(std::cin >> std::ws, City);

std::cout << "Enter Mobile Number: ";

std::cin >> Mob_No;

// Function to display person information

void displayPersonInfo() const {

std::cout << "Person Name: " << Person_Name << std::endl;

std::cout << "City: " << City << std::endl;

std::cout << "Mobile Number: " << Mob_No << std::endl;

// Function to search person details by mobile number


void searchPerson(const std::string& mobile) const {

if (Mob_No == mobile) {

std::cout << "Person found with the given mobile number:\n";

displayPersonInfo();

} else {

std::cout << "Person not found with the given mobile number.\n";

// Function to search person details by city

void searchPerson(const std::string& cityName, int) const {

if (City == cityName) {

std::cout << "Persons found in the given city:\n";

displayPersonInfo();

} else {

std::cout << "No persons found in the given city.\n";

};

int main() {

Person p1, p2, p3;

// Accept person information

std::cout << "Enter information for Person 1:\n";

p1.acceptPersonInfo();
std::cout << "\nEnter information for Person 2:\n";

p2.acceptPersonInfo();

std::cout << "\nEnter information for Person 3:\n";

p3.acceptPersonInfo();

// Display person information

std::cout << "\nPerson 1 Details:\n";

p1.displayPersonInfo();

std::cout << "\nPerson 2 Details:\n";

p2.displayPersonInfo();

std::cout << "\nPerson 3 Details:\n";

p3.displayPersonInfo();

// Search person details by mobile number

std::cout << "\nSearch by Mobile Number:\n";

std::string mobile;

std::cout << "Enter Mobile Number to search: ";

std::cin >> mobile;

p1.searchPerson(mobile);

p2.searchPerson(mobile);

p3.searchPerson(mobile);

// Search person details by city

std::cout << "\nSearch by City:\n";

std::string city;

std::cout << "Enter City Name to search: ";


std::cin >> city;

p1.searchPerson(city, 0); // Passing an extra argument to differentiate overloaded


function

p2.searchPerson(city, 0);

p3.searchPerson(city, 0);

return 0;

S12] Write a C++ program to accept length and width of a rectangle. Calculate and display
perimeter as well as area of a rectangle by using inline function.

ANS- #include <iostream>

// Inline function to calculate perimeter of rectangle

inline double calculatePerimeter(double length, double width) {

return 2 * (length + width);

// Inline function to calculate area of rectangle

inline double calculateArea(double length, double width) {

return length * width;

int main() {

double length, width;

// Input length and width of rectangle


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

std::cin >> length;

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

std::cin >> width;

// Calculate and display perimeter and area of rectangle

std::cout << "Perimeter of rectangle: " << calculatePerimeter(length, width) << std::endl;

std::cout << "Area of rectangle: " << calculateArea(length, width) << std::endl;

return 0;

S12] 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 an object)

ANS- #include <iostream>

#include <algorithm>

class ArrayWithMedian {

private:

int *arr;

int size;

public:

// Constructor to allocate memory and initialize array

ArrayWithMedian(int sz) : size(sz) {

arr = new int[size];


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

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

std::cin >> arr[i];

// Destructor to deallocate memory

~ArrayWithMedian() {

delete[] arr;

// Function to calculate and display median of the array

void displayMedian() {

std::sort(arr, arr + size);

double median;

if (size % 2 == 0) {

median = (arr[size / 2 - 1] + arr[size / 2]) / 2.0;

} else {

median = arr[size / 2];

std::cout << "Median of the array: " << median << std::endl;

};

int main() {

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

std::cin >> size;

// Create object of ArrayWithMedian class

ArrayWithMedian arrObj(size);

// Display median of the array

arrObj.displayMedian();

return 0;

S13] 1.Write a C++ program to implement a class ‘student’ to overload following functions
as follows: a. int maximum(int, int) – returns the maximum score of two students b. int
maximum(int *a, int arraylength) – returns the maximum score from an array ‘a’ [

ANS- #include <iostream>

class Student {

public:

// Overloaded function to find maximum score of two students

int maximum(int score1, int score2) {

return (score1 > score2) ? score1 : score2;

// Overloaded function to find maximum score from an array

int maximum(int *a, int arraylength) {

int max = a[0];


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

if (a[i] > max) {

max = a[i];

return max;

};

int main() {

Student studentObj;

// Example usage of overloaded functions

int score1 = 85, score2 = 92;

int scoresArray[] = {78, 89, 95, 80, 87};

int arrayLength = sizeof(scoresArray) / sizeof(scoresArray[0]);

std::cout << "Maximum score of two students: " << studentObj.maximum(score1,


score2) << std::endl;

std::cout << "Maximum score from the array: " << studentObj.maximum(scoresArray,
arrayLength) << std::endl;

return 0;

S13] Write a C++ program to read the contents of a text file. Count and display number of
characters, words and lines from a file. Find the number of occurrences of a given word
present in a file.
ANS- #include <iostream>

#include <fstream>

#include <string>

#include <sstream>

#include <algorithm>

// Function to count characters, words, and lines

void countCharactersWordsLines(std::ifstream& file, int& charCount, int& wordCount,


int& lineCount) {

std::string line;

while (std::getline(file, line)) {

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

++lineCount; // Counting lines

std::istringstream iss(line);

std::string word;

while (iss >> word) {

++wordCount; // Counting words

// Function to find the number of occurrences of a given word

int countWordOccurrences(std::ifstream& file, const std::string& targetWord) {

int count = 0;

std::string word;
while (file >> word) {

// Convert word to lowercase for case-insensitive comparison

std::transform(word.begin(), word.end(), word.begin(), ::tolower);

if (word == targetWord) {

++count;

return count;

int main() {

std::string filename;

std::cout << "Enter the name of the file: ";

std::cin >> filename;

std::ifstream file(filename);

if (!file.is_open()) {

std::cerr << "Error: Unable to open file." << std::endl;

return 1;

int charCount = 0, wordCount = 0, lineCount = 0;

countCharactersWordsLines(file, charCount, wordCount, lineCount);

// Reset file pointer to beginning

file.clear();
file.seekg(0, std::ios::beg);

std::string targetWord;

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

std::cin >> targetWord;

int wordOccurrences = countWordOccurrences(file, targetWord);

std::cout << "\nNumber of characters: " << charCount << std::endl;

std::cout << "Number of words: " << wordCount << std::endl;

std::cout << "Number of lines: " << lineCount << std::endl;

std::cout << "Number of occurrences of \"" << targetWord << "\": " << wordOccurrences
<< std::endl;

file.close();

return 0;

S14] 1. Write a C++ program to interchange values of two integer numbers (use call by
reference

ANS- #include <iostream>

// Function to interchange values of two integer numbers using call by reference

void interchange(int &a, int &b) {

int temp = a;

a = b;
b = temp;

int main() {

int num1, num2;

// Input two integer numbers

std::cout << "Enter first integer: ";

std::cin >> num1;

std::cout << "Enter second integer: ";

std::cin >> num2;

// Display the values before interchange

std::cout << "Before interchange:\n";

std::cout << "First integer: " << num1 << std::endl;

std::cout << "Second integer: " << num2 << std::endl;

// Interchange the values

interchange(num1, num2);

// Display the values after interchange

std::cout << "\nAfter interchange:\n";

std::cout << "First integer: " << num1 << std::endl;

std::cout << "Second integer: " << num2 << std::endl;

return 0;
}

S14] Create a class Fraction that contains two data members as numerator and
denominator. Write a C++ program to overload following operators a. ++ Unary (pre and
post both) b. << and >> Overload as friend functions

ANS- #include <iostream>

class Fraction {

private:

int numerator;

int denominator;

public:

// Constructor

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

// Overloading pre-increment operator

Fraction& operator++() {

numerator += denominator;

return *this;

// Overloading post-increment operator

Fraction operator++(int) {

Fraction temp(*this);

numerator += denominator;

return temp;
}

// Friend function to overload insertion operator (<<)

friend std::ostream& operator<<(std::ostream& out, const Fraction& frac) {

out << frac.numerator << "/" << frac.denominator;

return out;

// Friend function to overload extraction operator (>>)

friend std::istream& operator>>(std::istream& in, Fraction& frac) {

std::cout << "Enter numerator: ";

in >> frac.numerator;

std::cout << "Enter denominator: ";

in >> frac.denominator;

return in;

};

int main() {

Fraction frac1, frac2(3, 4);

// Testing pre-increment operator

std::cout << "Fraction 1 (initial): " << frac1 << std::endl;

++frac1;

std::cout << "Fraction 1 (after pre-increment): " << frac1 << std::endl;
// Testing post-increment operator

std::cout << "Fraction 2 (initial): " << frac2 << std::endl;

Fraction frac3 = frac2++;

std::cout << "Fraction 2 (after post-increment): " << frac2 << std::endl;

std::cout << "Fraction 3 (post-increment result): " << frac3 << std::endl;

// Testing insertion and extraction operators

Fraction frac4;

std::cin >> frac4;

std::cout << "Fraction 4 entered by user: " << frac4 << std::endl;

return 0;

S15] Write a C++ program to check minimum and maximum of two integer number (use
inline function and conditional operator)

ANS- #include <iostream>

// Inline function to find minimum of two integers

inline int findMin(int a, int b) {

return (a < b) ? a : b;

// Inline function to find maximum of two integers

inline int findMax(int a, int b) {

return (a > b) ? a : b;

}
int main() {

int num1, num2;

// Input two integer numbers

std::cout << "Enter first integer: ";

std::cin >> num1;

std::cout << "Enter second integer: ";

std::cin >> num2;

// Find and display minimum and maximum using inline functions

std::cout << "Minimum of " << num1 << " and " << num2 << " is: " << findMin(num1, num2)
<< std::endl;

std::cout << "Maximum of " << num1 << " and " << num2 << " is: " << findMax(num1,
num2) << std::endl;

return 0;

S15] Create a base class Conversion. Derive three different classes Weight (Gram,
Kilogram), Volume (Milliliter, Liter), Currency (Rupees, Paise) from Conversion class. Write
a program to perform read, convert and display operations. (Use Pure virtual function)

ANS- #include <iostream>

#include <string>

class Conversion {

public:

// Pure virtual function for conversion


virtual void convert() const = 0;

};

class Weight : public Conversion {

private:

double value;

std::string unit;

public:

// Constructor

Weight(double val, const std::string& u) : value(val), unit(u) {}

// Implementation of the convert function for weight conversion

void convert() const override {

if (unit == "Gram") {

std::cout << "Converted value: " << value / 1000 << " Kilograms" << std::endl;

} else if (unit == "Kilogram") {

std::cout << "Converted value: " << value * 1000 << " Grams" << std::endl;

};

class Volume : public Conversion {

private:

double value;

std::string unit;
public:

// Constructor

Volume(double val, const std::string& u) : value(val), unit(u) {}

// Implementation of the convert function for volume conversion

void convert() const override {

if (unit == "Milliliter") {

std::cout << "Converted value: " << value / 1000 << " Liters" << std::endl;

} else if (unit == "Liter") {

std::cout << "Converted value: " << value * 1000 << " Milliliters" << std::endl;

};

class Currency : public Conversion {

private:

double value;

std::string unit;

public:

// Constructor

Currency(double val, const std::string& u) : value(val), unit(u) {}

// Implementation of the convert function for currency conversion

void convert() const override {


if (unit == "Rupees") {

std::cout << "Converted value: " << value * 100 << " Paise" << std::endl;

} else if (unit == "Paise") {

std::cout << "Converted value: " << value / 100 << " Rupees" << std::endl;

};

int main() {

// Example usage of the classes and conversion operations

Weight weightObj(1500, "Gram");

Volume volumeObj(2.5, "Liter");

Currency currencyObj(250, "Rupees");

std::cout << "Weight conversion:\n";

weightObj.convert();

std::cout << "\nVolume conversion:\n";

volumeObj.convert();

std::cout << "\nCurrency conversion:\n";

currencyObj.convert();

return 0;

}
S16] 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.

Ans- #include <iostream>

class Number {

private:

int num1;

int num2;

public:

// Default constructor

Number() {

num1 = 0;

num2 = 0;

// Parameterized constructor

Number(int n1, int n2) {

num1 = n1;

num2 = n2;

// Function to display maximum of two numbers

void displayMaximum() const {


std::cout << "Maximum of " << num1 << " and " << num2 << " is: " << ((num1 > num2) ?
num1 : num2) << std::endl;

};

int main() {

// Create objects using default constructor and display maximum

Number numObj1;

std::cout << "For object 1 (using default constructor):\n";

numObj1.displayMaximum();

// Create objects using parameterized constructor and display maximum

Number numObj2(10, 20);

std::cout << "\nFor object 2 (using parameterized constructor):\n";

numObj2.displayMaximum();

return 0;

S16] Create a class Time containing members as: - hours - minutes - seconds Write a C++
program for overloading operators >> and << to accept and display a Time also write a
member function to display time in total seconds.

Ans- #include <iostream>

class Time {

private:

int hours;

int minutes;
int seconds;

public:

// Default constructor

Time() : hours(0), minutes(0), seconds(0) {}

// Parameterized constructor

Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}

// Overloading >> operator to accept a Time object

friend std::istream& operator>>(std::istream& in, Time& time) {

std::cout << "Enter hours: ";

in >> time.hours;

std::cout << "Enter minutes: ";

in >> time.minutes;

std::cout << "Enter seconds: ";

in >> time.seconds;

return in;

// Overloading << operator to display a Time object

friend std::ostream& operator<<(std::ostream& out, const Time& time) {

out << "Time: " << time.hours << " hours, " << time.minutes << " minutes, " <<
time.seconds << " seconds";

return out;

}
// Function to display time in total seconds

int totalTimeInSeconds() const {

return hours * 3600 + minutes * 60 + seconds;

};

int main() {

Time t;

// Input time from user

std::cout << "Enter time:\n";

std::cin >> t;

// Display time

std::cout << "Entered time: " << t << std::endl;

// Display time in total seconds

std::cout << "Total seconds: " << t.totalTimeInSeconds() << std::endl;

return 0;

S17] Write a C++ program to check if number is prime or not.

Ans- #include <iostream>

bool isPrime(int num) {


if (num <= 1) {

return false; // Numbers less than or equal to 1 are not prime

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

if (num % i == 0) {

return false; // If num is divisible by any number other than 1 and itself, it's not prime

return true; // If num is not divisible by any number other than 1 and itself, it's prime

int main() {

int num;

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

std::cin >> num;

if (isPrime(num)) {

std::cout << num << " is a prime number." << std::endl;

} else {

std::cout << num << " is not a prime number." << std::endl;

return 0;

}
S17] Create a class Fraction containing data members as Numerator and Denominator.
Write a program to overload operators ++ , -- and * to increment, decrement a Fraction and
multiply two Fraction respectively. (Use constructor to initialize values of an object)

Ans- #include <iostream>

class Fraction {

private:

int numerator;

int denominator;

public:

// Constructor to initialize values of an object

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

// Overloading ++ operator for prefix increment

Fraction& operator++() {

numerator += denominator;

return *this;

// Overloading ++ operator for postfix increment

Fraction operator++(int) {

Fraction temp(*this);

numerator += denominator;

return temp;

}
// Overloading -- operator for prefix decrement

Fraction& operator--() {

numerator -= denominator;

return *this;

// Overloading -- operator for postfix decrement

Fraction operator--(int) {

Fraction temp(*this);

numerator -= denominator;

return temp;

// Overloading * operator to multiply two fractions

Fraction operator*(const Fraction& other) const {

return Fraction(numerator * other.numerator, denominator * other.denominator);

// Function to display the fraction

void display() const {

std::cout << numerator << "/" << denominator;

};

int main() {
Fraction frac1(3, 4);

Fraction frac2(5, 6);

std::cout << "Initial fractions:\n";

std::cout << "Fraction 1: ";

frac1.display();

std::cout << std::endl;

std::cout << "Fraction 2: ";

frac2.display();

std::cout << std::endl;

// Increment fraction 1 and display

std::cout << "\nAfter incrementing fraction 1:\n";

(frac1++).display();

std::cout << std::endl;

// Decrement fraction 2 and display

std::cout << "After decrementing fraction 2:\n";

(--frac2).display();

std::cout << std::endl;

// Multiply fractions and display result

std::cout << "\nMultiplication of fractions:\n";

(frac1 * frac2).display();

std::cout << std::endl;


return 0;

S18] Write a C++ program to calculate following series: (1) + (1+2) + (1+2+3) + (1+2+3+4)
+ ... +(1+2+3+4+...+n)

Ans- #include <iostream>

// Function to calculate the series sum

int calculateSeriesSum(int n) {

int sum = 0;

int term = 0;

// Iterate through each term of the series

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

// Calculate the sum of numbers from 1 to i

term += i;

sum += term;

return sum;

int main() {

int n;

// Input the value of n from the user

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


std::cin >> n;

// Calculate and display the sum of the series

int seriesSum = calculateSeriesSum(n);

std::cout << "Sum of the series is: " << seriesSum << std::endl;

return 0;

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

#include <iostream>

#include <fstream>

struct Student {

int rollNo;

std::string name;

float percentage;

};

int main() {

int n;

// Input the number of students

std::cout << "Enter the number of students: ";

std::cin >> n;
// Create an array of Student structures to store student information

Student students[n];

// Input student information

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

std::cout << "\nEnter details for student " << i + 1 << ":\n";

std::cout << "Roll number: ";

std::cin >> students[i].rollNo;

std::cout << "Name: ";

std::cin.ignore(); // Ignore the newline character left in the input buffer

std::getline(std::cin, students[i].name);

std::cout << "Percentage: ";

std::cin >> students[i].percentage;

// Open a file for writing student information

std::ofstream outFile("student_info.txt");

// Check if the file is opened successfully

if (!outFile) {

std::cerr << "Error: Unable to open file!" << std::endl;

return 1;

// Write student information to the file

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


outFile << "Student " << i + 1 << ":\n";

outFile << "Roll number: " << students[i].rollNo << std::endl;

outFile << "Name: " << students[i].name << std::endl;

outFile << "Percentage: " << students[i].percentage << "%\n\n";

// Close the file

outFile.close();

std::cout << "\nStudent information has been written to the file 'student_info.txt'." <<
std::endl;

return 0;

S19] Write a C++ program to display factors of a number

Ans- #include <iostream>

void displayFactors(int num) {

std::cout << "Factors of " << num << " are:\n";

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

if (num % i == 0) {

std::cout << i << " ";

std::cout << std::endl;

}
int main() {

int number;

// Input the number from the user

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

std::cin >> number;

// Display factors of the number

displayFactors(number);

return 0;

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

Ans- #include <iostream>

#include <vector>

#include <algorithm>

// Base class Employee

class Employee {

protected:

std::string name;

std::string designation;
public:

// Default constructor

Employee() {}

// Parameterized constructor

Employee(const std::string& n, const std::string& d) : name(n), designation(d) {}

// Function to display employee details

void display() const {

std::cout << "Name: " << name << ", Designation: " << designation;

};

// Base class Project

class Project {

protected:

int projectID;

std::string title;

public:

// Default constructor

Project() {}

// Parameterized constructor

Project(int id, const std::string& t) : projectID(id), title(t) {}


// Function to display project details

void display() const {

std::cout << "Project ID: " << projectID << ", Title: " << title;

};

// Derived class Emp_Proj

class Emp_Proj : public Employee, public Project {

private:

int duration;

public:

// Default constructor

Emp_Proj() {}

// Parameterized constructor

Emp_Proj(const std::string& n, const std::string& d, int id, const std::string& t, int dur)

: Employee(n, d), Project(id, t), duration(dur) {}

// Function to display employee and project details along with duration

void display() const {

Employee::display();

std::cout << ", ";

Project::display();

std::cout << ", Duration: " << duration << " months";

}
// Getter function for duration

int getDuration() const {

return duration;

};

int main() {

std::vector<Emp_Proj> masterTable;

int choice;

do {

std::cout << "\nMenu:\n";

std::cout << "1. Build a master table\n";

std::cout << "2. Display a master table\n";

std::cout << "3. Display Project details in ascending order of duration\n";

std::cout << "4. Exit\n";

std::cout << "Enter your choice: ";

std::cin >> choice;

switch (choice) {

case 1: {

int n;

std::cout << "Enter the number of employees: ";

std::cin >> n;
for (int i = 0; i < n; ++i) {

std::string name, designation, title;

int projectID, duration;

std::cout << "\nEnter details for Employee " << i + 1 << ":\n";

std::cout << "Name: ";

std::cin >> name;

std::cout << "Designation: ";

std::cin >> designation;

std::cout << "Enter details for Project " << i + 1 << ":\n";

std::cout << "Project ID: ";

std::cin >> projectID;

std::cout << "Title: ";

std::cin >> title;

std::cout << "Duration (in months): ";

std::cin >> duration;

masterTable.push_back(Emp_Proj(name, designation, projectID, title, duration));

break;

case 2: {

std::cout << "\nMaster Table:\n";

for (const auto& emp_proj : masterTable) {

emp_proj.display();

std::cout << std::endl;


}

break;

case 3: {

std::cout << "\nProject Details in ascending order of duration:\n";

std::vector<Emp_Proj> sortedTable = masterTable;

std::sort(sortedTable.begin(), sortedTable.end(), [](const Emp_Proj& a, const


Emp_Proj& b) {

return a.getDuration() < b.getDuration();

});

for (const auto& emp_proj : sortedTable) {

emp_proj.display();

std::cout << std::endl;

break;

case 4:

std::cout << "Exiting program.\n";

break;

default:

std::cout << "Invalid choice. Please enter a valid choice.\n";

} while (choice != 4);

return 0;

}
S20] Write a C++ program to sort integer and float array elements in ascending order by
using function overloading.

Ans- #include <iostream>

// Function to sort integer array in ascending order

void sortArray(int arr[], int size) {

for (int i = 0; i < size - 1; ++i) {

for (int j = 0; j < size - i - 1; ++j) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Function to sort float array in ascending order

void sortArray(float arr[], int size) {

for (int i = 0; i < size - 1; ++i) {

for (int j = 0; j < size - i - 1; ++j) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

float temp = arr[j];

arr[j] = arr[j + 1];


arr[j + 1] = temp;

// Function to display array elements

template<typename T>

void displayArray(T arr[], int size) {

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

std::cout << arr[i] << " ";

std::cout << std::endl;

int main() {

int intArr[] = {3, 1, 4, 1, 5, 9, 2, 6};

float floatArr[] = {3.14f, 1.41f, 2.71f, 1.61f, 0.577f, 1.732f};

int intSize = sizeof(intArr) / sizeof(intArr[0]);

int floatSize = sizeof(floatArr) / sizeof(floatArr[0]);

std::cout << "Integer array before sorting: ";

displayArray(intArr, intSize);

sortArray(intArr, intSize);

std::cout << "Integer array after sorting: ";


displayArray(intArr, intSize);

std::cout << "Float array before sorting: ";

displayArray(floatArr, floatSize);

sortArray(floatArr, floatSize);

std::cout << "Float array after sorting: ";

displayArray(floatArr, floatSize);

return 0;

S20] Write a C++ program to create a class Department which contains data members as
Dept_Id, Dept_Name, H.O.D., Number_Of_staff. Write necessary member functions to a.
Accept details from user for ‘n’ departments and write it in a file “Dept.txt”. b. Display
details of department from a file.

Ans- #include <iostream>

#include <fstream>

#include <vector>

class Department {

private:

std::string deptId;

std::string deptName;

std::string hod;

int numberOfStaff;

public:

// Function to accept details of a department from the user


void acceptDetails() {

std::cout << "Enter Department ID: ";

std::cin >> deptId;

std::cout << "Enter Department Name: ";

std::cin.ignore(); // Ignore the newline character left in the input buffer

std::getline(std::cin, deptName);

std::cout << "Enter H.O.D.: ";

std::getline(std::cin, hod);

std::cout << "Enter Number of Staff: ";

std::cin >> numberOfStaff;

// Function to display details of a department

void displayDetails() const {

std::cout << "Department ID: " << deptId << std::endl;

std::cout << "Department Name: " << deptName << std::endl;

std::cout << "H.O.D.: " << hod << std::endl;

std::cout << "Number of Staff: " << numberOfStaff << std::endl;

// Function to write department details to a file

void writeToDeptFile(std::ofstream& outFile) const {

outFile << "Department ID: " << deptId << std::endl;

outFile << "Department Name: " << deptName << std::endl;

outFile << "H.O.D.: " << hod << std::endl;

outFile << "Number of Staff: " << numberOfStaff << std::endl << std::endl;
}

};

int main() {

int n;

std::vector<Department> departments;

std::cout << "Enter the number of departments: ";

std::cin >> n;

// Accept details for 'n' departments

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

Department dept;

std::cout << "\nEnter details for Department " << i + 1 << ":\n";

dept.acceptDetails();

departments.push_back(dept);

// Write department details to file

std::ofstream outFile("Dept.txt");

if (!outFile) {

std::cerr << "Error: Unable to open file!" << std::endl;

return 1;

for (const auto& dept : departments) {


dept.writeToDeptFile(outFile);

outFile.close();

// Display department details from file

std::ifstream inFile("Dept.txt");

if (!inFile) {

std::cerr << "Error: Unable to open file!" << std::endl;

return 1;

std::cout << "\nDetails of Departments from file 'Dept.txt':\n";

std::string line;

while (std::getline(inFile, line)) {

std::cout << line << std::endl;

inFile.close();

return 0;

You might also like