0% found this document useful (0 votes)
8 views

CSE201R01_OOP using C++_Manual_2025 (1)

The document is a laboratory manual for the Object Oriented Programming course in C++ (CSE201R01) at SASTRA University. It includes various exercises covering topics such as input/output, manipulators, reference arguments, inline functions, classes and objects, constructors, destructors, and classes with arrays. Each exercise provides specific programming tasks to enhance understanding of C++ concepts.

Uploaded by

nani.647000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

CSE201R01_OOP using C++_Manual_2025 (1)

The document is a laboratory manual for the Object Oriented Programming course in C++ (CSE201R01) at SASTRA University. It includes various exercises covering topics such as input/output, manipulators, reference arguments, inline functions, classes and objects, constructors, destructors, and classes with arrays. Each exercise provides specific programming tasks to enhance understanding of C++ concepts.

Uploaded by

nani.647000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Object Oriented Programming in C++

Laboratory

Course Code
Code: CSE201R01

Semester: II

Lab Manual
2025

SCHOOL OF COMPUTING
SHANMUGHA ARTS, SCIENCE, TECHNOLOGY AND RESEARCH
ACADEMY
(SASTRA Deemed to be) University
Tirumalaisamudram, Than
Thanjavur-613 401
Ex No 1 – Input/Output and Manipulators

1. Write a C++ program to find whether a given number is a perfect number


or not. A perfect number is a positive integer that is equal to the sum of its
proper divisors or divisors excluding the number itself. Take the number
as input from user and output the result as perfect number or not a perfect
number

2. Design your own manipulator to provide the following output


specification for printing money value:
i. 10 columns width
ii. The character '$' at the beginning
iii. Showing '+' sign.
iv. Two digits precision
v. Filling of unused spaces with ' * '
vi. Trailing zeros shown

3. Write a program that prompts the user to input that number of quarters,
dimes, and nickels. The program then outputs the total value of the coins
in dollars and cents. For example your output may look like this.
Enter the number of quarters: 5
Enter the number of dimes: 3
Enter the number of nickels: 4
Your charge totals to $1.75

4. When a value is smaller than a field specified with setw(), the unused
locations are, by default, filled in with spaces. The manipulator setfill()
takes a single character as an argument and causes this character to be
substituted for spaces in the empty parts of a field. Rewrite the WIDTH
program so that the characters on each line between the location name
and the population number are filled in with periods instead of spaces, as
in Portcity.....2425785

5. By default, output is right-justified in its field. You can left-justify text


output using the manipulator setiosflags(ios::left). Use this manipulator,
along with setw(), to help generate the following output:

Last name First name Street address Town State


------------------------------------------------------------------------------------------------------
Jones Bernard 109 Pine Lane Little town MI
O’Brian Coleen 42 E. 99th Ave. Bigcity NY
Wong Harry 121-A Alabama St. Lakeville IL

CSE201R01 – Object Oriented Programming in C++ Laboratory 2


Ex No 2 – Reference arguments and Default arguments

1. Write a C++ program to update the given numbers. Use the following
functions: getInput() function should take n1 and n2 as reference
arguments and get input for them. swap() function should take n1 and n2
as reference arguments and swap their values. The main function should
call the above functions and display the modified values.

2. Define a bestofTwoCIA() function that accepts two arrays of students


CIA1 and CIA2 marks, number of students and a result array as
arguments. The function compares the CIA1 and CIA2 marks of each
student and picks the maximum of them, assigns it into the result array.
Call this function from the main() by passing the sample marks, students
count and a result array. Print the result array contents after the function
call and check the result. Write a CPP program to implement the above
scenario.

3. Write a C++ program to print the Fibonacci sequence. The


printSequence() function should take two parameters for the first two
terms of the Fibonacci sequence and print the ‘n’ subsequent terms. If the
parameters are not specified, it should be taken as the default values of 0
and 1. The main function should call the above function and display the
Fibonacci sequence.

4. Write a C++ program to calculate the power of a number. The


getInput() function takes two reference parameters to get input for the
base and the exponent. The calculatePower() function calculates the
power of the number taking the base and exponent as parameters where
the exponent has a default value of 2 and returns the power. The main
function should call the above functions and display the calculated power.

5. Write a function that updates a bank account balance after a deposit or


withdrawal. Declare balance as a local variable in the main function.
 void getBalance(): This function takes balance as reference
argument and reads input from the user for initial opening balance.
 void deposit(): This function takes two arguments namely balance
