Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Dr.

Naveen Kumar
Associate Professor
Amity Institue of Information Technology
Amity University, Patna

Amity Institute of Information Technology


Amity University Patna

LAB WORKBOOK
ES203 Object-Oriented Programming Using C++
Object Oriented Programming Using C++ 1
COURSE CODE: ES 203
OBJECT ORIENTED PROGRAMMING USING C++

Lab 1:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: C​​.... fundamentals- Operators, Conditions, loops and output


statement.

Pre-Lab Task:

1. Write a C++ Program to print the “Hello World” statement.


2. Write a C++ program to compute the factorial of a number (assume hardcoded user
input) in main method

In-Lab Task:

1. Develop C++ code with 2 methods in MyFirstClass a) factorial () b) isStrong()

Strong number is a special number whose sum of factorial of digits is equal to the original
number. For example 145 is a strong number. Since, 1! + 4! + 5! = 145. The method expects
an integer as an argument and returns true if the number is strong, otherwise returns false.
Object Oriented Programming Using C++ 2

2. Rework of Q1, using class/static method and modularizing to a class level and
package/namespace level:

Post-Lab Task:

1. Modify MyIntegerMath class, such that it contains the following methods 1) countDigits()
2) isArmstrong().

countDigits() expects an integer as argument and returns the number of digits in it. isArmstrong()
expects an integer as argument and returns true if it is an Armstrong number otherwise returns false.
A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... Draw the class diagrams:
Object Oriented Programming Using C++ 3
a) modularized to class level

b) modularized to package level

2. Develop C++ code for the above designs:

a) modularized to class level

b) modularized to package level


Object Oriented Programming Using C++ 4
Lab 2:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Syntax to define class, Need for class as a template, Command line arguments
and console input

Pre-Lab Task:

1. Design a class named Stock that contains:


a. A string data field named symbol for the stock’s symbol.
b. A string data field named name for the stock’s name.
c. A double data field named previousClosingPrice that stores the stock price for the
previous day.
d. A double data field named currentPrice that stores the stock price for the current
time.
e. A method named getChangePercent() that returns the percentage changed from
previousClosingPrice to currentPrice.
Use appropriate access specifiers for instance variables and instance methods. Draw
the class diagram.
(Hint: Modularize to package level)
2. Write menu-driven main () method in Demo class to perform
a) Linear Search
b) Binary Search
c) Bubble Sort

The program must read a set of integers through command line arguments and use console
to read the key.

In-Lab Task:

1. Design a class named QuadraticEquation for a quadratic equation ax2 + bx + c = 0. The


class contains:
a. Private data fields a, b, and c that represent three coefficients.
b. Three getter methods for a, b, and c.
c. A method named getDiscriminant() that returns the discriminant, which is b2 - 4ac.
d. The methods named getRoot1() and getRoot2() for returning two roots of the
equation.

2
−𝑏± 𝑏 −4𝑎𝑐
𝑟1 𝑎𝑛𝑑 𝑟2 = 2𝑎
Object Oriented Programming Using C++ 5

2. Define a class Student with the following attributes under private access and methods under
public access.

a) Name b) ID c) gender d) department

a. Define setter methods such that name but not have any special characters and Digits.
b. ID must be a positive 9-digit value
c. Gender must be either M/F
d. Department must be either BCA/BBA/CE/CSE/ECE/EEE/ECS/ME/PE/MCA
e. Define toString() method that returns a string of the following format given below.
f. In the main method define two Student objects and prints the details of the students
in the following format.

ID: 220030000
Name: ABC
Gender: M
Department: CSE

(Hint: Read the data from console)

Post-Lab Task:

1. Write a program that randomly generates an array of 100,000 integers and a key. Estimate
the execution time of invoking the linearSearch() method in best, average and worst cases.

You can use the following code template to obtain the execution time:

a. long startTime = System.currentTimeMillis();


b. perform the task;
c. long endTime = System.currentTimeMillis();
d. long executionTime = endTime - startTime;

2. Develop a C++ program that reads the number of rows and columns through command-line,
reads the set of elements in a 2D array from console. The menu driven program must
perform the following operations:

a. Sum of all elements


