0% found this document useful (0 votes)
3 views84 pages

CPP Practical Slip Program Solution

The document outlines a series of C++ programming tasks, including creating classes, using functions, and implementing various programming concepts such as operator overloading, function overloading, and dynamic memory allocation. Each task includes specific requirements, such as calculating areas, handling file operations, and managing employee information. The document serves as a comprehensive guide for practicing C++ programming skills through practical examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views84 pages

CPP Practical Slip Program Solution

The document outlines a series of C++ programming tasks, including creating classes, using functions, and implementing various programming concepts such as operator overloading, function overloading, and dynamic memory allocation. Each task includes specific requirements, such as calculating areas, handling file operations, and managing employee information. The document serves as a comprehensive guide for practicing C++ programming skills through practical examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Sr.

No Program name Sign Mark


1 write a c++program to check maximum and
minimum of two numbers. (use inline function and
conditional operator)
2 create a c++ class my file with data members file
pointer and silename. Write necessary member
functions to accept and display [Link]
thefollowing operators:
3 write a c++program to find volume of cylinder,
cone and sphere.(use function overloading).
4 Write a C++ program to interchange values
of two integer numbers. (Usecall by
reference).
5 write a c++ program to accept worker information
worker_name , no_of_hours_worked,pay _rate and
salary, write necessary function to calculate and
display the salary of worker .(use defulate value for
pay_rate)
6 write a c++ program to create two class square and
rectangle . compare area of both the shapes using
friend function . accept appropriate data members
for both,the classes.
7 Write C++ program to create two classes Integer_Array and
Float_Array with an array as a data member. Write necessary
member functions to accept and display array elements of both
the classes. Find and display average of both the array. (Use Friend
function)
8 Create a C++ class Marksheet with data members Seat_No,
Student_Name, Class, Subject_Name[], Int_Marks[], Ext_Marks[],
Total[], Grand_Total, Percentage, Grade. Write member function
to accept Student information for 5 subjects. Calculate Total,
Grand_Total, Percentage, Grade and use setw(), setprecision() and
setfill() to display Marksheet.
9 ) Write a C++ program to create a class E_Bill with data
members Cust_Name, Meter_ID, No_of_Units and
Total_Charges. Write member functions to accept and display
customer information by calculating charges. (Rules o
calculate electricity board charges)
. For first 100 units : Rs. 1 per unit
. For next 200 units : Rs. 2 per unit
. Beyond 300 units : Rs. 5 per unit
All users are charged a minimum of Rs.150. If the total
charge is more than Rs.250.00 then an additional charge of
15% is added.
10 Create a C++ class Visiting Staff with data members Name,
No_of_Subjects, Name_of_Subjects[],Workinghours,
TotalSalary. (Number of subjects varies for a Staff).Write a
parameterized constructor to initialize the data members and
create an array for Name_of_Subjects dynamically. Display
Visiting Staff details by calculating salary. (Assume
remuneration Rs. 300 per working hour)
11 Write a C++ program to read array of ‘n’ integers from user
and display it in reverse order. (Use Dynamic memory
allocation)
12 Create a C++ class Employee with data members Emp_Id,
Emp_Name, Mobile_No, Salary. Write necessary member
functions for the following: i. Accept details of n employees ii.
Display employee details in descending order of their salary.
iii. Display details of a particular employee. (Use Array of
object and Use appropriate manipulators)
13 Create a C++ class College, with data members CollegeId,
CollegeName, Establishment_year, University_Name. Overload
operators>> and << to accept and display College information.
14 Create a base class Travels with data members T_no,
Company_Name.Derive a class Route with data members
Route_id, Source, and Destination from Travels class. Also
derive a class Reservation with data members
Number_of_Seats, Travels_Class, Fare, and Travel_Date from
Route. Write a C++ program to perform following necessary
member functions:
15 Write a C++ program to find average of 3 integer numbers
and average of 3 float numbers.(Use function overloading).
16 Create a C++ class Time with data members hours, minutes,
seconds. Write a C++ program using operator overloading to
perform the following:
17 Write a C++ program to calculate mean, mode and median of three
integer numbers. (Use Inline function)
18 Write a C++ program to read the contents of a “[Link]”
file. Create “[Link]” file to store uppercase characters,
“[Link]” file to store lowercase characters, “[Link]” file to
store digits and “[Link]” file to store remaining characters of a
given file.
19 Create a C++ class Fix Deposit with data members FD_No,
Cust_Name, FD_Amt, Interest rate, Maturity amt,
Number_of_months. Create and Initialize all values of FixDeposit
object by using parameterized constructor with default value for
interest rate. Calculate maturity amt using interest rate and display
all the details.
20 Create a C++ class InvoiceBill with data members Order_id,
O_Date, Customer_Name, No_of_Products, Prod_Name[],
Quantity[], Prod_Price[]. A Customer can buy ‘n’ products. Accept
quantity for each product. Generate and Display the bill using
appropriate Manipulators. (Use new operator)
21 Write a C++ program to define two function templates for
calculating the square and cube of given numbers with different
data types.
22 Write a C++ program to overload ‘display_str’ function as
follows:
[Link] display_str(char *) - Display a string in double quotes.
ii. void display_str (int n, char *)- Display first n characters from a
given string.
[Link] display_str (int m, int n,char *)- Display substring of a given
string from position m to n
23 Create a C++ class Employee with data members Emp_id,
EmpName, Company_Name and Salary. Write member functions
to accept and display Employee information. Design User defined
Manipulator to print Salary. (ForSalary set right justification,
maximum width to 7 and fill remaining spaces with ‘*’).
24 Create a C++ class for a two dimensional points. Write necessary
member functions to accept & display the point object. Overload
the following operators: Operator Example Purpose
+ (Binary) P3=P1+P2 Adds coordinates of point pl and p2.
- (Unary) -Pl Negates coordinates of point p1.
*(Binary) P2=P1*n Multiply coordinates of point pl by constant ‘n’.
25 Create a C++ class Number with integer data member. Write
necessary member functions to overload the operator unary pre
and post increment ‘++’.
26 Create a C++ class for inventory of Mobiles with data
members Model, Mobile _Company, Color, Price and
Quantity. Mobile can be sold, if stock is available, otherwise
purchase will be made. Write necessary member functions for
the following:
i. To accept mobile details from user.
ii. To sale a mobile. (Sale contains Mobile details & number of
mobiles to be sold).
iii. To Purchase a Mobile. (Purchase contains Mobile details
& number of mobiles to be purchased)
27 Write a C++ program to create a class Distance with data members
meter and centimeter to represent distance. Write a function
Larger( ) to return the larger of two distances. (Use this pointer)
28 Create a C++ base class Media. Derive two different classes from it,
class NewsPaper with data members N_Name, NEditor, N_Price,
No_ofPages and class Magazine with data members M_Name,
M_Editor, M_Price. Write a C++ program to accept and display
information of both NewsPaper and Magazine. (Use pure virtual
function)
29 Create a C++ class Student with data members Roll_no, S_Name,
Class, Percentage. Accept two students information and display
information of student having maximum percentage. (Use this
pointer)
30 Create a C++ class MyArray with data members
- int *arr
- int size
Write necessary member functions to accept and display Array
elements. Overload the following operators: Operator Example
Purpose
31 Create a C++ class MyMatrix. Write a C++ program to accept and
display a Matrix. Overload binary '-’ operator to calculate
subtraction of two matrices
Slip1(a):-write a c++program to check maximum and minimum of two
numbers. (use inline function and conditional operator)
#include <iostream>

using namespace std;

// Inline function to find the maximum of two numbers