and amount where balance is a reference argument, and amount is
default argument with default value of 100. The function should
update the balance appropriately and display the current balance.
 int withdraw(): This function takes two arguments namely balance
and amount where balance is a reference argument. The function

CSE201R01 – Object Oriented Programming in C++ Laboratory 3


should update the balance appropriately. Display the withdrawn
money which is returned from the function to the user along with
the current balance.
The main function should call the above functions and display the
modified balance after the operations.

CSE201R01 – Object Oriented Programming in C++ Laboratory 4


Ex No 3 - Inline functions and function overloading

1. Write a program to find the largest of three numbers using inline functions.

2. Write a program to sort arrays of different types (integer, float and


character) by overloading the sort function. Declare the three arrays in
main, ask user what type of values to be sorted, get input for the array of
that type, pass it to the sort function and print the sorted array from main.

3. Program to compute the volume of a cylinder using default arguments.


Define a function computeVolume() that receives two arguments, radius
and height. Use a default value of 4.5 for radius and 7 for height. Calculate
the volume of the cylinder by calling the functions from the main(), without
arguments, with 1 argument, and with 2 arguments.

4. Write overloaded functions named calculateVolume that:


 Calculate the volume of a cube (given side length).
 Calculate the volume of a rectangular box (given length, width, and
height).
 Calculate the volume of a cylinder (given radius and height).

5. Write a program to check if a student got a pass or fail in an exam. Define


a function getData() as inline that receives 3 marks (int type) as input from
user. Call the getData() function from main by passing the variables of
marks by reference. Print the marks in the main() function. Define another
function, calculate(), that receives the 3 marks as arguments and computes
their average. If the average is greater than 50 then print “PASS”.
Otherwise, print “FAIL.” Implement the above program and verify the
result.

CSE201R01 – Object Oriented Programming in C++ Laboratory 5


Ex No 4 – Class and Objects

1. Create a Book class with attributes such as title, author, and ISBN. Include
appropriate member functions to get book information’s and display book
details.

2. Design a Class called Polygon with attributes as number of sides and length
of each side. Implement appropriate member functions to calculate the
perimeter and area of different polygon, then display the results.

3. Create a class called CarPark that has the members CarRegnNo(int),


ChargePerHour(int) and ParkingDuration(float). Set the data and show the
charges and parked hours of a car based on CarRegnNo. Make appropriate
member functions for setting and showing the data.

4. Build a Mobile-Phone class with attributes like brand, model, price, and
Battery-Life. Implement appropriate member functions to store mobile
details and check if the phone is affordable or not based on the user given
budget.

5. Create a class called Participant that contains data members -- name,


participant Id, age, gender, marital status, and event name. Include the
following member functions
 getdata() to get all detail except participant Id and event name from the
user
 getLength() this function should return the length of the participant’s name
without using built-in function.
 getInitial() this function should return first character of the participant’s
name.
 getID() this function should call getInitial() and getLength() functions to fill
participantId (eg:. j5 name is “jagan”).
 toCaps() to change the participant’s name into uppercase and attach pre-fix
(Mr./Mrs./Miss/Master) based on age, gender & marital_status of the
participant.
 allotEvent() to fix event for the participant based on their age.
 putdata() to display the data.

Age Event Name


<=18 Long jump
>18 && <=50 Running
>50 and above Lemon with spoon race

CSE201R01 – Object Oriented Programming in C++ Laboratory 6


Write a main() function to exercise this class. Get the details of a participant,
then apply all functions and finally, display his/her details.

CSE201R01 – Object Oriented Programming in C++ Laboratory 7


Ex No 5 Constructors and destructors

1. Write a C++ program to create a Product class with a non-parameterized


constructor to initialize the private members product ID, name, and price.
Implement a destructor to display a message “object destroyed” when the
product object is destroyed. Add member functions to input values to the
product members, to calculate the total cost for a given quantity of the
product and to display the product details.

2. Write a C++ code to create class String class. Declare a character array
str to store a string and a variable len to store the length of the string.
Implement default constructor to initialize the string to be empty and a
parameterized constructor to initialize it with a user specified string.
Define a member function Length() to find the length of the string and
assign it to len. Provide a display function to show the string and its length
to the user.

3. Create a C++ program to calculate the area of different shapes using


overloaded constructors. Design a class Shape with constructors
overloaded to handle the calculation of the area for a rectangle, circle, and
triangle. Use appropriate parameters for each shape (e.g., length and
breadth for a rectangle, radius for a circle, and base and height for a
triangle). Implement the constructors and write a program to demonstrate
their functionality by calculating and displaying the area of all three
shapes.