b. Print the data in matrix form
c. Print the elements of principal diagonal
d. Print the sum of elements in Principal diagonal
Object Oriented Programming Using C++ 6
Lab 4:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Constructors and Overloading, Chaining and this

Pre-Lab Task:

1. Design a class named MyInteger. The class contains:


a. An int data field named value that stores the int value represented by this object.
b. A constructor that creates a MyInteger object for the specified int value.
c. A getter method that returns the int value.
d. The methodsisEven(),isOdd(),andisPrime() that return true if the value in this object
is even, odd, or prime, respectively.
e. The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the
specified value is even, odd, or prime, respectively.
f. The static methods isEven(MyInteger), isOdd(MyInteger), and isPrime(MyInteger)
that return true if the specified value is even, odd, or prime, respectively.
g. The methods equals(int) and equals(MyInteger) that return true if the value in this
object is equal to the specified value.
h. A static method parseInt(char[]) that converts an array of numeric characters to an
int value.
i. A static method parseInt(String) that converts a string into an int value.

Draw the class diagram for the class and then implement the class. Write a client program that tests
all methods in the class.

2. Enhance the above my adding a method factorial () which expects an integer argument and
returns the factorial value as BigInteger Wrapper class.

In-Lab Task:

1. Design a class named Account that contains:


● A private int data field named id for the account (default 0).
● A private double data field named balance for the account (default 0).
● A private double data field named annualInterestRate that stores the current interest rate
(default 0). Assume all accounts have the same interest rate.
● A no-arg constructor that creates a default account.
● A constructor that creates an account with the specified id and initial balance.
● The accessor and mutator methods for id, balance, and annualInterestRate.
● Mutators return Boolean (If all the fields must be +ve, return true, else false)
● A method named withdraw that withdraws a specified amount from the account.
● A method named deposit that deposits a specified amount to the account.

Draw the UML diagram for the class and then implement the class.
Object Oriented Programming Using C++ 7
(Hint: The method getMonthlyInterest() is to return monthly interest, not the interest rate
Monthly interest is balance * monthlyInterestRate.
monthlyInterestRate is annualInterestRate / 12.)

Note that annualInterestRate is a percentage,e.g., like 4.5%. You need to divide it by 100.) Write a
test program that creates an Account object with an account ID of 1122, a balance of $20,000, and
an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit
method to deposit $3,000, and print the balance, the monthly interest.

2. Design a class named MyPoint to represent a point with x- and y-coordinates. The class
contains

The data fields x and y that represent the coordinates with getter methods.

● A no-arg constructor that creates a point (0, 0).


● A constructor that constructs a point with specified coordinates.
● A method named distance that returns the distance from this point to a specified point of the
MyPoint type.
● A method named distance that returns the distance from this point to another point with
specified x- and y-coordinates.

Draw the UML diagram for the class and then implement the class. Write a test program that creates
the two points (0, 0) and (10, 30.5) and displays the distance between them.

Post-Lab Task:

1. Design Use the Account class that simulates an ATM machine. Create ten accounts in an
array with id 1, . . . , 10, and initial balance $100. The system prompts the user to enter an
id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is accepted,
the main menu is displayed as shown in the sample run. You can enter a choice 1 for
viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for
exiting the main menu. Once you exit, the system will prompt for an id again. Thus, once
the system starts, it will stop when id is 0.

2. Implement the following


Object Oriented Programming Using C++ 8
In the no-args constructor, size must be initialized to 10 and initialize the array with the
same.
Object Oriented Programming Using C++ 9
Lab 5:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Objects as data members, Menu driven programs to perform operations on


array of objects

Pre-Lab Task:
1. Design a class named StopWatch. The class contains:
● Private data fields startTime and endTime with getter methods.
● A no-arg constructor that initializes startTime with the current time.
● A method named start() that sets the startTime to the current time.
● A method named stop() that sets the endTime to the current time.
● A method named getElapsedTime() that returns the elapsed time for the stopwatch in
milliseconds.
Draw the UML diagram for the class and then implement the class.

2. A Restaurant serves dishes of three types: Veg, Non-Veg and Egg represented by green, red
and brown color codes respectively. Help them out by writing a menu driven program to
display the various dishes depending on the type of food the customer opts for.