inline int getMax(int a, int b) {

return (a > b) ? a : b;

// Inline function to find the minimum of two numbers

inline int getMin(int a, int b) {

return (a < b) ? a : b;

int main() {

int num1, num2;

// Taking input from the user

cout << "Enter two integers: ";

cin >> num1 >> num2;

// Displaying results

cout << "Maximum: " << getMax(num1, num2) << endl;

cout << "Minimum: " << getMin(num1, num2) << endl;

return 0;
}

OUTPUT:

Slip 1:(b):-create a c++ class my file with data members file pointer and
silename. Write necessary member functions to accept and display
[Link] thefollowing operators:
#include <stdio.h>

#include <stdlib.h>

#include <istream>

#include <conio.h>

#include <ctype.h>

#include <fstream>

#include <iostream>

using namespace std;

#include <string.h>

#define MAXSIZE (10)

class myfile

FILE *fp;

char fn[MAXSIZE];

public:

myfile(const char *fname)

{
strcpy(fn, fname);

myfile operator+(myfile);

void operator!();

void display();

};

void myfile::display()

fp = fopen(fn, "r");

char ch;

while ((ch = fgetc(fp)) != EOF)

cout << ch;

fclose(fp);

void myfile::operator!()

myfile f4("[Link]");

char ch;

fp = fopen(fn, "r");

[Link] = fopen([Link], "w");

while ((ch = fgetc(fp)) != EOF)

if (isupper(ch))

fputc(tolower(ch), [Link]);

else if (islower(ch))
fputc(toupper(ch), [Link]);

else

fputc(ch, [Link]);

fclose(fp);

fclose([Link]);

remove("[Link]");

rename("[Link]", "[Link]");

myfile myfile::operator+(myfile f2)

myfile f3("[Link]");

fp = fopen(fn, "r");

[Link] = fopen([Link], "r");

[Link] = fopen([Link], "w");

char ch;

while ((ch = fgetc(fp)) != EOF)

fputc(ch, [Link]);

fclose(fp);

while ((ch = fgetc([Link])) != EOF)

fputc(ch, [Link]);

_fcloseall();

return f3;
}

int main()

myfile f1("[Link]");

myfile f2("[Link]");

myfile f3("[Link]");

cout << "first file \n";

[Link]();

cout << "\nsecond file \n";

[Link]();

f3 = f1 + f2;

cout << "\nAfter concatnation file is ";

[Link]();

cout << "\nAfter changes case \n";

!f3;

[Link]();

return 0;

OUTPUT:

Slip2: (a):- write a c++program to find volume of cylinder, cone and sphere.
(use function overloading).
#include<iostream>

using namespace std;

float volume(float r, float h) {

return (3.14*r*2*h);

float coneVol(float r, float h) {

return (3.14*r*2*h/3);

float volume(float r) {

return (4/3*3.14*r*r*r);

int main() {

float cy_h, cy_r, co_h, co_r, sp_r;

cout << "Enter dimensions" << endl;

cout << "1. Cylinder" << endl;

cout << "Height: ";

cin >> cy_h;

cout << "Radius: ";

cin >> cy_r;

cout << endl;

cout << "2. Cone" << endl;

cout << "Height: ";

cin >> co_h;

cout << "Radius: ";

cin >> co_r;

cout << endl;

cout << "3. Sphere" << endl;


cout << "Radius: ";

cin >> sp_r;

cout << endl;

cout << "The volume of Cylinder is: " << volume(cy_h, cy_r) << endl;

cout << "The volume of Cone is: " << coneVol(co_h, co_r) << endl;

cout << "The volume of Sphere is: " << volume(sp_r) << endl;

return 0;

OUTPUT:

Slip 3(a):Write a C++ program to interchange values of two integer


numbers. (Usecall by reference).
#include<iostream>

using namespace std;

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

int temp;

temp = a;

a = b;
b = temp;

int main() {

int a,b;

cout << "Enter two numbers" << endl;

cout << "Enter first number: ";

cin >> a;

cout << "Enter second number: ";

cin >> b;

cout << endl << "Original Numbers" << endl << "a = " << a << " & b = " << b << endl;

swap(a, b);

cout << endl << "After swap Numbers" << endl << "a = " << a << " & b = " << b << endl;

return 0;

OUTPUT:

Slip 4(a):write a c++ program to accept worker information worker_name ,


no_of_hours_worked,pay _rate and salary, write necessary function to
calculate and display the salary of worker .(use defulate value for pay_rate)
#include<iostream>
using namespace std;

class WorkerInformation {
char Worker_Name[50];
int No_Of_Hours_Worked, Salary;

public:
void acccept() {
cout << "Enter name of the worker: ";
cin >> Worker_Name;

cout << "Enter number of hours worked: ";


cin >> No_Of_Hours_Worked;

void display() {
cout << endl << "Worker details" << endl;
cout << "Name: " << Worker_Name << endl;
cout << "Salary: " << calSal(No_Of_Hours_Worked) << endl;
}

int calSal(int work_hrs, int pay_rate=100) {


return (work_hrs*pay_rate);
}
};

int main() {
WorkerInformation w;

[Link]();
[Link]();
return 0;
}

OUTPUT:

Slip:6(a) write a c++ program to create two class square and rectangle .
compare area of both the shapes using friend function . accept appropriate
data members for both,the classes.
#include<iostream>
using namespace std;

class Square {

public:

int s;

void getdata() {

cout << "Enter the side of the square: ";

cin >> s;

int calArea() {

return (s*s);

friend void compare(int s, int r);

};

class Rectangle {

public:

int l, w;

void getdata() {

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

cin >> l;

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

cin >> w;
}

int calArea() {

return (l*w);

friend void compare(int s, int r);

};

void compare(int s, int r) {

if(s > r) {

cout << "The area of square is bigger than area of rectangle." << endl;

} else {

cout << "The area of rectangle is bigger than area of square." << endl;

int main() {

int s_area, r_area;

Square s1;

Rectangle r1;

[Link]();

s_area = [Link]();

[Link]();
r_area = [Link]();

cout << "Square: " << s_area << endl;

cout << "Rectangle: " << r_area << endl;

compare(s_area, r_area);

return 0;

OUTPUT:

Slip 30:(a): Write C++ program to create two classes Integer_Array and Float_Array with an
array as a data member. Write necessary member functions to accept and display array
elements of both the classes. Find and display average of both the array. (Use Friend
function)

#include <iostream>

using namespace std;

class Integer_Array;

class Float_Array;

// Friend function declaration to calculate and display the average of arrays

void calculateAverage(Integer_Array &intArr, Float_Array &floatArr);

class Integer_Array {

private:

int arr[5]; // Array of integers with size 5


public:

// Function to accept array elements

void accept() {

cout << "Enter 5 integer values for Integer Array: ";

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

cin >> arr[i];

// Function to display array elements

void display() {

cout << "Integer Array: ";

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

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

cout << endl;

// Friend function to calculate average

friend void calculateAverage(Integer_Array &intArr, Float_Array &floatArr);

};

class Float_Array {

private:

float arr[5]; // Array of floats with size 5

public:

// Function to accept array elements

void accept() {

cout << "Enter 5 float values for Float Array: ";

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


cin >> arr[i];

// Function to display array elements

void display() {

cout << "Float Array: ";

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

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

cout << endl;

// Friend function to calculate average

friend void calculateAverage(Integer_Array &intArr, Float_Array &floatArr);

};

// Friend function definition to calculate and display the average of both arrays

void calculateAverage(Integer_Array &intArr, Float_Array &floatArr) {

// Calculate and display the average of Integer Array

float intAvg = 0;

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

intAvg += [Link][i];

intAvg /= 5;

// Calculate and display the average of Float Array

float floatAvg = 0;

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

floatAvg += [Link][i];

}
floatAvg /= 5;

// Display the results

cout << "Average of Integer Array: " << intAvg << endl;

cout << "Average of Float Array: " << floatAvg << endl;

int main() {

Integer_Array intArr;

Float_Array floatArr;

// Accept array elements

[Link]();

[Link]();

// Display array elements

[Link]();

[Link]();

// Calculate and display averages using the friend function

calculateAverage(intArr, floatArr);

return 0;

}
OUTPUT:

Slip30(b): Create a C++ class Marksheet with data members Seat_No, Student_Name, Class,
Subject_Name[], Int_Marks[], Ext_Marks[], Total[], Grand_Total, Percentage, Grade. Write member
function to accept Student information for 5 subjects. Calculate Total, Grand_Total, Percentage,
Grade and use setw(), setprecision() and setfill() to display Marksheet.

#include <iostream>

#include <iomanip> // For setw(), setprecision(), and setfill()

using namespace std;

class Marksheet {

private:

int Seat_No;

string Student_Name;

string Class;

string Subject_Name[5];

int Int_Marks[5]; // Internal marks for 5 subjects

int Ext_Marks[5]; // External marks for 5 subjects

int Total[5]; // Total marks for each subject (Internal + External)

int Grand_Total;
float Percentage;

char Grade;

public:

// Function to accept student information and marks

void accept() {

cout << "Enter Seat Number: ";

cin >> Seat_No;

[Link](); // To ignore any newline character left by cin

cout << "Enter Student Name: ";

getline(cin, Student_Name);

cout << "Enter Class: ";

getline(cin, Class);

// Accept subject names and marks for 5 subjects

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

cout << "Enter Subject " << i + 1 << " Name: ";

getline(cin, Subject_Name[i]);

cout << "Enter Internal Marks for " << Subject_Name[i] << ": ";

cin >> Int_Marks[i];

cout << "Enter External Marks for " << Subject_Name[i] << ": ";

cin >> Ext_Marks[i];

// Calculate Total marks for each subject

Total[i] = Int_Marks[i] + Ext_Marks[i];

// Function to calculate Grand Total, Percentage, and Grade

void calculate() {

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

Grand_Total += Total[i];

// Assuming the maximum marks for each subject are 100

int max_marks = 100 * 5; // 5 subjects with 100 marks each

Percentage = (float)Grand_Total / max_marks * 100;

// Determine Grade based on Percentage

if (Percentage >= 90)

Grade = 'A';

else if (Percentage >= 75)

Grade = 'B';

else if (Percentage >= 50)

Grade = 'C';

else

Grade = 'F';

// Function to display the marksheet

void display() {

// Set formatting for displaying the marksheet

cout << setw(50) << setfill('-') << "" << endl;

cout << setw(20) << left << "Marksheet" << setw(30) << right << "Seat No: " <<
Seat_No << endl;

cout << setw(50) << setfill('-') << "" << endl;

cout << setw(20) << left << "Student Name: " << setw(30) << right << Student_Name
<< endl;

cout << setw(20) << left << "Class: " << setw(30) << right << Class << endl;

cout << setw(50) << setfill('-') << "" << endl;


cout << setw(10) << left << "Subject" << setw(15) << left << "Internal" << setw(15) <<
left << "External" << setw(15) << left << "Total" << endl;

cout << setw(50) << setfill('-') << "" << endl;

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

cout << setw(10) << left << Subject_Name[i]

<< setw(15) << left << Int_Marks[i]

<< setw(15) << left << Ext_Marks[i]

<< setw(15) << left << Total[i] << endl;

cout << setw(50) << setfill('-') << "" << endl;

// Display Grand Total, Percentage, and Grade

cout << setw(10) << left << "Grand Total: " << setw(20) << right << Grand_Total <<
endl;

cout << setw(10) << left << "Percentage: " << setw(20) << right << fixed <<
setprecision(2) << Percentage << "%" << endl;

cout << setw(10) << left << "Grade: " << setw(20) << right << Grade << endl;

cout << setw(50) << setfill('-') << "" << endl;

};

int main() {

Marksheet marksheet;

// Accept student information and marks

[Link]();

// Calculate Grand Total, Percentage, and Grade

[Link]();

// Display the marksheet

[Link]();

return 0;
}

OUTPUT:

Slip 29 - A) Write a C++ program to create a class E_Bill with data members Cust_Name,
Meter_ID, No_of_Units and Total_Charges. Write member functions to accept and display
customer information by calculating charges. (Rules o calculate electricity board charges)
. For first 100 units : Rs. 1 per unit
. For next 200 units : Rs. 2 per unit
. Beyond 300 units : Rs. 5 per unit
All users are charged a minimum of Rs.150. If the total charge is more than Rs.250.00 then
an additional charge of 15% is added.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class E_Bill {
private:
string Cust_Name;
int Meter_ID;
int No_of_Units;
float Total_Charges;
public:
// Function to accept customer information and units used
void accept() {
cout << "Enter Customer Name: ";
getline(cin, Cust_Name);
cout << "Enter Meter ID: ";
cin >> Meter_ID;
cout << "Enter Number of Units Used: ";
cin >> No_of_Units;
}
// Function to calculate total charges based on the number of units
void calculateCharges() {
float basicCharges = 0;
// For the first 100 units
if (No_of_Units <= 100) {
basicCharges = No_of_Units * 1.0;
}
// For the next 200 units (101 to 300)
else if (No_of_Units <= 300) {
basicCharges = 100 * 1.0 + (No_of_Units - 100) * 2.0;
}
// For units above 300
else {
basicCharges = 100 * 1.0 + 200 * 2.0 + (No_of_Units - 300) * 5.0;
}
// Minimum charge of Rs. 150
if (basicCharges < 150) {
basicCharges = 150;
}
// If the charge exceeds Rs. 250, add 15% extra charge
if (basicCharges > 250) {
Total_Charges = basicCharges + (basicCharges * 0.15);
} else {
Total_Charges = basicCharges;
}
}
// Function to display the customer bill details
void display() {
cout << "\n---------------------- E-Bill ----------------------" << endl;
cout << "Customer Name: " << Cust_Name << endl;
cout << "Meter ID: " << Meter_ID << endl;
cout << "Number of Units Used: " << No_of_Units << endl;
cout << fixed << setprecision(2); // Display the charges with 2 decimal places
cout << "Total Charges: Rs. " << Total_Charges << endl;
cout << "------------------------------------------------------" << endl;
}
};
int main() {
E_Bill bill;
// Accept customer information and units used
[Link]();
// Calculate total charges based on the units used
[Link]();
// Display the calculated bill
[Link]();
return 0;
}
OUTPUT:

Slip27-(b):Create a C++ class Visiting Staff with data members Name, No_of_Subjects,
Name_of_Subjects[],Workinghours, TotalSalary. (Number of subjects varies for a
Staff).Write a parameterized constructor to initialize the data members and create an array for
Name_of_Subjects dynamically. Display Visiting Staff details by calculating salary. (Assume
remuneration Rs. 300 per working hour)
Solution:
#include <iostream>

#include <string>

#include <iomanip>

using namespace std;

class VisitingStaff {

private:

string Name;

int No_of_Subjects;

string* Name_of_Subjects; // Dynamic array to store the names of subjects

int Workinghours;

float TotalSalary;

public:

// Parameterized constructor to initialize data members

VisitingStaff(string name, int numSubjects, int hours) {

Name = name;

No_of_Subjects = numSubjects;

Workinghours = hours;

Name_of_Subjects = new string[No_of_Subjects]; // Dynamically allocating memory for


subject names

// Accept the names of subjects

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

cout << "Enter name of Subject " << i + 1 << ": ";

cin >> Name_of_Subjects[i];

}
// Calculate Total Salary (Rs. 300 per working hour)

TotalSalary = Workinghours * 300;

// Function to display the details of the visiting staff

void display() {

cout << "\n----------- Visiting Staff Details -----------\n";

cout << "Name: " << Name << endl;

cout << "Number of Subjects: " << No_of_Subjects << endl;

cout << "Subjects: ";

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

cout << Name_of_Subjects[i] << " ";

cout << endl;

cout << "Working Hours: " << Workinghours << endl;

cout << fixed << setprecision(2); // Display the salary with two decimal points

cout << "Total Salary: Rs. " << TotalSalary << endl;

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

// Destructor to free dynamically allocated memory

~VisitingStaff() {

delete[] Name_of_Subjects; // Deallocating the dynamically allocated memory

};

int main() {

string name;

int numSubjects, hours;


// Accept staff details

cout << "Enter the name of the visiting staff: ";

cin >> name;

cout << "Enter number of subjects: ";

cin >> numSubjects;

cout << "Enter total working hours: ";

cin >> hours;

// Create a VisitingStaff object using the parameterized constructor

VisitingStaff staff(name, numSubjects, hours);

// Display the visiting staff details

[Link]();

return 0;

OUTPUT:

Slip 28(a): Write a C++ program to read array of ‘n’ integers from user and display it in
reverse order. (Use Dynamic memory allocation)

#include <iostream>
using namespace std;

int main() {

int n;

// Asking user to enter the number of elements in the array

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

cin >> n;

// Dynamically allocating memory for the array

int* arr = new int[n];

// Reading the elements of the array from the user

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

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

cin >> arr[i];

// Displaying the elements in reverse order

cout << "Array in reverse order: ";

for (int i = n - 1; i >= 0; i--) {

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

cout << endl;

// Deallocating the dynamically allocated memory

delete[] arr;

return 0;

OUTPUT:
Slip-28(b) Create a C++ class Employee with data members Emp_Id, Emp_Name,
Mobile_No, Salary. Write necessary member functions for the following: i. Accept details of
n employees ii. Display employee details in descending order of their salary. iii. Display
details of a particular employee. (Use Array of object and Use appropriate manipulators)

#include <iostream>

#include <iomanip>

#include <vector>

#include <algorithm>

using namespace std;

class Employee {

private:

int Emp_Id;

string Emp_Name;

string Mobile_No;

double Salary;

public:

// Function to accept employee details

void acceptDetails() {

cout << "Enter Employee ID: ";

cin >> Emp_Id;

[Link](); // To ignore any newline character left in the buffer

cout << "Enter Employee Name: ";


getline(cin, Emp_Name);

cout << "Enter Mobile Number: ";

getline(cin, Mobile_No);

cout << "Enter Salary: ";

cin >> Salary;

// Function to display employee details

void displayDetails() const {

cout << setw(15) << left << Emp_Id

<< setw(25) << left << Emp_Name

<< setw(15) << left << Mobile_No

<< setw(10) << right << fixed << setprecision(2) << Salary << endl;

// Getter function to get the employee salary

double getSalary() const {

return Salary;

// Getter function to get the employee ID

int getEmpId() const {

return Emp_Id;

// Function to display employee details by ID

void displayById(int id) const {

if (Emp_Id == id) {

cout << "\nEmployee Found!" << endl;

displayDetails();

}
}

// Static function to compare employees based on salary (for sorting)

static bool compareSalary(Employee &e1, Employee &e2) {

return [Link]() > [Link](); // Sort in descending order of salary

};

int main() {

int n;

cout << "Enter number of employees: ";

cin >> n;

// Create an array of Employee objects dynamically

vector<Employee> employees(n);

// Accept details of n employees

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

cout << "\nEnter details for employee " << i + 1 << ":" << endl;

employees[i].acceptDetails();

// Sort employees based on salary in descending order

sort([Link](), [Link](), Employee::compareSalary);

// Display employee details in descending order of their salary

cout << "\nEmployee details sorted by salary (Descending):" << endl;

cout << setw(15) << left << "Emp_Id"

<< setw(25) << left << "Emp_Name"

<< setw(15) << left << "Mobile_No"

<< setw(10) << right << "Salary" << endl;

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

employees[i].displayDetails();
}

// Display details of a particular employee

int searchId;

cout << "\nEnter Employee ID to search: ";

cin >> searchId;

bool found = false;

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

employees[i].displayById(searchId);

found = true;

if (!found) {

cout << "Employee with ID " << searchId << " not found!" << endl;

return 0;

OUTPUT:
Slip-27(a): Create a C++ class College, with data members CollegeId, CollegeName,
Establishment_year, University_Name. Overload operators>> and << to accept and display College
information.

#include <iostream>

#include <string>

using namespace std;

class College {

private:

int CollegeId;

string CollegeName;

int Establishment_year;

string University_Name;

public:

// Overloading the >> operator to accept College information

friend istream& operator>>(istream& in, College& c) {

cout << "Enter College ID: ";

in >> [Link];

[Link](); // Ignore the newline left by cin

cout << "Enter College Name: ";

getline(in, [Link]);

cout << "Enter Establishment Year: ";

in >> c.Establishment_year;

[Link](); // Ignore the newline left by cin

cout << "Enter University Name: ";

getline(in, c.University_Name);

return in;

}
// Overloading the << operator to display College information

friend ostream& operator<<(ostream& out, const College& c) {

out << "College ID: " << [Link] << endl;

out << "College Name: " << [Link] << endl;

out << "Establishment Year: " << c.Establishment_year << endl;

out << "University Name: " << c.University_Name << endl;

return out;

};

int main() {

College c;

// Accepting College information using overloaded >> operator

cin >> c;

// Displaying College information using overloaded << operator

cout << "\nCollege Information:\n";

cout << c;

return 0;

OUTPUT:
Slip-27(b): Create a base class Travels with data members T_no, Company_Name.Derive a
class Route with data members Route_id, Source, and Destination from Travels class. Also
derive a class Reservation with data members Number_of_Seats, Travels_Class, Fare, and
Travel_Date from Route. Write a C++ program to perform following necessary member
functions:

i, Accept details of ‘n’ reservations.

ii. Display details of all reservations.

iii. Display reservation details of a specified Date.

#include <iostream>

#include <string>

#include <vector>

#include <iomanip>

using namespace std;

// Base class: Travels

class Travels {

protected:

int T_no; // Travel number

string Company_Name; // Name of the travel company

public:

// Accept details of the travel

void acceptTravelDetails() {
cout << "Enter Travel Number: ";

cin >> T_no;

[Link](); // Ignore newline character left by cin

cout << "Enter Company Name: ";

getline(cin, Company_Name);

// Display travel details

void displayTravelDetails() const {

cout << setw(15) << left << T_no

<< setw(25) << left << Company_Name;

};

// Derived class: Route

class Route : public Travels {

protected:

int Route_id; // Route ID

string Source; // Source of the journey

string Destination; // Destination of the journey

public:

// Accept route details

void acceptRouteDetails() {

cout << "Enter Route ID: ";

cin >> Route_id;

[Link](); // Ignore newline character left by cin

cout << "Enter Source: ";

getline(cin, Source);

cout << "Enter Destination: ";

getline(cin, Destination);
}

// Display route details

void displayRouteDetails() const {

displayTravelDetails();

cout << setw(15) << left << Route_id

<< setw(20) << left << Source

<< setw(20) << left << Destination;

};

// Derived class: Reservation

class Reservation : public Route {

private:

int Number_of_Seats; // Number of seats reserved

string Travels_Class; // Class of travel (e.g., First Class, Economy)

double Fare; // Fare per seat

string Travel_Date; // Date of travel

public:

// Accept reservation details

void acceptReservationDetails() {

acceptTravelDetails();

acceptRouteDetails();

cout << "Enter Number of Seats: ";

cin >> Number_of_Seats;

[Link](); // Ignore newline character left by cin

cout << "Enter Travel Class: ";

getline(cin, Travels_Class);

cout << "Enter Fare per Seat: ";

cin >> Fare;


[Link](); // Ignore newline character left by cin

cout << "Enter Travel Date (DD-MM-YYYY): ";

getline(cin, Travel_Date);

// Display reservation details

void displayReservationDetails() const {

displayRouteDetails();

cout << setw(15) << left << Number_of_Seats

<< setw(20) << left << Travels_Class

<< setw(10) << right << fixed << setprecision(2) << Fare

<< setw(15) << left << Travel_Date << endl;

// Getter function to get the Travel Date

string getTravelDate() const {

return Travel_Date;

};

int main() {

int n;

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

cin >> n;

[Link](); // Ignore newline character left by cin

// Create a vector to store n reservations

vector<Reservation> reservations(n);

// Accept details of n reservations

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

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

reservations[i].acceptReservationDetails();
}

// Display details of all reservations

cout << "\nAll Reservations Details:\n";

cout << setw(15) << left << "Travel No"

<< setw(25) << left << "Company Name"

<< setw(15) << left << "Route ID"

<< setw(20) << left << "Source"

<< setw(20) << left << "Destination"

<< setw(15) << left << "Seats"

<< setw(20) << left << "Travel Class"

<< setw(10) << right << "Fare"

<< setw(15) << left << "Travel Date" << endl;

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

reservations[i].displayReservationDetails();

// Display reservation details for a specified date

string searchDate;

cout << "\nEnter Travel Date (DD-MM-YYYY) to search for reservations: ";

getline(cin, searchDate);

bool found = false;

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

if (reservations[i].getTravelDate() == searchDate) {

cout << "\nReservation details for " << searchDate << ":\n";

reservations[i].displayReservationDetails();

found = true;

if (!found) {
cout << "No reservations found for " << searchDate << endl;

return 0;

OUTPUT:

Slip-26(a): Write a C++ program to find average of 3 integer numbers and average of 3 float
numbers.(Use function overloading).

#include <iostream>

using namespace std;

// Function to calculate the average of 3 integers

double average(int num1, int num2, int num3) {

return (num1 + num2 + num3) / 3.0; // Returning the average as a double

// Function to calculate the average of 3 floats

double average(float num1, float num2, float num3) {

return (num1 + num2 + num3) / 3.0; // Returning the average as a double

int main() {

// Variables to store the integers and floats

int int1, int2, int3;

float float1, float2, float3;

// Input 3 integers

cout << "Enter 3 integers: ";


cin >> int1 >> int2 >> int3;

// Calculate and display the average of integers

double intAvg = average(int1, int2, int3);

cout << "Average of integers: " << intAvg << endl;

// Input 3 floats

cout << "Enter 3 float numbers: ";

cin >> float1 >> float2 >> float3;

// Calculate and display the average of floats

double floatAvg = average(float1, float2, float3);

cout << "Average of floats: " << floatAvg << endl;

return 0;

OUTPUT:

Slip-26(b): Create a C++ class Time with data members hours, minutes, seconds. Write a C++
program using operator overloading to perform the following:

I.!= To check whether two Times are equal or not.

ii. >> To accept the time.

iii. << To display the time

#include <iostream>

using namespace std;

class Time {

private:
int hours;

int minutes;

int seconds;

public:

// Constructor to initialize time

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

// Overload the >> operator to accept time input

friend istream& operator>>(istream& in, Time& t) {

cout << "Enter hours: ";

in >> [Link];

cout << "Enter minutes: ";

in >> [Link];

cout << "Enter seconds: ";

in >> [Link];

return in;

// Overload the << operator to display the time

friend ostream& operator<<(ostream& out, const Time& t) {

out << [Link] << " hours " << [Link] << " minutes " << [Link] << " seconds";

return out;

// Overload the != operator to check if two times are not equal

bool operator!=(const Time& t) const {

return (hours != [Link] || minutes != [Link] || seconds != [Link]);

};

int main() {

Time time1, time2;

// Accepting the time for the first object

cout << "Enter details for time1:\n";


cin >> time1;

// Accepting the time for the second object

cout << "Enter details for time2:\n";

cin >> time2;

// Displaying both times

cout << "\nTime1: " << time1 << endl;

cout << "Time2: " << time2 << endl;

// Checking if times are not equal

if (time1 != time2) {

cout << "\nThe two times are not equal." << endl;

} else {

cout << "\nThe two times are equal." << endl;

return 0;

OUTPUT:

Slip-25(a): Write a C++ program to calculate mean, mode and median of three integer numbers.
(Use Inline function)

#include <iostream>

#include <algorithm>
using namespace std;

// Inline function to calculate the mean

inline double mean(int a, int b, int c) {

return (a + b + c) / 3.0;

// Inline function to calculate the mode

inline int mode(int a, int b, int c) {

if (a == b && b == c) {

return a; // All three numbers are the same

} else if (a == b) {

return a; // a and b are the same

} else if (b == c) {

return b; // b and c are the same

} else if (a == c) {

return a; // a and c are the same

} else {

return -1; // No mode

// Inline function to calculate the median

inline double median(int a, int b, int c) {

// Sorting the numbers to find the middle value

int arr[] = {a, b, c};

sort(arr, arr + 3);

return arr[1]; // The middle value of the sorted array

int main() {

int num1, num2, num3;

// Input the three integers

cout << "Enter three integers: ";


cin >> num1 >> num2 >> num3;

// Calculate and display the mean

cout << "Mean: " << mean(num1, num2, num3) << endl;

// Calculate and display the mode

int modeValue = mode(num1, num2, num3);

if (modeValue == -1) {

cout << "Mode: No mode (all numbers are different)" << endl;

} else {

cout << "Mode: " << modeValue << endl;

// Calculate and display the median

cout << "Median: " << median(num1, num2, num3) << endl;

return 0;

OUTPUT:

Slip-25(b): Write a C++ program to read the contents of a “[Link]” file. Create
“[Link]” file to store uppercase characters, “[Link]” file to store lowercase characters,
“[Link]” file to store digits and “[Link]” file to store remaining characters of a given file.

#include <iostream>

#include <fstream>

#include <cctype> // For isdigit, isupper, islower functions

using namespace std;

int main() {

// Open the input file "[Link]" for reading


ifstream inputFile("[Link]");

// Check if the file was successfully opened

if (!inputFile) {

cout << "Error: Could not open the input file." << endl;

return 1; // Return with an error code

// Open the output files for writing

ofstream upperFile("[Link]");

ofstream lowerFile("[Link]");

ofstream digitFile("[Link]");

ofstream otherFile("[Link]");

// Check if the output files were successfully opened

if (!upperFile || !lowerFile || !digitFile || !otherFile) {

cout << "Error: Could not open one or more output files." << endl;

return 1; // Return with an error code

char ch;

// Read each character from the input file

while ([Link](ch)) {

if (isupper(ch)) {

[Link](ch); // Write uppercase characters to [Link]

} else if (islower(ch)) {

[Link](ch); // Write lowercase characters to [Link]

} else if (isdigit(ch)) {

[Link](ch); // Write digits to [Link]

} else {

[Link](ch); // Write other characters (punctuation, spaces) to [Link]

// Close all the files


[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

cout << "File processing completed successfully!" << endl;

return 0; // Indicating successful completion

OUTPUT:

Slip-24(a): Create a C++ class Fix Deposit with data members FD_No, Cust_Name, FD_Amt,
Interest rate, Maturity amt, Number_of_months. Create and Initialize all values of FixDeposit
object by using parameterized constructor with default value for interest rate. Calculate
maturity amt using interest rate and display all the details.

#include <iostream>

#include <string>

using namespace std;

class FixDeposit {

private:

int FD_No;

string Cust_Name;

double FD_Amt;

double InterestRate; // Interest rate as a percentage

double MaturityAmt;

int Number_of_months;

public:

// Parameterized constructor with default interest rate of 5%

FixDeposit(int fdNo, string custName, double fdAmt, int months, double interestRate = 5.0) {
FD_No = fdNo;

Cust_Name = custName;

FD_Amt = fdAmt;

Number_of_months = months;

InterestRate = interestRate;

MaturityAmt = 0.0;

// Calculate Maturity Amount

calculateMaturityAmount();

// Function to calculate Maturity Amount

void calculateMaturityAmount() {

// Formula for Maturity Amount: FD_Amt * (1 + (InterestRate / 100) * (Number_of_months


/ 12))

MaturityAmt = FD_Amt * (1 + (InterestRate / 100) * (Number_of_months / 12.0));

// Function to display details of the fixed deposit

void displayDetails() {

cout << "FD Number: " << FD_No << endl;

cout << "Customer Name: " << Cust_Name << endl;

cout << "Fixed Deposit Amount: " << FD_Amt << endl;

cout << "Interest Rate: " << InterestRate << "%" << endl;

cout << "Number of Months: " << Number_of_months << endl;

cout << "Maturity Amount: " << MaturityAmt << endl;

};

int main() {

// Create an object of FixDeposit with all values

FixDeposit fd1(101, "John Doe", 50000.0, 24, 6.0); // FD with 6% interest rate for 24 months

[Link]();

cout << endl;


// Create another object of FixDeposit with default interest rate (5%)

FixDeposit fd2(102, "Jane Smith", 100000.0, 12); // FD with default interest rate for 12
months

[Link]();

return 0;

OUTPUT:

Slip-24(b): Create a C++ class InvoiceBill with data members Order_id, O_Date,
Customer_Name, No_of_Products, Prod_Name[], Quantity[], Prod_Price[]. A Customer can buy
‘n’ products. Accept quantity for each product. Generate and Display the bill using appropriate
Manipulators. (Use new operator)

#include <iostream>

#include <iomanip>

#include <string>

using namespace std;

class InvoiceBill {

private:

int Order_id;

string O_Date;

string Customer_Name;

int No_of_Products;
string* Prod_Name; // Dynamically allocated array of product names

int* Quantity; // Dynamically allocated array of quantities

double* Prod_Price; // Dynamically allocated array of product prices

public:

// Constructor to initialize the invoice details and allocate memory for arrays

InvoiceBill(int order_id, string o_date, string customer_name, int no_of_products) {

Order_id = order_id;

O_Date = o_date;

Customer_Name = customer_name;

No_of_Products = no_of_products;

// Dynamically allocate memory for product names, quantities, and prices

Prod_Name = new string[No_of_Products];

Quantity = new int[No_of_Products];

Prod_Price = new double[No_of_Products];

// Destructor to release dynamically allocated memory

~InvoiceBill() {

delete[] Prod_Name;

delete[] Quantity;

delete[] Prod_Price;

// Method to accept product details from the user

void acceptProductDetails() {

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

cout << "\nEnter details for product " << i + 1 << ": " << endl;

cout << "Product Name: ";

cin >> Prod_Name[i];

cout << "Quantity: ";

cin >> Quantity[i];

cout << "Price per product: ";


cin >> Prod_Price[i];

// Method to display the invoice bill

void generateBill() {

double totalAmount = 0;

cout << "\n\nInvoice Bill" << endl;

cout << "--------------------------------------" << endl;

cout << "Order ID: " << Order_id << endl;

cout << "Order Date: " << O_Date << endl;

cout << "Customer Name: " << Customer_Name << endl;

cout << "--------------------------------------" << endl;

cout << left << setw(20) << "Product Name"

<< setw(10) << "Quantity"

<< setw(15) << "Unit Price"

<< setw(15) << "Total Price" << endl;

cout << "--------------------------------------" << endl;

// Loop through products and display each one with calculated total price

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

double totalPrice = Quantity[i] * Prod_Price[i];

totalAmount += totalPrice;

cout << left << setw(20) << Prod_Name[i]

<< setw(10) << Quantity[i]

<< setw(15) << fixed << setprecision(2) << Prod_Price[i]

<< setw(15) << fixed << setprecision(2) << totalPrice << endl;

cout << "--------------------------------------" << endl;

cout << "Total Amount: " << fixed << setprecision(2) << totalAmount << endl;

};
int main() {

int orderId, noOfProducts;

string orderDate, customerName;

// Accepting order details

cout << "Enter Order ID: ";

cin >> orderId;

cout << "Enter Order Date: ";

cin >> orderDate;

cout << "Enter Customer Name: ";

[Link](); // to ignore the newline character left by previous cin

getline(cin, customerName);

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

cin >> noOfProducts;

// Create an InvoiceBill object

InvoiceBill invoice(orderId, orderDate, customerName, noOfProducts);

// Accept product details

[Link]();

// Generate and display the bill

[Link]();

return 0;

OUTPUT:
Slip-22(a): Write a C++ program to define two function templates for calculating the square and
cube of given numbers with different data types.

#include <iostream>

using namespace std;

// Function template for calculating square of a number

template <typename T>

T square(T x) {

return x * x;

// Function template for calculating cube of a number

template <typename T>

T cube(T x) {
return x * x * x;

int main() {

// Test with integer data type

int num1 = 5;

cout << "Square of " << num1 << " is: " << square(num1) << endl;

cout << "Cube of " << num1 << " is: " << cube(num1) << endl;

// Test with float data type

float num2 = 4.5f;

cout << "Square of " << num2 << " is: " << square(num2) << endl;

cout << "Cube of " << num2 << " is: " << cube(num2) << endl;

// Test with double data type

double num3 = 3.7;

cout << "Square of " << num3 << " is: " << square(num3) << endl;

cout << "Cube of " << num3 << " is: " << cube(num3) << endl;

return 0;

OUTPUT:

Slip-22(b): Write a C++ program to overload ‘display_str’ function as follows:

[Link] display_str(char *) - Display a string in double quotes.

ii. void display_str (int n, char *)- Display first n characters from a given string.

[Link] display_str (int m, int n,char *)- Display substring of a given string from position m to n.

#include <iostream>
#include <cstring> // For strlen()

using namespace std;

// Function to display the string in double quotes

void display_str(char* str) {

cout << "\"" << str << "\"" << endl;

// Function to display the first 'n' characters of a string

void display_str(int n, char* str) {

for (int i = 0; i < n && str[i] != '\0'; i++) {

cout << str[i];

cout << endl;

// Function to display a substring from position 'm' to 'n'

void display_str(int m, int n, char* str) {

if (m >= 0 && n >= m && m < strlen(str) && n < strlen(str)) {

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

cout << str[i];

cout << endl;

} else {

cout << "Invalid range." << endl;

int main() {

char str[] = "Hello, world!";

// Test case 1: Display the string in double quotes

display_str(str);

// Test case 2: Display the first 'n' characters (e.g., 5 characters)

int n = 5;
display_str(n, str);

// Test case 3: Display a substring from position 'm' to 'n' (e.g., from index 7 to 11)

int m = 7, n_sub = 11;

display_str(m, n_sub, str);

return 0;

OUTPUT:

Slip-21(a): Create a C++ class Employee with data members Emp_id, EmpName, Company_Name and
Salary. Write member functions to accept and display Employee information. Design User defined
Manipulator to print Salary. (ForSalary set right justification, maximum width to 7 and fill remaining
spaces with ‘*’).

#include <iostream>

#include <iomanip> // For setting width, fill, and right justification

using namespace std;

// Class Employee definition

class Employee {

private:

int Emp_id;

string EmpName;

string Company_Name;

double Salary;

public:

// Function to accept employee details

void acceptDetails() {

cout << "Enter Employee ID: ";

cin >> Emp_id;


[Link](); // To ignore the newline character after entering Emp_id

cout << "Enter Employee Name: ";

getline(cin, EmpName);

cout << "Enter Company Name: ";

getline(cin, Company_Name);

cout << "Enter Salary: ";

cin >> Salary;

// Function to display employee details

void displayDetails() const {

cout << "Employee ID: " << Emp_id << endl;

cout << "Employee Name: " << EmpName << endl;

cout << "Company Name: " << Company_Name << endl;

cout << "Salary: ";

// Calling the user-defined manipulator to display salary

displaySalary(Salary);

cout << endl;

// User-defined manipulator to display Salary with specific formatting

void displaySalary(double salary) const {

cout << right << setw(7) << setfill('*') << salary; // Right justification, width 7, fill with '*'

};

int main() {

Employee emp;

// Accepting employee details

[Link]();

// Displaying employee details

cout << endl << "Employee Details:" << endl;

[Link]();
return 0;

OUTPUT:

Slip-21(b): Create a C++ class for a two dimensional points. Write necessary member functions to
accept & display the point object. Overload the following operators: Operator Example Purpose

+ (Binary) P3=P1+P2 Adds coordinates of point pl and p2.

- (Unary) -Pl Negates coordinates of point p1.

*(Binary) P2=P1*n Multiply coordinates of point pl by constant ‘n’.

#include <iostream>

using namespace std;

class Point {

private:

int x, y; // Coordinates of the point

public:

// Constructor to initialize point coordinates

Point(int x = 0, int y = 0) : x(x), y(y) {}

// Function to accept the point coordinates

void acceptPoint() {

cout << "Enter x coordinate: ";

cin >> x;

cout << "Enter y coordinate: ";


cin >> y;

// Function to display the point coordinates

void displayPoint() const {

cout << "(" << x << ", " << y << ")";

// Overload + operator to add two points (binary operator)

Point operator+(const Point& p) {

return Point(x + p.x, y + p.y);

// Overload - operator to negate the point's coordinates (unary operator)

Point operator-() {

return Point(-x, -y);

// Overload * operator to multiply point by a constant (binary operator)

Point operator*(int n) {

return Point(x * n, y * n);

};

int main() {

// Create two points

Point P1, P2;

// Accept coordinates for P1 and P2

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

[Link]();

cout << "Enter details for Point 2:\n";

[Link]();

// Display the points

cout << "Point 1: ";

[Link]();
cout << "\nPoint 2: ";

[Link]();

// Demonstrate the overloaded + operator (P3 = P1 + P2)

Point P3 = P1 + P2;

cout << "\nP3 (P1 + P2): ";

[Link]();

// Demonstrate the overloaded - operator (-P1)

Point P4 = -P1;

cout << "\nP4 (-P1): ";

[Link]();

// Demonstrate the overloaded * operator (P1 * 3)

Point P5 = P1 * 3;

cout << "\nP5 (P1 * 3): ";

[Link]();

return 0;

OUTPUT:

Slip-20(a): Create a C++ class Number with integer data member. Write necessary member functions
to overload the operator unary pre and post increment ‘++’.

#include <iostream>

using namespace std;


class Number {

private:

int value; // Integer data member

public:

// Constructor to initialize the value

Number(int val = 0) : value(val) {}

// Function to display the number

void display() const {

cout << "Value: " << value << endl;

// Overload pre-increment (Unary Operator ++x)

Number& operator++() {

++value; // Increment the value first

return *this; // Return the current object

// Overload post-increment (Unary Operator x++)

Number operator++(int) {

Number temp = *this; // Save the current value in a temporary object

++value; // Increment the value after saving the current state

return temp; // Return the object with the old value

};

int main() {

Number num1(5);

cout << "Original ";

[Link]();

// Pre-increment

++num1;

cout << "After Pre-increment ";

[Link]();
// Post-increment

num1++;

cout << "After Post-increment ";

[Link]();

return 0;

OUTPUT:

Slip-20(b): Create a C++ class for inventory of Mobiles with data members Model, Mobile
_Company, Color, Price and Quantity. Mobile can be sold, if stock is available, otherwise
purchase will be made. Write necessary member functions for the following:
i. To accept mobile details from user.
ii. To sale a mobile. (Sale contains Mobile details & number of mobiles to be sold).
iii. To Purchase a Mobile. (Purchase contains Mobile details & number of mobiles to be
purchased)

#include <iostream>

#include <string>

using namespace std;

class MobileInventory {

private:

string model;

string mobile_company;

string color;
float price;

int quantity;

public:

// Constructor to initialize an empty inventory item

MobileInventory() : price(0.0), quantity(0) {}

// Function to accept mobile details from the user

void acceptMobileDetails() {

cout << "Enter Mobile Model: ";

cin >> model;

cout << "Enter Mobile Company: ";

cin >> mobile_company;

cout << "Enter Mobile Color: ";

cin >> color;

cout << "Enter Mobile Price: ";

cin >> price;

cout << "Enter Mobile Quantity: ";

cin >> quantity;

// Function to sale a mobile

void saleMobile() {

int num_to_sell;

cout << "\nEnter the number of mobiles to sell: ";


cin >> num_to_sell;

if (num_to_sell <= quantity) {

quantity -= num_to_sell;

cout << num_to_sell << " mobiles of " << model << " sold successfully.\n";

cout << "Remaining stock: " << quantity << endl;

} else {

cout << "Not enough stock available to sell " << num_to_sell << " mobiles.\n";

cout << "Current stock: " << quantity << endl;

// Function to purchase a mobile

void purchaseMobile() {

int num_to_purchase;

cout << "\nEnter the number of mobiles to purchase: ";

cin >> num_to_purchase;

quantity += num_to_purchase;

cout << num_to_purchase << " mobiles of " << model << " purchased successfully.\n";

cout << "Updated stock: " << quantity << endl;

// Function to display the mobile inventory details

void displayMobileDetails() {
cout << "\nMobile Details:\n";

cout << "Model: " << model << endl;

cout << "Company: " << mobile_company << endl;

cout << "Color: " << color << endl;

cout << "Price: " << price << endl;

cout << "Stock Quantity: " << quantity << endl;

};

int main() {

MobileInventory mobile;

int choice;

do {

cout << "\nMobile Inventory System\n";

cout << "1. Accept Mobile Details\n";

cout << "2. Sell Mobile\n";

cout << "3. Purchase Mobile\n";

cout << "4. Display Mobile Details\n";

cout << "5. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:
[Link]();

break;

case 2:

[Link]();

break;

case 3:

[Link]();

break;

case 4:

[Link]();

break;

case 5:

cout << "Exiting... Thank you!\n";

break;

default:

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

} while (choice != 5);

return 0;
}
OUTPUT:

Slip19-(a): Write a C++ program to create a class Distance with data members meter and
centimeter to represent distance. Write a function Larger( ) to return the larger of two
distances. (Use this pointer)

#include <iostream>

using namespace std;

class Distance {

private:

int meter;

int centimeter;

public:

// Constructor to initialize distance

Distance(int m = 0, int cm = 0) : meter(m), centimeter(cm) {}

// Function to display distance

void display() const {

cout << meter << " meters " << centimeter << " centimeters" << endl;

// Function to return larger distance using 'this' pointer

Distance* Larger(Distance& d) {
// Convert both distances to centimeters for comparison

int totalCentimeters1 = this->meter * 100 + this->centimeter;

int totalCentimeters2 = [Link] * 100 + [Link];

if (totalCentimeters1 >= totalCentimeters2) {

return this;

} else {

return &d;

};

int main() {

// Creating two Distance objects

Distance d1(5, 50); // 5 meters 50 centimeters

Distance d2(6, 30); // 6 meters 30 centimeters

// Displaying both distances

cout << "Distance 1: ";

[Link]();

cout << "Distance 2: ";

[Link]();

// Find and display the larger distance

Distance* largerDistance = [Link](d2);

cout << "Larger distance is: ";


largerDistance->display();

return 0;
}
OUTPUT:

Slip-19(b): Create a C++ base class Media. Derive two different classes from it, class
NewsPaper with data members N_Name, NEditor, N_Price, No_ofPages and class Magazine
with data members M_Name, M_Editor, M_Price. Write a C++ program to accept and
display information of both NewsPaper and Magazine. (Use pure virtual function)
#include <iostream>

#include <string>

using namespace std;

// Abstract base class Media with a pure virtual function

class Media {

public:

// Pure virtual function to be implemented by derived classes

virtual void acceptData() = 0; // pure virtual function

virtual void displayData() const = 0; // pure virtual function

// Virtual destructor

virtual ~Media() {}

};

// Derived class NewsPaper

class NewsPaper : public Media {

private:

string N_Name;

string NEditor;

float N_Price;
int No_ofPages;

public:

// Function to accept data for NewsPaper

void acceptData() override {

cout << "Enter Newspaper Name: ";

getline(cin, N_Name);

cout << "Enter Newspaper Editor: ";

getline(cin, NEditor);

cout << "Enter Newspaper Price: ";

cin >> N_Price;

cout << "Enter Number of Pages: ";

cin >> No_ofPages;

[Link](); // to consume the newline character after entering the number

// Function to display data for NewsPaper

void displayData() const override {

cout << "\nNewspaper Details:" << endl;

cout << "Name: " << N_Name << endl;

cout << "Editor: " << NEditor << endl;

cout << "Price: " << N_Price << endl;

cout << "Number of Pages: " << No_ofPages << endl;

};

// Derived class Magazine

class Magazine : public Media {

private:

string M_Name;

string M_Editor;

float M_Price;

public:
// Function to accept data for Magazine

void acceptData() override {

cout << "Enter Magazine Name: ";

getline(cin, M_Name);

cout << "Enter Magazine Editor: ";

getline(cin, M_Editor);

cout << "Enter Magazine Price: ";

cin >> M_Price;

[Link](); // to consume the newline character after entering the price

// Function to display data for Magazine

void displayData() const override {

cout << "\nMagazine Details:" << endl;

cout << "Name: " << M_Name << endl;

cout << "Editor: " << M_Editor << endl;

cout << "Price: " << M_Price << endl;

};

int main() {

// Creating pointers of type Media to accept and display data

Media* mediaPtr;

// Creating a NewsPaper object and accepting its data

NewsPaper newspaper;

mediaPtr = &newspaper;

mediaPtr->acceptData();

mediaPtr->displayData();

// Creating a Magazine object and accepting its data

Magazine magazine;

mediaPtr = &magazine;

mediaPtr->acceptData();
mediaPtr->displayData();

return 0;

OUTPUT:

Slip-18(a): Create a C++ class Student with data members Roll_no, S_Name, Class, Percentage.
Accept two students information and display information of student having maximum percentage.
(Use this pointer)

#include <iostream>

#include <string>

using namespace std;

class Student {

private:

int Roll_no;

string S_Name;

string Class;

float Percentage;

public:
// Constructor to initialize data members

Student(int r = 0, string name = "", string c = "", float perc = 0.0) : Roll_no(r),
S_Name(name), Class(c), Percentage(perc) {}

// Function to accept student information

void acceptData() {

cout << "Enter Roll Number: ";

cin >> Roll_no;

[Link](); // to ignore the newline character after entering Roll_no

cout << "Enter Name: ";

getline(cin, S_Name);

cout << "Enter Class: ";

getline(cin, Class);

cout << "Enter Percentage: ";

cin >> Percentage;

[Link](); // to ignore the newline character after entering Percentage

// Function to display student information

void displayData() const {

cout << "\nStudent Details:\n";

cout << "Roll Number: " << Roll_no << endl;

cout << "Name: " << S_Name << endl;

cout << "Class: " << Class << endl;

cout << "Percentage: " << Percentage << "%" << endl;

// Function to return the student with higher percentage using 'this' pointer

Student* getHigherPercentageStudent(Student& otherStudent) {

if (this->Percentage >= [Link]) {


return this; // return the current student if their percentage is higher or equal

} else {

return &otherStudent; // return the other student if their percentage is higher

};

int main() {

// Creating two Student objects

Student student1, student2;

// Accepting data for both students

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

[Link]();

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

[Link]();

// Find the student with the maximum percentage

Student* higherPercentageStudent = [Link](student2);

// Display the student with the higher percentage

cout << "\nStudent with higher percentage:\n";

higherPercentageStudent->displayData();

return 0;

OUTPUT:
Slip-18(b): Create a C++ class MyArray with data members

- int *arr

- int size

Write necessary member functions to accept and display Array elements. Overload the following
operators: Operator Example Purpose

- (Unary) -Al Reverse array elements.

+(Binary) A2=A+n Add constant n to all array elements.

#include <iostream>

using namespace std;

class MyArray {

private:

int *arr;

int size;

public:

// Constructor to initialize the array with a given size

MyArray(int s) : size(s) {
arr = new int[size]; // Dynamically allocate memory for array

// Destructor to free the dynamically allocated memory

~MyArray() {

delete[] arr;

// Function to accept array elements from the user

void acceptData() {

cout << "Enter " << size << " array elements:\n";

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

cin >> arr[i];

// Function to display array elements

void displayData() const {

cout << "Array elements: ";

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

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

cout << endl;

// Overloading unary - operator to reverse the array elements

void operator-() {

int start = 0;

int end = size - 1;

while (start < end) {

// Swap the elements


int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

// Overloading binary + operator to add a constant 'n' to all array elements

MyArray operator+(int n) {

MyArray temp(size); // Create a temporary array to hold the result

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

[Link][i] = arr[i] + n; // Add 'n' to each element

return temp; // Return the modified array

};

int main() {

int size;

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

cin >> size;

// Create an object of MyArray class

MyArray arr1(size);

// Accept and display array elements for arr1

[Link]();

[Link]();

// Use unary - operator to reverse the array elements

-arr1; // Reverse the array using the overloaded unary - operator


cout << "Array after reversing: ";

[Link]();

// Use binary + operator to add a constant value to each element

int n;

cout << "Enter the constant value to add to all elements: ";

cin >> n;

MyArray arr2 = arr1 + n; // Add n to each element of arr1

cout << "Array after adding " << n << ": ";

[Link]();

return 0;

OUTPUT:

Slip-17(a): Create a C++ class MyMatrix. Write a C++ program to accept and display a Matrix.
Overload binary '-’ operator to calculate subtraction of two matrices.

#include <iostream>

using namespace std;

class MyMatrix {

private:

int **matrix;

int rows, cols;

public:
// Constructor to initialize the matrix with given dimensions

MyMatrix(int r, int c) : rows(r), cols(c) {

matrix = new int*[rows]; // Allocate memory for rows

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

matrix[i] = new int[cols]; // Allocate memory for columns in each row

// Destructor to free the dynamically allocated memory

~MyMatrix() {

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

delete[] matrix[i]; // Delete each row

delete[] matrix; // Delete the matrix array

// Function to accept matrix elements

void acceptData() {

cout << "Enter elements of the matrix (" << rows << "x" << cols << "):\n";

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

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

cin >> matrix[i][j];

// Function to display the matrix

void displayData() const {

cout << "Matrix (" << rows << "x" << cols << "):\n";

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


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

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

cout << endl;

// Overloading the binary - operator to subtract two matrices

MyMatrix operator-(const MyMatrix& m) {

// Ensure matrices have the same dimensions

if (rows != [Link] || cols != [Link]) {

cout << "Matrix dimensions do not match for subtraction!" << endl;

exit(1); // Exit the program if dimensions don't match

MyMatrix result(rows, cols); // Create a result matrix with the same dimensions

// Perform subtraction

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

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

[Link][i][j] = matrix[i][j] - [Link][i][j];

return result; // Return the resulting matrix

};

int main() {

int rows, cols;

// Get matrix dimensions from the user

cout << "Enter number of rows: ";


cin >> rows;

cout << "Enter number of columns: ";

cin >> cols;

// Create two matrix objects

MyMatrix matrix1(rows, cols);

MyMatrix matrix2(rows, cols);

// Accept data for both matrices

cout << "\nEnter data for Matrix 1:\n";

[Link]();

cout << "\nEnter data for Matrix 2:\n";

[Link]();

// Display both matrices

cout << "\nMatrix 1:\n";

[Link]();

cout << "\nMatrix 2:\n";

[Link]();

// Subtract matrix2 from matrix1

MyMatrix result = matrix1 - matrix2;

// Display the result of subtraction

cout << "\nResult of Matrix 1 - Matrix 2:\n";

[Link]();

return 0;

OUTPUT:

You might also like