4. Create a C++ program with a Distance class to calculate the sum of two
distances given in feet and inches using a function Design the class
Distance with two data members: feet and inches. Use a parameterized
constructor to initialize the distances. Develop a member function to add
two Distance objects by passing the second object as an argument to the
function and display the result. Ensure that the inches are properly
converted to feet if they exceed 12. Write a program to demonstrate the
functionality by creating two Distance objects, add them, and display the
result.

5. Create a class called Person that has three private data members name,
age and height and thefollowing public member functions:
 Default constructor – To initialize the data members

CSE201R01 – Object Oriented Programming in C++ Laboratory 8


 Parameterized constructor – To initialize them with the given values
 getInput() - To get the person details from the user
 showOutput() - A constant member function to display the person
details.
 getHeight() – To return the value of the height variable
Names should be left justified and age and height to be right justified.
Develop a function named isTaller() which is a function that takes the
person object array as parameter, retrieves the heights using the getHeight()
and finds the tallest person. Write a main function to create an array of 3
Person objects and find the tallest person. Display all the persons details and
print the details of the tallest person.

CSE201R01 – Object Oriented Programming in C++ Laboratory 9


Ex No 6. Classes with arrays and array of objects

1. Create a class called Matrix that contains an attribute


mat1[10][10](integer), rows and cols. Implement a member function named
getMat() to retrieve the matrix values. Additionally, include three functions:
diagonalSum() for calculating the sum of diagonal values and rowSum()
for computing the sum of each row. Finally, write the main() function to test
the class by creating its object and invoking the functions.

2. Write a C++ program to manage car rentals for a rental company. Each car
in the rental fleet should have attributes such as carID (integer) , make
(string) to store the car manufacturer name, model (string) for the car's
model, year (integer) representing the year of manufacturing, rentalPrice
(float) indicating the daily rental price, and availabilityStatus (bool) to
indicate whether the car is available in the fleet or rented (true if available,
false if rented). The program should use an array of objects to represent the
cars in the rental fleet. Provide functionalities to input car details, to rent a
car using the car id (modify availability status to false) and to display all
available cars

3. Write a C++ program to define a class Employee with attributes including


employee_id (integer), name (string), designation (string)(e.g., "Manager,"
"Team Lead," "Engineer"), salary (float), bonus (float) and
totalCompensation (float). The program should allow the user to input
details for multiple employees using an array of objects. Implement
necessary constructors, methods getdetails() to input employee
details(validate that the salary is non-negative while accepting input),
cal_comp()to calculate the bonus(designation based) and total
compensation and finally method to display the all details of each
employee. Write a main() function to exercise the above functionalities.

4. Write a C++ program to create a student class with attributes rollNumber


(integer), name (string), marks (array of floats to store marks for 5
subjects), average (float to store the average of the marks) and grade(char).
Include necessary constructors, a getDetails() method to input the student's
details,validate()to check if marks are within the range of 0 to 100,
cal_grade() to calculate average and set grade, and a printDetails() method
to display the student's information. In the main program, declare an array
of Student objects to store and manage information for multiple students.
CSE201R01 – Object Oriented Programming in C++ Laboratory 10
The program should prompt the user to input details for each student,
validate marks, and display all students' information, including their
calculated average and grades.

5. Define a class called TNEB with the following members: EB number,


Consumer Name, Consumer type( domestic or commercial), Units
consumed, and Bill amount. Use constructor to initialize the class
members. Provide a member function getDetails to get the input for class
members. Implement generateBill to generate the bill amount based on the
consumer type and the units consumed. The showBill function displays the
bill.

For domestic consumers the monthly bill is calculated as follows:


Number of units consumed Rate per unit
1 to 50 Rs 5
51 to 100 Rs 7
101 to 200 Rs 9
201 and above Rs 11
Minimum bill amount is Rs 50. If the total bill exceeds 5000 then add a
penalty of %2 on the bill amount.
For example, if the number of units consumed is 545 then the bill amount is
to be calculated as follows:
50 X 5 + 50 X 7 + 100 X 9 + 345 X 11 = 5295
Since 5295 > 5000 add 2 % penalty = 5295 + 105 = 5400

For commercial consumers the bill amount is calculated as follows:


Number of units consumed Rate per unit
1 to 50 Rs 8
51 to 100 Rs 10
101 to 200 Rs 12
201 and above Rs 14
Note: Minimum bill amount should be Rs 100. If the total bill exceeds
10,000 then add a penalty of %2 on the bill amount.
Declare an array of objects for the TNEB class in main() and calculate the
bill amount of multiple consumers of different types.

CSE201R01 – Object Oriented Programming in C++ Laboratory 11


Ex No: 7 String class and its functions

1. Write a C++ program to get a line of text by using string obj and implement
the following operations
 Find empty spaces in the given text
 If only one space between words, add one more extra space
 If more than two spaces, reduce to two

2. A chat application that needs to analyze messages for inappropriate


content. As part of the development team, you're assigned the task of
implementing and testing the functionality using the string class in C++
a. Write a function to count the total number of vowels, display the
individual counts of each vowel, and determine and display which vowel
has the highest count.
b. Write a function to count the number of words in a message.
c. Write a function to check if a specific keyword is present in a message. If
present, return the starting position of the first occurrence of the keyword.

3. Create a Class String with private string objects (eg: string s1,s2) and two
methods: int merge (string s1, string s2) : this method will return 1 for
merging two different strings and return 0 for merging two same strings. int
compare (): this method should compare two strings and return 1 if first
string is greater; 0 otherwise.

4. Define two classes as class A and class B. A contains a string and B contains
a character array. Initialize them using constructors. Define two
overloaded isPalindrome functions in both the class A and B. Class A
should check whether the string stored in class A’s object is a palindrome. If
so, it should return true, else return false. class B should do the same for the
string in class B’s object.

5. Design a StringManipulator class to handle strings of any length and


provide various string formatting functionalities. The class should include a
parameterized constructor to initialize the string with a user-specified
value. It should also have member functions to perform specific string
transformations: capitalize(), which converts the first character of the string
to uppercase; toSentenceCase(), which converts the entire string to
lowercase while capitalizing the first character; toTitleCase(), which
capitalizes the first letter of each word in the string; Additionally, the class
should provide getString() to allow the user to input a new string and
CSE201R01 – Object Oriented Programming in C++ Laboratory 12
putString() to display the current string. In the main program, a menu-
driven interface should be implemented to let the user create a
StringManipulator object, choose various formatting options, and view the
updated string, demonstrating the full functionality of the class.

CSE201R01 – Object Oriented Programming in C++ Laboratory 13


Ex No: 8 Class templates

1. Write a generic function to find the maximum of two numbers of


integers and floating point numbers.

2. Write a program with a generic function to swap two values any type.
The values to be swapped needs to be passed as call by reference from
main function and display the swapped values.

3. Write program to sort an array of numbers using bubble sort. Implement


bubbleSort as a generic function to sort both integers and floating point
numbers.

4. Implement a matrix class template that supports operations for the


addition of two matrix objects and for displaying the matrix. Include a
member function to input values. add() function should take object2 as an
arguments and add the matrix in object1 with the matrix in object2. If
dimensions don’t match throw an error message. The result of the addition
should be returned as a result object and print it by invoking display on
the result object.

5. Write a program to perform insert, delete and empty operations on an


array. Define a generic class containing the array. Through the insert
function, a value can be inserted at the end of the array or at the beginning
of the array as per user choice. If array is full show an error message.
Similarly delete operation can remove a value from beginning or end.
Error message should be shown in case of empty array. Empty function
removes all the values and makes the array empty. Provide a menu to let
the user choose the type of values to be stored in the array as 1. Integer 2.
Char 3. Float and create a specific object for that type.

CSE201R01 – Object Oriented Programming in C++ Laboratory 14


Ex No: 9 Operator overloading

1. Create a class Distance with attributes for feet and inches. Overload the +
operator to add two Distance objects and return the resulting distance.

2. Create a class Player with attributes such as name and score. Overload the
> operator to compare two players based on their scores and determine
which player has a higher score.

3. Create a class Employee with attributes such as name, age, designation,


and salary. Overload the << operator to display the employee details in a
well-formatted manner.

4. Design a class BankAccount to represent a bank account with attributes


like account number, account holder name, and balance. Overload the +=
operator to deposit money and the -= operator to withdraw money from
the account. Ensure that the withdraw operation is permitted only whem
there is sufficient balance in account. Implement viewSummary function to
show the details of the account.

5. Implement a Date class that represents date as day, month and year.
Overload the various operators to perform operations on the Date object.
Overload + operator to add days to the Date to find a future date. Overload
- operator to subtract days from the Date to find a past date. Overload == to
find whether two Date objects have the same date. Overload ++ operator to
increment the Date by one day.