In-Lab Task:
1. A customer of a bank wants to withdraw/deposit money from his account. There are 3
ATMs in his town. Help him out by writing a program such that his balance will be updated
after a transaction in any of the ATMs. (Use ‘Account’ as Singleton Class and it should be
Early Instantiated)
2. A company wants to digitalize their manual records of the employee details (Employee ID,
Employee name, Employee Department). If all the three fields are given, use the given
details. If not, use the default values.
(Use Constructor Overloading)

Default values are:


ID: 0
Name: #
Department: #
Write toString () method, mutators and accessors.
Write a menu driven main () method to perform the following operations:

a. Create new Employee record


b. Update name based on ID
c. Print All Employees
d. Print Department Specific employees
Object Oriented Programming Using C++ 10
Post-Lab Task:
1. Use the student class define in Lab 2 and enhance the main method such that we can store
data of 10 students in an array and perform the following operations as a menu driven
program.
a. Create a new student
b. Print details of all students
c. Print details based on ID
d. Modify student name based on ID
e. Remove a student based on ID
2. Enhance the design of In-lab Q2, such that the date of joining is one attribute of Employee
and print the details of all employees who joined in 2019.
Object Oriented Programming Using C++ 11
Lab 6: Strings

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: String, StringBuffer, StringTokenizer and Date

Pre-Lab Task:

1. Write a menu driven program to illustrate the following operations on String Class

a) charAt()
b) length()
c) indexOf() -all overloaded methods
d) lastIndexOf() -all overloaded methods
e) substring() - all overloaded methods
f) valueOf() - all overloaded methods
2. Write a menu driven program to illustrate the following operations on StringBuffer Class
a. charAt()
b. append()
c. capacity()
d. length()
e. delete()
f. deleteCharAt()
g. insert()
h. reverse()
i. replace()

In-Lab Task:

1. Write a program that sets up a String variable containing a paragraph of text of your choice
from file. Extract the words from the text and sort them into alphabetical order. Display the
sorted list of words. You could use a simple sorting method called the bubble sort.
2. Define an array of ten String elements each containing an arbitrary string of the form
“month/day/year”; for example,”10/29/99” or “12/5/01”. Analyze each element in the
array and output the date represented in the form 29th October 1999.

Post-Lab Task:

1. Write a program that will reverse the sequence of letters in each word of your chosen
paragraph from Exercise 3. For instance, “To be or not to be.” would become “oT eb ro ton
ot eb.”
Object Oriented Programming Using C++ 12
Lab 07:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Inheritance, method overloading

Pre-Lab Task:

1. Develop a program that creates a generic Shape class with attributes fillColor, borderColor,
fill (Boolean type) and border width. The classes Rectangle, Circle must inherit Shape.
Rectangle has length and width as attributes and circle with radius as attribute. Also add
the corresponding getters and setters, toString() in each of the classes. Use appropriate
access specifiers. In the main () method of Demo class, create objects and access the
methods. Draw the class diagram.
2. Enhance the Pre-lab Q1 hierarchy such that Shape is the general class, inherited by
TwoDShape and ThreeDShape class, and Rectangle, Circle inherits the TwoDShape, Cuboid
and Sphere extend the ThreeDshape.

In-Lab Task:

1. Design a class named Triangle that extends GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default values 1.0 to denote
three sides of the triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and side3.
■ The accessor methods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this triangle.
■ A method named toString() that returns a string description for the triangle.
The toString() method is implemented as follows:
return "Triangle: side1 = " + side1 + " side2 = " + side2 +
" side3 = " + side3;
Draw the UML diagrams for the classes Triangle and GeometricObject and implement the
classes. Write a test program that prompts the user to enter three sides of the triangle, a
color, and a Boolean value to indicate whether the triangle is filled. The program should
create a Triangle object with these sides and set the color and filled properties using the
input. The program should display the area, perimeter, color, and true or false to indicate
whether it is filled or not.
2. Design a class named Person and its two subclasses named Student and Employee. Make
Faculty and Staff subclasses of Employee. A person has a name, address, phone number,
and email address. A student has a class status (freshman, sophomore, junior, or senior).
Define the status as a constant. An employee has an office, salary, and date hired. A faculty
member has office hours and a rank. A staff member has a title. Override the toString
method in each class to display the class name and the person’s name. Draw the UML
diagram for the classes and implement them. Write a test program that creates a Person,
Student, Employee, Faculty, and Staff, and invokes their toString() methods.
Object Oriented Programming Using C++ 13
Post-Lab Task:

1. The Account class was defined to model a bank account. An account has the properties
account number, balance, annual interest rate, and date created, and methods to deposit
and withdraw funds. Create two subclasses for checking and saving accounts. A checking
account has an overdraft limit, but a savings account cannot be overdrawn. Draw the UML
diagram for the classes and then implement them. Write a test program that creates
objects of Account, SavingsAccount, and CheckingAccount and invokes their toString()
methods.
Object Oriented Programming Using C++ 14
Lab 08:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Inheritance, abstract classes

Pre-Lab Task:
1. A customer walks into a KFC outlet and sees that he has two options: veg and non- veg. He
observes that plain veg burger costs 80/- and plain non-veg burger costs 120/- each. But he
wishes to have extra mayonnaise and either of extra veggies/chicken on each of his
burgers. Help the outlet by writing a program which’ll help them calculate the cost of the
basic burger and include the cost of the condiments if he chooses to add any. (Use
Inheritance and Null Object Design Pattern)

Item Cost

Mayonnaise 30/-

Veggies 45/-

Chicken 60/-

In -Lab Task:

1. Your local library needs your help related to library management and wants you to develop
a program that will help them to calculate the fine. Remember that the name and the
number of days the borrower had the book with them should be protected and display the
information using inheritance concept. After 15 days fine will be charged as 2 rupees per
day until the day of submission, if there is no charge simply print “NO FINE” else print the
fine.
2. Abilash has given his credit card to his three sons for their monthly expenses. After the turn
of the month, he gets a bill of 1,00,000/- Rahul tells him that he had used 15,000/- in that
month. SriRam and Kartheek tell him that they’ve used 35,000/- and 50,000/- respectively.
Help Abilash to find out percentage of amount each of his sons used in that month.
Consider creditBill as abstract class containing a return method and an abstract method.
Use Dynamic Polymorphism.
Object Oriented Programming Using C++ 15

Post-Lab Task:

1. Karteek is the head of the village panchayat and decides to collect the data related to the
population, total income and the average income of the village and stores it in a class which
is in a package village. Help him out to create another package and access the village
information. (Use Protected access specifier)
2. Rahul owns a company and ran it for a period of 7 years with a profit of 80cr per annum. He
falls sick and his son Rohan inherits the ownership of the company and runs it for a period
of 6 years with a profit margin of 120cr per annum. Complete the given code. (Use the
keyword ‘Super’)

class Rahul
{
Rahul (int yearsWorked, int profitPerAnnum)
{ //Fill the code

}
}

class Rohan extends Rahul

Rohan (int yearsWorked, int profitPerAnnum) //Fill the code


{

}
}
Object Oriented Programming Using C++ 16

OUTPUT FORMAT:

Rahul worked for 7 years and earned profit 80 crores


Total Profit earned by Rahul is: 560
After Rahul's ill health his son Rohan, took over to develop his father’s company Rohan worked for
6 years and earned profit 120 crores
Total Profit earned by Rohan is: 720
Object Oriented Programming Using C++ 17
Lab 09:
Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Abstract classes and Interfaces

Pre-Lab Task:

1. Mobile phone evolution initially happened in 4 phases. It started with phones having only
call feature, then it extended to phones to having messaging also. In the next generation
phones also had camera and in the final generation of that revolution they started having
internet also. Write a program to print all the features present in a 4th generation phone.
(Use inheritance)

In-Lab Task:

1. Define an abstract base class Shape that includes protected data members for the (x, y)
position of a shape, a public method to move a shape, and a public abstract method show()
to output a shape. Derive subclasses for lines, circles, and rectangles. Also, define the class
PolyLine with Shape as its base class. You can represent a line as two points, a circle as a
center and a radius, and a rectangle as two points on diagonally opposite corners.
Implement the toString() method for each class. Test the classes by selecting ten random
objects of the derived classes, and then invoking the show() method for each.