CSE201R01 – Object Oriented Programming in C++ Laboratory 15


Ex No: 10 Inheritance

1. Define a class called Person which has the members to represent a person
with the values of name, gender, age, type and nationality. Implement a
constructor in the Person class to initialize its members. Derive two classes
from the Person class as Singer and Author. The singer class should
contain the member variables for number of songs sung and number of
awards won. Type of singer can be carnatic or western or fork. Singer class
should have the member variables for language of writing (English or
Tamil or Telugu ) and number of books published. Type of writer can be
novel or history or technical. Both these classes must have constructors to
initialize their own members as well as the members of their base class.
Include read() and print() functions in the derived classes to get input and
to display the values of their members.

2. Create a class called Payroll with the members of Basic pay, HRA, DA,
PF, Gross pay and Netpay. Add a default constructor to initialize all the
values to 0. Define a member function named getSalary() with the formula
for salary calculation provided below. Derive a class Employee from
Payroll with the members of Name, Age, Date of joining and Designation.
Include a member function as getEmployeeDetails() to get input for the
member variables. Declare an object of Employee and invoke the two
functions.
Gross Pay(GP) = Basic Pay(BP) + HRA( 17% of BP) + DA( 45 % of BP)
Net Pay = GP – PF( 12% of GP)

3. Define a base class named Blue bus with the member of customer details:
Name, Email, Phone number and total cost. Use a constructor to assign
their values as per user choice. Derive a class as Bus booking with the
members of Bus no, date of journey, from, to and no of passengers.
Define a bookBus function to book bus ticket by providing the required
details. Display the ticket using a member function displayTicket. Compute
total cost as 500 X no of passengers. Derive another class named Hotel
booking with the members of Hotel name, city, date of check in, date of
check out and no of guests. Define a function as bookHotel to book room
by collecting details and a displayHotel function to display details of
booking. Calculate total cost as 1000 X no of days X no of guests. Provide
5% discount if no of days of stay exceeds two.

CSE201R01 – Object Oriented Programming in C++ Laboratory 16


4. Define a class named Personal_details with the attributes of Name, Age,
Gender and Phone number. Derive a class called Students with the
attributes of Reg no, Branch, Year of study and SGPA. Define a function
named findSGPA to calculate SGPA based on user input values. Derive
another class named Staff with the attributes of EmpId, Department,
Designation and Pay scale. Create a class named University which inherits
Students and Staff. Define two functions named displayStudent() and
displayStaff() to display the details of the particular type. Create object of
University, during execution ask user whether he is a student or staff, collect
the details accordingly and call the suitable display function.

Where:
Ci = Credit for the ith course
Gi = Grade Point earned in the ith course
The summation (∑) is done for all the courses in the semester.

5. Create a base class Amazon which is a online store selling items. There are
two types of accounts provided by Amazon, Customer and Seller.
Implement a program with a base class Amazon and two derived classes
as customer and seller.
Amazon class includes the data members:
 Amazon_Id(integer), Name(string), Email(string) and phone
number(integer).
 Provide a parameterized constructor to assign values for them.

Customer class includes:


 AmazonPay (float) and cart total(float).
CSE201R01 – Object Oriented Programming in C++ Laboratory 17
 Initialize them using a parameterized constructor
 Define a function named placeOrder to purchase the items in the cart. If
the cart total < Amazon pay then subtract cart total from Amazon pay and
make cart total to be 0 and show the message that “Order placed
successfully”
If the cart total > Amazon pay then subtract Amazon pay from cart total
and make Amazon pay to be 0. Show cart total value as the amount to be
paid and ask user to enter the money. If user entered value is equal to cart
total then display that “Order placed successfully” else show that
“Payment failed”.
 customerDisplay() function to display the details of the customer

Seller class includes:


 Seller type and stock value
 Initialize them using a parameterized constructor
 Define a function named supplyItems to add items into the stock.
If seller type is Prime then the maximum stock value is 500000 else it is
200000.
For Prime seller, If stock value + input value < 500000 then stock value
+= input value else show message “ Excess stock”
For normal seller, If stock value + input value < 200000 then stock value
+= input value else show message “ Excess stock”
 sellerDisplay() function to display the details of the seller

Create objects for the Customer and Seller classes in the main function by
passing values through their constructors. Then Invoke the member
functions through the objects.