a. Use the toString() methods in the derived classes a menu driven program to
illustrate the a few operations on String Class
2. Implement the following for a Bank ABC
Object Oriented Programming Using C++ 18

3. Mark owns a Xerox shop. He uses a Smart Printer which can Print, Fax and Scan to render
his services to the customers. As the business is booming, he bought and installed an
Economic Printer which can only print. Implement interfaces for both printers using
Interface Segregation Principle.

Post-Lab Task:

1. You are a journalist and are required to submit a report on the number of accidents that
had occurred in your area. Collect the information of accidents caused by car, bus and bike
from your local NGO’s and write a program that will print the number of accidents of each
type that had occurred. (Use Interface and it contains a method numberOfAccidents, also
use Adapter Design Pattern.)
Object Oriented Programming Using C++ 19
Lab 10:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Exception Handling

Pre-Lab Task:

1. An old man wants to distribute sweets to children near his home. He was confused of how
many sweets he must give to each child. Help the old man by writing a program where the
number of sweets and number of children are initialized using parameterized constructor.
Observe what happens when there are zero number of children and handle the exception if
any.
2. Write C++ program to read 10 values into an array and prints the value in 11th index .

In-Lab Task:

1. Election committee wants to check whether the voter is eligible to vote or not. The person
can vote if his age is greater than 18. Help the Election committee by developing a code
which arises exception if the voter age is less than 18 then print the exception and “VOTER
IS NOT ELIGIBLE TO VOTE”, otherwise print “VOTER IS ELIGIBLE TO VOTE”. (Hint: Develop
user-defined Exception)
2. Enhance the Lab-5 In-Lab Task Q2, such that when Invalid ID (-ve number) is given it must
throw InvalidIDException, and InvalidNameException when name has special characters or
digits.

Post-Lab Task:

1. Enhance Q2, to read data from file. The program must close the file even when an
exception arises or not. (Hint: Use finally block)
Object Oriented Programming Using C++ 20
Lab 11

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Multithreading

Pre-Lab Task:

1. You are given a task of printing the first five natural numbers assigned to all three different
threads which should be created by implementing runnable interface. Run this program for
three times and check the printing style each time.
2. Perform the Pre-Lab Q1 task by extending the Thread class.

In-Lab Task:

1. Rohan was asked by his teacher to develop a program which takes in a dynamic user input
and prints all the prime numbers till that number and then prints all the composite
numbers till that number. Help him out by developing the program to do so. Use one
thread each for both prime and composite numbers
2. Tony was asked to develop a program which takes in five alphabets as dynamic user input
and stores them in an array. He passes the array to two threads. First one should traverse
the array, and the vowels present in it should be printed and the second thread should
print the consonants present in the array. Help him out by writing the program.

Post-Lab Task:

1. You are asked to take two integer values as dynamic user inputs. The values are then
passed to two threads where their respective multiplication table’s logic (up to 10) should
be written in a synchronized block and print them.
Object Oriented Programming Using C++ 21
Lab 12

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Collection Framework – List, Set and Map

Pre-Lab Task:

1. Develop a C++ program to store 10 integer values in an arraylist. Calculate the sum, insert
10 more values and compute the sum.
2. Develop a C++ program to store 10 integer values in a Hashset and print them. Analyze the
output in case of duplicate inputs.
3. Create a HashMap with 10 elements where each element has (key:int, value: String) and
apply the following operations.
a. Search for an element of a given key. If exists in the HashMap, print the key – value
pair, otherwise, print “Search key not found”.
b. Remove an element from the HashMap for a given key.

In-Lab Task:

1. Develop a C++ program to store the details of students in an ArrayList. Use the student
class as defined in In-Lab 2 Exercise.
2. You are the class representative and are required to store the Student Details and ID
numbers of all your classmates. Develop a program which takes in the details of the
students as dynamic user input and store them in Hashmap. It should print the details and
it should also be able to help you search for a Student details using the ID number.

Post-Lab Task:
1. Develop a program to read the country names (separated by space) from a file and store in an
ArrayList and then perform the following menu driven operations.
a. Search for a country name
b. Sort based on country name

You might also like