CSE201R01 – Object Oriented Programming in C++ Laboratory 18


Ex No: 11 Virtual functions and friend functions

1. Create two classes as List_of_Integers and List_of_decimals. Declare an


integer array in the first class and a float array in the second class.
Implement a readNumbers() function in the both classes to get the
numbers as input from users. Define a function called sortNumbers()
which sorts arrays in both the classes. Declare this function as a friend of
both the classes. Display the sorted integers and decimals by passing the
two objects to the sortNumbers function as arguments.

2. Define a class Matrix with a 2D integer array to represent a matrix.


Overload the * operator to perform the multiplication of a scalar value with
the matrix. Overload the operator* function so that it can be called in main
function both by using Object*2 and also 2*Object. Implement one
overloading as friend function and another as a member function.

3. Create a base class Vehicle with a member variable mileage and a pure
virtual function fuelEfficiency(). Derive three classes Car, Truck, and
Bike that each override the fuelEfficiency() function. They Use a base
class pointer to call the fuelEfficiency() method for each derived object. It
must return the mileage of the vehicle per litre of petrol.

4. Create a base class Reliance with member variable named bill_amount


and a pure virtual function named bill(). Derive two classes as Petroleum
and Jewellery that override the bill function. Petroleum class has a
member variable ltr and Jewellery class has a member variable gm. Use
parameterized constructors to assign the values to the ltr and gm variables.
Override the bill function to calculate the bill amounts and show the results
under the two classes as given below based on the purchase quantity and
the type. Use a pointer of the class Reliance to invoke the bill() function of
the two derived classes.
Petroleum price Jewellery price
Petrol – Rs 101, Diesel-Rs Gold – Rs 7752, Silver – RS
92 (per litre) 104 (per gram)

5. Develop a program for the ICICI insurance company that offers both
Life insurance for people and General insurance for vehicles. Define the
hierarchy of classes as per the description provided below.

CSE201R01 – Object Oriented Programming in C++ Laboratory 19


 Provide a menu to let the user choose either life insurance policy or general
insurance policy as per their choice.
 Depending upon their choice create the object for the appropriate class
 buyPolicy() should be implemented by Life and General classes separately
by collecting required details for the respective policy types and calculate
premium using the formula given below. Apply 18% GST for all the
premiums.

*SI – Sum insured


 Note: For vehicles older than 15 years, insurance not to be given and
persons older than 80 insurance not to be issued.
 payPremium()- Premium payment term for life insurance can be chosen
by user as 1- Monthly, 2- Half yearly 3- Quarterly, 4- Annually. But for

CSE201R01 – Object Oriented Programming in C++ Laboratory 20


general insurance only single payment is available. Implement the
payPremium method in the two classes accordingly.
 Use the pointer of the ICIC Insurance class to access the Life and
General objects to invoke the virtual functions implemented by them

CSE201R01 – Object Oriented Programming in C++ Laboratory 21


Ex No: 12 File Input/output

1. Create a file called "DATA.txt" to store the set of integer elements. Read
an integer element from the user and search whether the given integer
element is present or not within the file.

2. Write a C++ program to design a student class with name, reg_no and
design a derived class called Score with ml and m2. Derive a class called
Result from student and score classes. In Result class, include a function
to display the student results along with name and reg_no. Assume a class
having 10 students. After calculating the results write the students details
(as object) into a file called "result.dat". Later retrieve from data from the
file and display it. Include necessary member functions.

3. Create a class called Cricketer with name and number of matches as


attributes. Derive a class called Batsman with total runs and appropriate
member function to compute batting_average. Derive another class
called Bowler with number of wickets, type of bowler as attributes. In
main (), create array of pointes for the Cricketer class to get the details of
2 batsmen and 2 bowlers and write into a file. Retrieve the data from the
file and display it.

4. Write a program to create a file to store numbers. Read the numbers from
the file and store the prime numbers in one file and non-prime numbers
in another file. Read and display the content of all the files. The interaction
should look like this, Enter the integers to be stored: 11 14 15 17 8 3
Content in the input file is: 11 14 15 17 8 3. Content in prime file: 11 17 3
Content in non-prime file: 14 15 8.

5. Create a file called "DATA" to store the set of integer elements. Search
whether the given element is present or not within the file. If the element is
present, then write the factors of that searching element in the
"FACTORS" file. Write a formatted IO file program to demonstrate the
above operation and display the contents of "FACTORS" file.

CSE201R01 – Object Oriented Programming in C++ Laboratory 22

You might also like