0% found this document useful (0 votes)
614 views64 pages

Updated OOPs Lab Manual 2024

Oops

Uploaded by

sonaprabu2015
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)
614 views64 pages

Updated OOPs Lab Manual 2024

Oops

Uploaded by

sonaprabu2015
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/ 64

Alliance School of Advance Computing

3CS 1005: OBJECT ORIENTED PROGRAMMING

Laboratory Manual

Prepared by: Approved By:


Dr R Rajasekar Dr Ezil Sam Leni
Professor/CSE Professor/Head
1
VISION OF THE UNIVERSITY
Alliance University’s vision is to be a world-class University that nurtures talent and catalytically
transforms the lives of millions through excellence in teaching, research, service and community
development. To uphold a commitment to shaping lives through scholarly teaching and learning,
and that which contributes to an equitable and holistic transformation of society at large.

MISSION OF THE UNIVERSITY


The mission of the University is to create and sustain a community of lifelong learners in an
environment that emphasizes literacy, critical thinking, and humanistic and scientific inquiry. The
University provides a dynamic, challenging and ethical environment for pursuing high quality
teaching, research, learning and service across all areas of university, where students, faculty and
other key constituents can interact, collaborate and partner with the global community for creation
and dissemination of knowledge and transform lives of people through innovation and excellence
in higher education.

University Strives to
• Pursue excellence in teaching, learning and scholarship.
• Prepare students for leadership through enlightened learning partnerships with faculty
mentors and the community.
• Support faculty and other scholars in pursuing world-class research: clinical, theoretical,
empirical, experiential and foster creative endeavour.
• Promote and preserve academic freedom, diversity, equality, harmony and justice.
• Develop mastery of disciplines and professions and instil confidence among its key
constituents in their application for a future of meaningful pursuits and productive work in
the service of humanity.
• Channelise faculty and student talent for professionally related service to the university,
the community and society at large.

2
Core Values
• Uncompromising Academic Integrity.
• Scholarly work and continuous self-improvement.
• Encouraging and building student ability, character and creativity.
• Pride in Self, University and the Community.
• Leadership, Service, Philanthropy, Social Justice, and Entrepreneurship.

ALLIANCE SCHOOL OF ADVANCED COMPUTING

VISION:
To be a technical institution of repute nationally and internationally in higher learning
and research and to produce creative solutions to societal needs.

MISSION:
To provide every individual with a conducive environment suitable to achieve career
goals, with a strong emphasis on personality development, and to offer resources to the
academically inclined, to gain quality education in all spheres of engineering, applied
sciences and management, without compromising the quality and code of ethics to each
student of the Institution.

3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION:
Envisions to develop world class Engineers, researchers, and entrepreneurs in the field
of Computer Science & Information Technology driven by scientific curriculum
research, and experiential learning that will enable students to solve real world
problems.

MISSION:
• To impart critical thinking, humanistic and scientific inquiry in disciplinary and
interdisciplinary competencies and skills to solve-real world challenges.
• To provide an environment of continuous learning and improvement for students,
faculty members, and other stakeholders by instilling a culture of entrepreneurial
spirit through academic and research collaborations within university and across
national and international institutions of repute.
• To create highly skilled graduates with potential, to design and develop software
systems using innovative approaches in programming and problem solving

PROGRAM DETAILS

Program Educational Objectives

PEO1: Apply critical thinking to design, develop, analyze and implement solutions
to complex problems in computer science and engineering.
PEO2: Effectively deliver technical ideas and collaborate with multidisciplinary
teams to address societal needs and contribute to the advancement of technology.
PEO3: Engage in innovative practices, entrepreneurial endeavors, or technology-
based startups, contributing to the development of new products, services, or
solutions that address societal needs and challenges.

4
PROGRAM OUTCOMES

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2. Problem analysis: Identify, formulate, research literature, and analyse complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.

PO3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues, and the consequent responsibilities relevant to the
professional engineering practice.

PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9. Individual and teamwork: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

PO10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with the society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO11. Project management and finance: Demonstrate knowledge understanding of the


engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

5
PO12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES


PSO1: Apply knowledge of mathematics, science, and engineering to solve complex engineering
problems.
PSO2: Implement secured network system using standard protocols and security principles.
PSO3: Design, implement, and evaluate a computer-based system, process, component, or
program to meet desired needs.

STUDENT OUTCOMES (EAC) [FOR ENGINEERING


PROGRAMS ONLY]

SO1: an ability to identify, formulate, and solve complex engineering problems by applying
principles of engineering, science, and mathematics.

SO2: an ability to apply engineering design to produce solutions that meet specified needs with
consideration of public health, safety, and welfare, as well as global, cultural, social,
environmental, and economic factors.

SO3: an ability to communicate effectively with a range of audiences.

SO4: an ability to recognize ethical and professional responsibilities in engineering situations and
make informed judgments, which must consider the impact of engineering solutions in global,
economic, environmental, and societal contexts.

SO5: an ability to function effectively on a team whose members together provide


leadership, create a collaborative and inclusive environment, establish goals, plan
tasks, and meet objectives

SO6: an ability to develop and conduct appropriate experimentation, analyze and


interpret data, and use engineering judgment to draw conclusions

SO7: an ability to acquire and apply new knowledge as needed, using appropriate
learning strategies

6
OBJECTIVES OF THE LAB

The objective of this lab is to understand and implement the core concepts of Object-Oriented
Programming (OOP) in C++. By the end of this lab, students should be able to:

1. Define and use classes and objects.


2. Implement inheritance to reuse and extend existing classes.
3. Use polymorphism to design flexible and reusable code.
4. Apply encapsulation to protect data and ensure data integrity.

LAB SETUP

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)

OVERVIEW OF THE LAB ACTIVITIES


1: Classes and Objects

• Objective: Learn how to define and use classes and objects.


• Description:
o Create a Book class with attributes for title, author, and price.
o Implement methods to set and get these attributes.
o Implement a method to display the book information.
• Skills Gained: Understanding of class definition, object instantiation, and member
functions.

2: Inheritance

• Objective: Understand how to reuse and extend existing classes using inheritance.
• Description:
o Create a Person class with attributes for name and age, and methods to set and get
these attributes.

7
o Create a student class that inherits from Person and adds additional attributes for
studentID and major.
o Override the displayInfo method to include student-specific information.
• Skills Gained: Implementation of inheritance, method overriding, and reusability of code.

3: Polymorphism

• Objective: Learn how to use polymorphism to design flexible and reusable code.
• Description:
o Using the Person and Student classes, demonstrate polymorphic behavior.
o Create a function printPersonInfo that takes a Person pointer and calls the
displayInfo method.
o Show how this function can be used with both Person and Student objects.
• Skills Gained: Understanding of polymorphism, virtual functions, and dynamic binding.

4: Encapsulation

• Objective: Apply encapsulation to protect data and ensure data integrity.


• Description:
o Ensure all class attributes are private.
o Provide public getter and setter methods to access and modify the attributes.
o Demonstrate the use of encapsulation in the Book, Person, and Student classes.
• Skills Gained: Implementation of encapsulation, access control, and data protection

5: Function Templates

• Objective: Learn how to define and use function templates.


• Description:
o Create a function template named findMin to find the minimum of two values.
o Test the findMin function with different data types (e.g., int, float, string).
• Skills Gained: Understanding of function templates and type independence.

8
6: Class Templates

• Objective: Understand how to define and use class templates.


• Description:
o Create a class template named Pair with attributes for two values of the same type.
o Implement methods to set and get these values.
o Implement a method to display the pair of values.
o Test the Pair class with different data types (e.g., int, float, string).
• Skills Gained: Understanding of class templates and generic programming.

7: Exception Handling

• Objective: Learn how to implement exception handling to manage runtime errors.


• Description:
o Create a function that performs division and throws an exception if the divisor is
zero.
o Implement try-catch blocks to handle the exception.
o Test the function with different inputs to ensure proper exception handling.
• Skills Gained: Understanding of exception handling and robust error management.

8: File Handling

• Objective: Understand how to use file handling to read from and write to files.
• Description:
o Create a program to write user input to a file.
o Create a program to read data from a file and display it on the console.
o Implement error checking to ensure the file operations are successful.
• Skills Gained: Understanding of file handling, stream operations, and error checking.

9
SAFETY PRECAUTIONS AND GUIDELINES
• You may use the computers in the lab only when a teacher is present.
• Please place your bags at the front of the lab.
• Keep the lab clean and neat at all times.
• Use only the computer you are assigned to.
• Report any hardware fault immediately to your teacher. Never attempt to dismantle the
different parts of the computer.
• Each student must log in to his/her account. No sharing of accounts is permitted.
• The computers are for your academic use. Playing computer games for entertainment is
strictly not allowed.
• Shut down the computer properly after use.
• Do not charge your personal mobile devices in the lab.

Syllabus
Course Title Object Oriented Programming CREDITS
Core/Elective/ L 2-0-2-
T P S C CH
Course Code 3 CS 1005 Course Category Ability 0-3-4
Enhancement 2 0 2 0 3 4

Version 1.0 Approval Details ACM LEARNING LEVEL

Co-requisite Advanced Data Structures Pre-requisite Joy of Computing

Course
Dr R Rajasekar, Professor/CSE
Coordinator
This course provides a comprehensive introduction to Object-Oriented Programming (OOP)
using C++, a powerful and widely used programming language in both academic and industry
Course
settings. The course is designed to equip students with the fundamental concepts and
Description
techniques of OOP and to develop their ability to design and implement robust, maintainable,
and efficient C++ programs.
1. Understand the basic building blocks of programming, such as variables, data types,
operators, expressions, and control flow statements.
2. Design and implement classes and objects.
Course
3. Learn how to use polymorphism to achieve dynamic binding and virtual function calls.
Objectives
4. Learn how to use arrays and strings to store and manipulate data.
5. Understand how to use templates to create generic classes and functions that can work
with different data types.

10
Bloom’s
Course
CO Statement Taxonomy
Outcome
Level
1 Understand and apply the principles of object-oriented programming. 2
2 Implement Iterative and Conditional Control Structures: 3
3 Design and implement C++ programs using classes and objects. 3
4 Understand and Apply Inheritance, Operator Overloading. 3
Utilize virtual functions for dynamic binding and friend functions for 3
5
privileged access across classes.
Course Syllabus
Module Name Contact Hours: 45

Introduction: Basic concepts of Oops, benefits of oops, application of Oops, Difference


between Procedural Oriented programming and object-oriented programming, C++ Data
Module -I types, Basic program construction: Input output statements: cin and cout, Comments, escape
sequence in C++ ,Operators: types of operators in C++ , library functions,
Structures: A Simple Structure, Defining and accessing the structure, Nested.

Control Statements and Functions: Loops: For loop – while loop & do loop, Decisions: If-
if else, switch, control statements, Array and Strings: Array Fundamentals and string
Module -II handling, Functions: Function prototyping, Passing arguments to functions, Returning values
from functions ,Reference arguments, overloaded functions ,Recursion, Inline functions,
default arguments ,scope and storage class, Returning by reference

Class and objects: A simple class, Modifiers or access specifiers, C++ objects, C++ objects
as data types, Constructor and destructor: constructor definition, types-parameterized, Object
Module -III as function arguments, Overloaded constructors, Copy constructors, returning objects from
functions, destructors, Structures and classes ,Static class data, constant classes , arrays as
class members ,arrays of objects.

11
Inheritance: Derived class and Base class, types of Inheritance - single, multiple, multilevel,
hierarchical and hybrid derived class constructors, function overriding and Aggregation.
Other Functions: Virtual Functions, Friend Functions, Static Functions, and. Operator
Module -IV Overloading: Unary Operators, Binary Operators overloading, Overloading assignment
Operators, Pointer Pointers: address and pointers, Pointers and arrays, pointers and functions,
this pointer, new and delete operator, pointers to objects, pointers to pointer

Templates: Function Templates and Class Templates Exception Handling: Introduction,


Runtime Exception hierarchy, syntax, simple example programs using try, catch, and throw,
Module -V
Streams and files: C++ Stream, stream Classes, Disk File I/O with Streams, open/close file,
Error Handling in File I/O, Command-Line Arguments.

Practical Syllabus
Experiment Name
No.
Create a Structure STUDENT with the fields name, roll_num, marks (marks in 5 different
subjects), total and average and write the functions to perform following operations:

1. Input the details of n students.


1.
2. Calculate the total and average marks for each student.

3. Sort the details of students based on roll number.


Create a structure EMPLOYEE with the field’s employee name, id, grade, basic, da, hra,
gross salary, net salary. Input the details of n employees and calculate the gross salary, net
salary and tax paid for each of them. Write the functions to perform the following operations:
1. Sort the employee details based on id.
2.
2. Display the details of all the employees of a given grade and sort based on employee id.
3. Display the details of the employee who pays Highest Tax.
4. Display the details of the employee who pays Lowest Tax.

a. Write program to implement function handling in C++ to add two numbers sign with
arguments and with return values.
3.
b) Write a C++ program to compute the area of Square, Circle, Triangle and Rectangle using
function overloading concept.

12
a. write a program in C++ to prepare a student Record using class and object.
4.
b. writes a program to Implement of constructors.
a) Write a C++ program to implement single inheritance using employee 1 as base class and
employee 2 as derived class. Calculate and display the gross salary for both the employee
class object, considering sales percentage for employee 2 class object.
5.
b) Write a C++ program to create a class called student with data members username, id and
age using inheritance. Create the class ug_students and pg_students having data members
called semester, fee_stipend, CGPA. Enter data for at least 10 students. Find the semester wise
average age for all ug and pg students.
a) Write a C++ program to demonstrate hierarchical inheritance for Employee class as base
class (name and e_id as data member) and derived classes as Manager Class (title and dues as
data member), Scientist class(pubs as data member) and Laborer class(no data member). Read
6.
and display the data for multiple derived class objects.

b) Write a C++ program to add three Distance class objects.


write a C++ program that demonstrates multiple inheritance by creating a class that inherits
7.
from two base classes.
Write a C++ program that computes the area of a triangle and rectangle using a pure virtual function in a base
8.
class.
9. write C++ program that swaps two numbers using the concept of a function template.
a) Write a C++ program that overloads the binary + operator to add two Distance class objects.
10.
b) Write a C++ program to set duration and distance class objects by passing them as parameter to friend
function
write a C++ program that handles division by zero using exception handling mechanisms
11.
(try, catch, and throw).
Write a C++ program to create a simple Bank Application that allows users to perform basic operations such
12.
as creating an account, depositing money, withdrawing money, and checking the account balance.
Self-Study topics for Advanced Learners

13
Program 1: Abstract Classes and Pure Virtual Functions

An abstract class in C++ is a class that cannot be instantiated and is designed to be inherited from. It usually
contains at least one pure virtual function.

Program 2: Interfaces using Pure Virtual Functions

In C++, interfaces can be implemented using pure virtual functions.

Program 3: Multiple Inheritance

Multiple inheritance allows a class to inherit from more than one base class.

Program 4: Templates and Generic Programming


Templates allow you to write generic programs that can work with any data type.
Textbooks
E. Balagurusamy, Object Oriented Programming with C++, eighth edition, Mc Graw Hill
1.
publication, 2021, ISBN13:978-93-89949-18-6. (Module I, II, III, IV, V)
Reference books
Bhave, Patekar, “Object Oriented Programming with C++”, 2nd Edition, Pearson
1.
Publication, 2012. ISBN:9788131770726. (Module III, IV, V)
2. Kogent, “Concepts of Programming and OOPS”, International Edition, Wiley Publication,
2011.ISBN 10: 9350042363, ISBN 13: 9789350042366. (Module I, II)
E Books
Robert Lafore, Object Oriented Programming in C++, Fourth Edition, Tech Media, reprint
1.
2012, ISBN 0-672-32308-7.
Coursera Credit Course
1. https://www.coursera.org/specializations/hands-on-cpp
Online Resources
1. https://www.coursera.org/specializations/object-oriented-programming-s12n
Case Studies
Design and implement a banking system using C++ that incorporates various OOP concepts
1. such as inheritance, polymorphism, encapsulation, and abstraction. The system should
manage different types of bank accounts and provide functionalities for account management,
transactions, and customer interactions.
Develop an online shopping cart system in C++ using OOP principles to manage products,
2. customers, and orders. The system should support adding/removing products, applying
discounts, and generating invoices.

14
CO-PO MAPPING
Cours P P P P P P P P P PO PO PO PS PS PS
e O O O O O O O O O 10 11 12 O1 O2 O3
Outco 1 2 3 4 5 6 7 8 9
mes
CO1 3 3 3 2 2 2 2 3
CO2 3 3 3 2 2 2 3 2
CO3 3 3 3 2 2 2 2 2
CO4 3 3 3 2 2 2 2 2 2
CO5 3 3 3 2 2 2 2 2 2 1

CO-SO MAPPING:
Course Student Outcomes (EAC) Student Outcomes (CAC)
Outcomes SO1 SO2 SO3 SO4 SO5 SO6 SO7 SO1 SO2 SO3 SO4 SO5
CO1 1 2
CO2 1 2 1 1 1
CO3 2 2 2 2 1 2
CO4 2 2 2 2 2
CO5 2 2 2 1 2 2

LIST OF EXPERIMENTS
Sl.No Name of Experiment/Assignment Equipment/Tool/Consumables Page
Required for conduction No.
1. Create a Structure STUDENT with the fields At least 8 GB RAM, Intel i5 or
name, roll_num, marks (marks in 5 different equivalent processor, 500 GB
subjects), total and average and write the functions HDD/SSD / Visual Studio,
Code:Blocks, CLion, Eclipse. /
to perform following operations:
GCC (GNU Compiler
Collection), Clang, Microsoft
1. Input the details of n students. Visual C++.
19-22
2. Calculate the total and average marks for
each student.

3. Sort the details of students based on roll


number.

15
2 Create a structure EMPLOYEE with the field’s
employee name, id, grade, basic, da, hra, gross
salary, net salary. Input the details of n employees
and calculate the gross salary, net salary and tax
paid for each of them. Write the functions to
perform the following operations:

1. Sort the employee details based on id.


23-26
2. Display the details of all the employees of a
given grade and sort based on employee id.

3. Display the details of the employee who pays


Highest Tax.

Display the details of the employee who pays


Lowest Tax.
3 a. Write program to implement function handling
in C++ to add two numbers sign with arguments 27-28
and with return values.

b) Write a C++ program to compute the area of


Square, Circle, Triangle and Rectangle using 29-31
function overloading concept

4 a. writes a program in C++ to prepare a student


Record using class and object. 32-34

b. writes a program to Implement of constructors 35-37


5 a) Write a C++ program to implement single
inheritance using employee 1 as base class and
employee 2 as derived class. Calculate and
display the gross salary for both the employee 38-39
class object, considering sales percentage for
employee 2 class object.

16
b) Write a C++ program to create a class called
student with data members username, id and age
using inheritance. Create the class ug_students and
pg_students having data members called semester,
40-42
fee_stipend, CGPA. Enter data for at least 10
students. Find the semester wise average age for
all ug and pg students.

6 a) Write a C++ program to demonstrate


hierarchical inheritance for Employee class as
base class (name and e_id as data member) and
derived classes as Manager Class (title and dues as
43-45
data member), Scientist class(pubs as data
member) and Laborer class(no data member).
Read and display the data for multiple derived
class objects.
b) Write a C++ program to add three Distance
class objects. 46-48

7 write a C++ program that demonstrates multiple


inheritance by creating a class that inherits from 49-50
two base classes.

8 Write a C++ program that computes the area of a


triangle and rectangle using a pure virtual function 51-52
in a base class.
9 write C++ program that swaps two numbers using
53-54
the concept of a function template.
10 a Write a C++ program that overloads the binary
+ operator to add two Distance class objects. 55-56

b) Write a C++ program to set duration and


distance class objects by passing them as 57-58
parameter to friend function.
11 write a C++ program that handles division by zero
using exception handling mechanisms (try, catch, 58-60
and throw).
12 Write a C++ program to create a simple Bank
Application that allows users to perform basic 61-64
operations such as creating an account, depositing

17
money, withdrawing money, and checking the
account balance.
Mini Project ( Team Work)

1) Design a system for a library management application using classes in C++. Include classes
for Book, Library, and Member. Each Book should have properties such as title, author,
ISBN, and availability status. The library class should manage a collection of books and
allow operations like adding a book, lending a book to a member, and returning a book.
The Member class should represent library members with properties like name, member
ID, and borrowed books. (BTL 6)

2) Create a system for managing different types of employees in an organization using


inheritance and polymorphism in C++. Define a base class Employee with common
attributes like name, ID, and salary. Derive classes Manager, Developer, and Tester from
Employee, each with specific attributes and methods. Implement polymorphism by
defining a virtual function calculate Salary() in the base class and overriding it in each
derived class to compute salaries based on specific rules (e.g., including bonuses for
managers, or overtime pay for developers). (BTL 6)

3) Design a generic stack data structure using templates in C++. Implement the stack using
an array-based approach and provide methods for pushing, popping, checking if the stack
is empty, and retrieving the top element. Test the stack implementation with different data
types (e.g., int, double, string) to demonstrate its reusability and flexibility using templates.
(BTL 6)

Suggested Complex problems for proficient Learners linked with real world
problems/Applications.
Sl.No Problem Statement Linked Page No
Experiment No.
1 Enhanced Input Handling and 4-5 25
Validation-
2 Advanced Sorting Techniques 8-9 50

18
Exp. No. 1 Title of the Experiment Date:

Create a Structure STUDENT with the fields name, roll_num, marks (marks in 5 different
subjects), total and average and write the functions to perform following operations:

1. Input the details of n students.

2. Calculate the total and average marks for each student.

3. Sort the details of students based on roll number.

Aim: The aim of this experiment is to create a structure named STUDENT with the fields name,
roll_num, marks (marks in 5 different subjects), total, and average, and to write functions that
perform the operations

Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)

Suggested Reading (Theoretical Background):


"Object-Oriented Programming in C++" by Robert Lafore: Provides a thorough introduction to
object-oriented concepts such as classes, objects, inheritance, polymorphism, and encapsulation

Algorithm:

Step 1: Define the Structure

• Structure: STUDENT
o Fields: name, roll_num, marks [5], total, average

Step 2: Function to Input Student Details

• Function: inputDetails(STUDENT students[], int n)


o For i from 0 to n-1:
▪ Read students[i].name
▪ Read students[i]. roll_num

19
▪ For j from 0 to 4:
▪ Read students[i]. marks[j]

Step 3: Function to Calculate Total and Average Marks

• Function: calculateTotalAndAverage(STUDENT students[], int n)


o For i from 0 to n-1:
▪ Initialize students[i]. total to 0
▪ For j from 0 to 4:
▪ students[i]. total += students[i]. marks[j]
▪ students[i]. average = students[i]. total / 5

Step 4 : Function to Sort Students by Roll Number

• Function: compareByRollNum(STUDENT a, STUDENT b)


o Return a.roll_num < b.roll_num
• Function: sortStudents(STUDENT students[], int n)
o Sort students using compareByRollNum

Step 5: Function to Display Student Details

• Function: displayDetails(STUDENT students[], int n)


o For i from 0 to n-1:
▪ Print students[i].name
▪ Print students[i].roll_num
▪ Print students[i].total
▪ Print students[i].average

Step 6 : Main Function

• Function: main ()
o Read n
o Declare STUDENT students[n]
o Call inputDetails(students, n)

20
o Call calculateTotalAndAverage(students, n)
o Call sortStudents(students, n)
o Call displayDetails(students, n)

Sample Output/Result
Enter the number of students: 3
Enter details for student 1:
Name: Alice
Roll Number: 102
Enter marks in 5 subjects: 85 90 78 92 88
Enter details for student 2:
Name: Bob
Roll Number: 101
Enter marks in 5 subjects: 75 80 70 82 77
Enter details for student 3:
Name: Charlie
Roll Number: 103
Enter marks in 5 subjects: 95 92 89 94 90
Student Details (sorted by roll number):
Name: Bob, Roll Number: 101, Total Marks: 384, Average Marks: 76.8
Name: Alice, Roll Number: 102, Total Marks: 433, Average Marks: 86.6
Name: Charlie, Roll Number: 103, Total Marks: 460, Average Marks: 92

21
Inferences:
creating a structure involves defining a user-defined data type that can hold both data members
(variables) and member functions (methods). Here’s an outline of the inferences or key aspects
related to creating a structure in OOP with C++

Viva Questions:
1. What is the purpose of using a structure in C++?
2. Explain the components of the STUDENT structure you have defined for this experiment.
3. How do you input the details of n students using functions in your program?
4. Can you explain the importance of sorting students based on roll numbers in a real-world
scenario?

22
Exp. No. 2 Title of the Experiment Date:

Create a structure EMPLOYEE with the field’s employee name, id, grade, basic, da, hra, gross
salary, net salary. Input the details of n employees and calculate the gross salary, net salary and
tax paid for each of them. Write the functions to perform the following operations:

1. Sort the employee details based on id.

2. Display the details of all the employees of a given grade and sort based on employee id.

3. Display the details of the employee who pays Highest Tax.

Display the details of the employee who pays Lowest Tax.

Aim: The program that manages employee records using a structured approach. The program will
define a structure EMPLOYEE with fields for employee details and salary components. Operations
will include sorting employees based on ID, displaying employees by grade with sorting, and
identifying employees with the highest and lowest tax payments.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)

Suggested Reading (Theoretical Background):


"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Structure Definition

Step 2 : Input Employee Details Function:

• Input: Array of EMPLOYEE structures, n (number of employees).


• Output: Populated EMPLOYEE structures with details

Step 3 : Calculate Gross Salary Function:

• Input: Array of EMPLOYEE structures.

23
• Output: Gross salary calculation for each employee

Step 4: Calculate Net Salary Function:

• Input: Array of EMPLOYEE structures.


• Output: Net salary calculation for each employee

Step 5 : Calculate Tax Paid Function:

• Input: Array of EMPLOYEE structures.


• Output: Tax calculation for each employee.

Step 6: Sort Employee Details by ID Function:

• Input: Array of EMPLOYEE structures, n (number of employees).


• Output: Sorted array based on employee ID.

Step 7: Display Employees of Given Grade and Sort Function:

• Input: Array of EMPLOYEE structures, n (number of employees), grade.


• Output: Display details of employees of a specific grade, sorted by employee ID.

Step 8: Find Employee with Highest Tax Function:

• Input: Array of EMPLOYEE structures, n (number of employees).


• Output: Display details of the employee who pays the highest tax.

Step 9: Find Employee with Lowest Tax Function:

• Input: Array of EMPLOYEE structures, n (number of employees).


• Output: Display details of the employee who pays the lowest tax

Step 10: Main Program Execution:

• Main Function:
o Initialize array of EMPLOYEE structures.
o Call functions sequentially to input details, calculate salaries and tax, perform
sorting, and display results based on user requirements.

Sample output / Result

Let's assume we have 3 employees with their details as follows:

1. Employee 1:
o Name: John Doe
o ID: 101

24
o Grade: A
o Basic Salary: 50000
o DA: 8000
o HRA: 6000
2. Employee 2:
o Name: Jane Smith
o ID: 102
o Grade: B
o Basic Salary: 45000
o DA: 7000
o HRA: 5000
3. Employee 3:
o Name: Michael Johnson
o ID: 103
o Grade: A
o Basic Salary: 48000
o DA: 7500
o HRA: 5500

Sorted Employee Details by ID:


Employee ID: 101, Name: John Doe, Grade: A, Gross Salary: 64000, Net Salary: 57200, Tax Paid:
6800
Employee ID: 102, Name: Jane Smith, Grade: B, Gross Salary: 57000, Net Salary: 50900, Tax
Paid: 6100
Employee ID: 103, Name: Michael Johnson, Grade: A, Gross Salary: 61000, Net Salary: 54700,
Tax Paid: 6400
Employees of Grade 'A' sorted by ID:
Employee ID: 101, Name: John Doe, Grade: A, Gross Salary: 64000, Net Salary: 57200, Tax Paid:
6800
Employee ID: 103, Name: Michael Johnson, Grade: A, Gross Salary: 61000, Net Salary: 54700,
Tax Paid: 6400

Employee with Highest Tax Paid:


Employee ID: 101, Name: John Doe, Grade: A, Gross Salary: 64000, Net Salary: 57200, Tax Paid:
6800
Employee with Lowest Tax Paid:
Employee ID: 103, Name: Michael Johnson, Grade: A, Gross Salary: 61000, Net Salary: 54700,
Tax Paid: 6400

25
Inferences:
Creating a structure for an Employee in C++ involves defining a user-defined data type that
encapsulates various attributes and behaviors related to an employee
Viva Questions:
1. Explain the significance of using a structure in C++ to represent an EMPLOYEE. How does
using a structure facilitate the organization and manipulation of employee data in this program?
2. Discuss the role of constructors and member functions in the EMPLOYEE structure.
3. Explain how the program sorts employee details based on ID. What sorting algorithm would
you use, and why?
4. What factors determine the amount of tax paid by an employee, and how does the program
ensure accuracy in tax calculation?

26
Exp. No. 3 a. Title of the Experiment Date:

Write program to implement function handling in C++ to add two numbers sign with
arguments and with return values

Aim: Write a C++ program that implements function handling to add two numbers, using function
arguments and returning the sum as a result.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm: Adding Two Numbers Using Function Handling in C++

1. Start:
2. Declare Function Prototype:
o Declare a function prototype int addNumbers(int num1, int num2); to specify the
function name (addNumbers), parameters (num1 and num2 of type int), and return
type (int).
3. Define Main Function:
o Declare integer variables num1, num2, and sum.
o Output a prompt to enter the first number (num1).
o Input num1 from the user.
o Output a prompt to enter the second number (num2).
o Input num2 from the user.
o Call the function addNumbers(num1, num2) and assign its return value to sum.
o Output the result (sum) along with a descriptive message.
4. Define Function addNumbers:
o Start the function definition int addNumbers(int num1, int num2).
o Declare an integer variable result.
o Compute the sum of num1 and num2 and store it in result.
o Return result.
5. End

Sample output / Result

27
Input
Enter first number: 25
Enter second number: 37
Output
Sum of 25 and 37 is: 62

Inferences:

The key inferences of Function definition and function Argument and Return , Encapsulation,
Function Overloading.

Viva Questions:
1. What is the purpose of using functions in C++ programming?
2. Explain the concept of function prototyping in C++. Why is it necessary?
3. How does the addNumbers function in your program work?
4. Discuss the advantages of using function return values in C++ programs.

28
Exp. No. 3 b. Title of the Experiment Date:

Write a C++ program to compute the area of Square, Circle, Triangle and Rectangle using function
overloading concept.

Aim: Write a C++ program to compute the area of geometric shapes (Square, Circle, Triangle,
and Rectangle) using function overloading concept, where each shape's area calculation is
encapsulated in a separate function with the same name but different parameter lists based on the
shape's requirements.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:

• #include <iostream> for input/output operations.


• Optionally, #include <cmath> for mathematical constants and functions (M_PI for pi if
needed).

Step 3: Function Prototypes:

• Declare function prototypes for each shape's area calculation using function overloading:
o double calculateArea(int sideLength); for Square
o double calculateArea(double radius); for Circle
o double calculateArea(int base, int height); for Triangle
o double calculateArea(int length, int width); for Rectangle

Step 4 : Main Function:

• Declare variables:
o int choice to store user's shape selection.
o Variables for dimensions (sideLength, radius, base, height, length, width) based on
shape selected.
• Display menu to choose a shape (Square, Circle, Triangle, Rectangle).

29
• Read user's choice (choice).
• Use switch statement on choice:
o Case 1: Calculate area of Square:
▪ Prompt user for sideLength.
▪ Call calculateArea(sideLength) and print the result.
o Case 2: Calculate area of Circle:
▪ Prompt user for radius.
▪ Call calculateArea(radius) and print the result.
o Case 3: Calculate area of Triangle:
▪ Prompt user for base and height.
▪ Call calculateArea(base, height) and print the result.
o Case 4: Calculate area of Rectangle:
▪ Prompt user for length and width.
▪ Call calculateArea(length, width) and print the result.
o Default: Display error message for invalid choice.

Step 5: Function Definitions:

• Define functions calculateArea for each shape:


o double calculateArea(int sideLength): Compute area of Square (sideLength *
sideLength).
o double calculateArea(double radius): Compute area of Circle (pi * radius * radius).
o double calculateArea(int base, int height): Compute area of Triangle (0.5 * base *
height).
o double calculateArea(int length, int width): Compute area of Rectangle (length *
width).

Step 6: End.

Sample output / Result


Choose a shape to calculate area:
1. Square
2. Circle
3. Triangle
4. Rectangle
Enter your choice (1-4): 1
Enter side length of the square: 5
Area of the square: 25

30
Inferences:

• In C++, function overloading allows you to define multiple functions with the same name
but with different parameter lists. This concept can be effectively used to compute the area
of different geometric shapes such as Square, Circle, Triangle, and Rectangle

Viva Questions:
1. What is function overloading in C++? How does it apply to the program you've written?
2. How does the main function interact with the calculateArea functions to compute the
area of different shapes?
3. What are the advantages of using function overloading in this program compared to
using separate functions for each shape's area calculation?
4. Can you explain a scenario where function overloading might lead to ambiguity? How
can such issues be resolved in C++?

31
Exp. No. 4 a. Title of the Experiment Date:

write a program in C++ to prepare a student Record using class and object.

Aim:

Write a program in C++ to implement a student record system using class and object concepts,
where each student's information (such as name, roll number, marks) is encapsulated within a class.
Utilize object-oriented programming principles to manage and display student records efficiently.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):

"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:

• #include <iostream> for input/output operations.


• #include <string> for using string data type.

Step 3: Class Definition:

• Define a class Student with private data members (name, rollNumber, marks, etc.) to
encapsulate student information.
• Include public member functions (methods) to set and get student details, calculate grades,
display student information, etc.
• Optionally, include constructors to initialize objects with default values or user-provided
data.

Step 4: Main Function:

• Declare objects (instances) of the Student class to represent individual students.


• Demonstrate object creation and interaction by setting student details using member
functions and displaying student records.

32
• Optionally, allow user input to dynamically add or update student information,
demonstrating the flexibility of class-based data management.

Step 5: Data Management:

• Implement methods within the Student class to manage student data securely (e.g.,
validation of input data, handling exceptions).
• Utilize access specifiers (public, private, protected) to control access to class members,
ensuring data integrity and security.

Step 6: User Interaction:

• Implement a user-friendly interface in the main function to interact with the student record
system.
• Allow users to input student details, perform operations like adding, deleting, or updating
records, and display student information in a structured format.

Step 7: End

Sample output / Result


Student 1 Details:
Name: John Doe
Roll Number: 101
Marks: 85.5

Student 2 Details:
Name: Jane Smith
Roll Number: 102
Marks: 92.0
Inferences:
Creating a student record using classes and objects in C++ involves defining a class to encapsulate
student information and using objects of that class to represent individual student records. Here
are the key inferences and steps involved in preparing a student record using class and object in
C++

33
Viva Questions:
1. How does encapsulation contribute to the design of your student record program?
2. What are classes and objects in C++? How are they utilized in the context of your
program to manage student records?
3. iscuss the role of constructors in your student record program. How are they utilized,
and why are they important?
4. Discuss any OOP concepts such as inheritance or polymorphism that are applicable or
could be extended in your student record system.

34
Exp. No. 4 b. Title of the Experiment Date:

writes a program to Implement of constructors

Aim:

Write a C++ program to implement constructors, demonstrating their role in initializing objects of
a class with default values and user-provided data. Explore the use of constructors to ensure object
initialization and prepare objects for further operations within the program.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:

• #include <iostream> for input/output operations.


• #include <string> for using string data type (if needed).

Step 3: Class Definition:

• Define a class Student with private data members (name, rollNumber, marks) to
encapsulate student information.
• Include constructors (default constructor and parameterized constructor) to initialize
objects (student1, student2, etc.) with default or user-provided data.
• Optionally, include other member functions (methods) to manipulate and display student
details.

Step 4: Constructor Implementation:

• Default Constructor (Student()):


o Initialize private data members (name = "", rollNumber = 0, marks = 0.0) to default
values.
• Parameterized Constructor (Student(string, int, float)):

35
o Set private data members (name, rollNumber, marks) with values provided as
parameters during object creation.

Sterp 5: Object Creation and Usage:

• In the main function or other relevant functions, create objects (student1, student2, etc.) of
the Student class using different constructors.
• Use object methods (display, etc.) to manipulate and display student details.

Step 6: Demonstration:

• Illustrate the usage of constructors to initialize objects (student1, student2) with default and
user-defined values.
• Display student details using object methods to verify correct initialization and operation
of the program.

Step 7: End.
Sample output / Result
Student 1 Details:
Name:
Roll Number: 0
Marks: 0
Student 2 Details:
Name: John Doe
Roll Number: 101
Marks: 85.5

36
Inferences:
Implementing constructors in a C++ program allows you to initialize objects of a class when they
are created. Constructors are special member functions that are automatically called when objects
of the class are instantiated
Viva Questions:
1. What are constructors in C++?
2. Explain the difference between a default constructor and a parameterized constructor.
3. How do constructors contribute to the principles of object-oriented programming
(OOP)?
4. Discuss scenarios where you might use different types of constructors (default,
parameterized) in a C++ program.

37
Exp. No. 5 a. Title of the Experiment Date:

Write a C++ program to implement single inheritance using employee 1 as base class and
employee 2 as derived class. Calculate and display the gross salary for both the employee class
object, considering sales percentage for employee 2 class object.

Aim:

Write a C++ program to demonstrate single inheritance using Employee1 as the base class and
Employee2 as the derived class. Calculate and display the gross salary for both Employee1 and
Employee2 class objects, considering a sales percentage for the Employee2 class object.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:

Step 1: Start

Step 2: Include necessary header files:

• #include <iostream> for input/output operations.


• #include <string> for using string data type.

Step 3: Define the base class Employee1:

• Declare protected data members empId, empName, basicSalary, and allowances.


• Implement a default constructor to initialize data members to default values (0 or "").
• Implement a parameterized constructor to initialize data members with provided values (id,
name, salary, allowance).
• Define a method calculateGrossSalary() to calculate and display the gross salary
(basicSalary + allowances).

Step 4: Define the derived class Employee2 (inherits from Employee1):

• Declare a private data member salesPercentage to store the sales bonus percentage.
• Implement a parameterized constructor to initialize data members of both base
(Employee1) and derived class (Employee2).

38
• Override the calculateGrossSalary() method inherited from Employee1 to include the sales
bonus (basicSalary + allowances + (basicSalary * salesPercentage / 100)).

Step 5: Main function:

• Inside main(), create objects of both Employee1 and Employee2 classes.


• Call appropriate methods to set employee details and sales details for Employee2.
• Display the computed gross salary for both employees using calculateGrossSalary().

Step 6: End

Sample output / Result


Employee 1 - Gross Salary: 55000
Employee 2 - Gross Salary (including 10% sales bonus): 66000

Inferences:

• implementing single inheritance in C++ involves creating a base class (parent class) and a
derived class (child class) where the derived class inherits properties and behaviours from
the base class. Here’s how you can implement this concept with Employee1 as the base
class and Employee2 as the derived class

Viva Questions:
1. What is single inheritance in C++?
2. Explain the concept of method overriding as demonstrated in your program. How does
Employee2 override the calculate Gross Salary() method inherited from Employee1?
3. How does polymorphism apply in the context of your program using single
inheritance?
4. Discuss the advantages of using inheritance in your program. How does it contribute
to code reuse and maintainability?

39
Exp. No. 5 b. Title of the Experiment Date:

Write a C++ program to create a class called student with data members username, id and age
using inheritance. Create the class ug_students and pg_students having data members called
semester, fee_stipend, CGPA. Enter data for at least 10 students. Find the semester wise average
age for all ug and pg students.

Aim:

Write a C++ program to create a class Student with data members username, id, and age, and
implement inheritance to derive classes ug_students and pg_students. ug_students and pg_students
will have additional data members semester, fee_stipend, and CGPA. Input data for at least 10
students, calculate and display the semester-wise average age for all ug_students and pg_students.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)

Suggested Reading (Theoretical Background):


"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.

Algorithm:

Step 1: Define the Base Class (Student):

• Declare a class Student with private data members username, id, and age.
• Provide public member functions:
o setData() to initialize username, id, and age.
o getAge() to retrieve the age of the student.
o displayData() to output username, id, and age.

Step 2: Define Derived Classes (ug_students and pg_students):

• Inherit publicly from the Student class.


• Extend each derived class with additional private data members:
o semester: Semester number.
o fee_stipend: Fee details or stipend amount.

40
o
CGPA: Cumulative Grade Point Average.
• Implement public member functions:
o setData() to initialize all data members including inherited ones.
o getSemester() to retrieve the semester number.
o displayData() to output all data members including inherited ones.

Step 3: Main Function:

• Declare arrays or containers for at least 10 objects of type ug_students and pg_students.
• Loop to input data for each student object:
o Prompt and read username, id, age, semester, fee_stipend, and CGPA.
o Call setData() for each student object to set the respective data members.

Step 4: Calculate Semester-wise Average Age:

• Initialize variables to accumulate total ages and count of students for each semester
(sum_age_semester, count_students_semester).
• Loop through each object in the arrays:
o Use getAge() and getSemester() to retrieve age and semester information.
o Accumulate age into sum_age_semester based on the semester of the current object.
o Increment count_students_semester for each student in the semester.
• Calculate average age for each semester (avg_age_semester = sum_age_semester /
count_students_semester).
• Output the semester-wise average ages.

Sample output / Result

Student 1:

Username: "John Doe"

ID: 101

Age: 20

Semester: 2

Fee/Stipend: 1500.0

CGPA: 8.2

Student 2:

Username: "Jane Smith"

41
ID: 102

Age: 21

Semester: 3

Fee/Stipend: 1800.0

CGPA: 7.9

Inferences:
In C++, using inheritance allows you to create a hierarchy of classes where a derived class inherits
characteristics (data members and member functions) from a base class. Let's create a scenario
where a Student class inherits from a base class Person, which includes data members username,
id, and age.

Viva Questions:
1. Explain how you implemented inheritance in your C++ program for student
management.
2. How did you ensure data encapsulation and access control in your program?
3. Describe the process of calculating semester-wise average age for both undergraduate
and postgraduate students in your program.
4. How would you modify your program to include additional functionality, such as
calculating GPA or handling more than 10 students?

42
Exp. No. 6a. Title of the Experiment Date:

Write a C++ program to demonstrate hierarchical inheritance for Employee class as base class
(name and e_id as data member) and derived classes as Manager Class (title and dues as data
member), Scientist class(pubs as data member) and Laborer class(no data member). Read and
display the data for multiple derived class objects.

Aim:

The aim of this C++ program is to demonstrate hierarchical inheritance using the Employee class
as the base class, with Manager, Scientist, and Laborer classes derived from it. The Employee class
includes name and e_id as data members. The derived classes (Manager, Scientist, Laborer) each
have their own additional data members (title and dues for Manager, pubs for Scientist, and no
additional data members for Laborer).

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):

"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:

Step 1 : Start

Step 2: Define the Employee Class:

• Declare a base class Employee with private data members name (string) and e_id (integer).
• Provide public member functions to set (setName, setEid) and get (getName, getEid) these
data members.

Step 3: Define Derived Classes:

• Manager Class:
o Inherit publicly from Employee.
o Add private data members title (string) and dues (double).

43
o Provide public member functions to set (setTitle, setDues) and get (getTitle,
getDues) these data members.
• Scientist Class:
o Inherit publicly from Employee.
o Add private data member pubs (integer).
o Provide public member functions to set (setPubs) and get (getPubs) this data
member.
• Laborer Class:
o Inherit publicly from Employee.
o No additional data members.

Step 4: Input Data for Derived Class Objects:

• Declare and initialize objects of each derived class (Manager, Scientist, Laborer).
• Use member functions to set data for each object (name, employee ID, title, dues,
publications).

Step 5: Display Data for Derived Class Objects:

• Use member functions to get and display data for each object.
• Ensure that data from both the base class (Employee) and derived classes (Manager,
Scientist, Laborer) are displayed appropriately.

Step 6: End

Sample output / Result

Manager Details:

Name: John Doe

Employee ID: 1001

Title: Project Manager

Dues: $1500.00

Scientist Details:

Name: Alice Smith

Employee ID: 1002

Publications: 5

44
Laborer Details:

Name: Bob Johnson

Employee ID: 1003

Inferences:
Hierarchical inheritance in C++ involves creating a class hierarchy where multiple derived classes
inherit from a single base class. In this scenario, we'll create a Employee class as the base class,
and then derive two classes from it: Manager and possibly another derived class like Worker
(though not explicitly mentioned)
Viva Questions:
1. Explain the concept of hierarchical inheritance in object-oriented programming using the
example of your C++ program
2. Describe the role of polymorphism in your C++ program.
3. Discuss the importance of encapsulation in the Employee base class of your program
4. Explain the process of reading and displaying data for multiple derived class objects in
your C++ program.

45
Exp. No. 6b. Title of the Experiment Date:

Write a C++ program to add three Distance class objects.

Aim:

To develop a C++ program that defines a Distance class and implements methods to input, display,
and add three Distance objects, demonstrating the addition of distances in feet and inches
accurately.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):

"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:

Step 1: Define the Distance Class:

• Create a class named Distance.


• Define private member variables feet (integer) and inches (float) to store the distance in
feet and inches respectively.

Step 2: Define Constructor and Methods:

• Implement a default constructor to initialize feet and inches to zero.


• Implement a parameterized constructor to initialize feet and inches with given values.
• Implement methods:
o inputDistance(): Accepts user input for feet and inches.
o displayDistance(): Displays the feet and inches of the object.
o addDistance(const Distance& d2): Adds the current Distance object with another
Distance object d2 and returns the sum as a new Distance object.
o addThreeDistances(const Distance& d2, const Distance& d3): Adds the distances
of the current Distance object, d2, and d3, and returns the sum as a new Distance
object.

Step 3: Main Function:

• Create three Distance objects (d1, d2, d3).

46
• Prompt the user to input distances for d1, d2, and d3.
• Use the addThreeDistances() method of d1 to compute the sum of d1, d2, and d3.
• Display the result using the displayDistance() method.

Sample output / Result


Enter first distance:
Enter feet: 5
Enter inches: 9.5

Enter second distance:


Enter feet: 3
Enter inches: 6.25

Enter third distance:


Enter feet: 2
Enter inches: 8.75

Sum of the three distances:


Feet: 11 Inches: 0.5

47
Inferences:

Adding three Distance class objects in C++ involves creating a class that represents distances and
overloading the + operator to allow addition of distances.

Viva Questions:
1. Can you explain how you designed the Distance class to handle feet and inches in your
program?
2. Describe the purpose of the addThreeDistances() method in your Distance class. How
does it work?
3. How did you ensure user input for distances is handled correctly in your program?
4. hat are the advantages of using a custom Distance class over directly using primitive
data types (like int and float) for representing distances in your program?

48
Exp. No. 7. Title of the Experiment Date:
write a C++ program that demonstrates multiple inheritance by creating a class that inherits from
two base classes

Aim:

To write a C++ program that demonstrates multiple inheritance by creating a derived class that
inherits from two base classes. The program should illustrate how multiple inheritance allows a
class to inherit properties and behaviors from more than one base class, showcasing the flexibility
and power of this object-oriented programming feature.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):

"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:

Step 1: Define Base Classes:

• Create two base classes, let's name them Base1 and Base2, each with distinct member
variables and methods.

Step 2: Implement Base Classes:

• Implement Base1 and Base2 with appropriate member variables and methods.

Step 3 : Define Derived Class with Multiple Inheritance:

• Create a derived class, Derived, that inherits publicly from both Base1 and Base2.

Step 4: Main Function:

49
• Implement the main() function where objects of the Derived class are created and their
member functions are called to demonstrate inheritance.

Sample output / Result

Data from Base1: 100

Data from Base2: 3.14

Character data from Derived: X

Inferences:
Multiple inheritance in C++ allows a derived class to inherit from more than one base class. This
feature enables a class to combine features and behaviours from multiple parent classes into a
single derived class.
Viva Questions:
1. What is multiple inheritance in C++? How does it differ from single inheritance?
2. Describe the structure of your program that demonstrates multiple inheritance with a
derived class inheriting from Base1 and Base2.
3. What are the advantages and potential pitfalls of using multiple inheritance in C++?
4. Discuss the design considerations when deciding to use multiple inheritance versus other
inheritance models

50
Exp. No. 8. Title of the Experiment Date:
Write a C++ program that computes the area of a triangle and rectangle using a pure virtual
function in a base class

Aim:

To develop a C++ program that demonstrates the use of abstract base classes and pure virtual
functions to compute the area of geometric shapes, specifically a triangle and a rectangle. The
program should illustrate inheritance, polymorphism, and abstraction by defining a base class with
a pure virtual function for area calculation, which is overridden in derived classes representing the
triangle and rectangle.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):

"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:

Step 1: Define a Shape Base Class:

• Create an abstract base class Shape with a pure virtual function virtual float calculateArea()
= 0;.
• This class will serve as the base for shapes like triangle and rectangle.

Step2: Define Derived Classes:

• Create derived classes Triangle and Rectangle that inherit publicly from the Shape base
class.
• Implement the calculateArea() function in each derived class to compute the area specific
to each shape

Step 3: Main Function:

• In the main() function, create objects of Triangle and Rectangle.


• Use polymorphism to invoke calculateArea() on these objects, which will call the
appropriate derived class method based on the object type.

51
Step 4: Display Results:

• Display the calculated area for each shape using the overridden calculateArea() function

Sample output / Result

Enter dimensions of the Triangle:

Base: 5

Height: 8

Enter dimensions of the Rectangle:

Length: 4

Breadth: 6

Area of the Triangle: 20

Area of the Rectangle: 24

Inferences:

To compute the area of shapes like a triangle and rectangle using a pure virtual function in a base
class in C++, you would typically create an abstract base class with a pure virtual function for
calculating the area.

Viva Questions:
1. What is a pure virtual function in C++? How is it declared and used in the context of
abstract base classes?
2. How does polymorphism play a role in your program that calculates the area of a triangle
and rectangle using the Shape base class and derived classes like Triangle and Rectangle?
3. Describe the process of creating a new shape (e.g., a circle) in your program. What changes
would you make to incorporate a new shape while maintaining the existing structure?
4. Explain the importance of using an abstract base class (Shape) in your program design.
How does it promote code reusability and maintainability?

52
Exp. No. 9. Title of the Experiment Date:
write C++ program that swaps two numbers using the concept of a function template.

Aim:

To develop a C++ program that demonstrates the use of function templates to swap two numbers
of any data type. This program aims to illustrate the flexibility and reusability provided by function
templates in C++, allowing the swapping of integers, floats, doubles, or any other user-defined
data type without needing separate implementations for each type.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2: Define a function template swapNumbers that takes two parameters of type T (template
parameter).

• Parameters: T& a, T& b

Step 3: Inside the function template swapNumbers:

• Declare a temporary variable of type T: T temp;


• Swap the values of a and b using the temporary variable:
o temp = a;
o a = b;
o b = temp;

Step 4: End the function template.


Step 5: In the main() function:

• Declare variables of different types (int, float, double, etc.) to demonstrate the flexibility
of the function template.
• Prompt the user to enter values for the variables.
• Call the swapNumbers function template with appropriate arguments to swap the values.
• Display the swapped values to verify the correctness of the swap operation.

53
Step 6: End

Sample output / Result

Enter two integers:

First integer: 5

Second integer: 10

Swapped integers: 10 5

Enter two floats:

First float: 3.14

Second float: 2.71828

Swapped floats: 2.71828 3.14

Enter two doubles:

First double: 123.456

Second double: 789.012

Swapped doubles: 789.012 123.456

Inferences:

Swapping two numbers using a function template in C++ allows you to write a single function that
can work with different data types (like int, double, etc.) without having to overload the function
for each type.

Viva Questions:
1. What is a function template in C++? How does it differ from a regular function or a
function with function overloading?
2. How does the function template swapNumbers handle different data types (e.g., int,
float, double) seamlessly?
3. What are the advantages of using a function template over traditional function
overloading for implementing operations like swapping two numbers?
4. Explain the process of using the function template swapNumbers in a C++ program.
Provide a step-by-step explanation of how the template is instantiated and how the
swapping operation is performed for integers and floats.

54
Exp. No. 10a. Title of the Experiment Date:

Write a C++ program that overloads the binary + operator to add two Distance class objects.

Aim:

To develop a C++ program that demonstrates operator overloading by overloading the binary +
operator in the Distance class. This program aims to enable the addition of two Distance objects
using the overloaded operator, allowing for intuitive and natural addition of distance values
represented by objects of the Distance class.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2 : Define a class Distance with private data members:

• feet of type int


• inches of type float

Step 3: Implement the following member functions in the Distance class:

• Default constructor Distance() to initialize feet to 0 and inches to 0.0.


• Parameterized constructor Distance(int ft, float in) to initialize feet and inches with given
values.
• Overload the binary + operator as a member function to add two Distance objects:
o Distance operator+(const Distance& d) const;
▪ Inside the function:
▪ Create a temporary Distance object.
▪ Calculate the sum of feet and inches for the current object (*this)
and the object d passed as parameter.
▪ Return the temporary Distance object containing the sum.

Step 4: Implement the operator+ function outside the class using the Distance class declaration:

• Distance operator+(const Distance& d1, const Distance& d2);


o Inside the function:

55
▪ Create a temporary Distance object.
▪ Calculate the sum of feet and inches for the objects d1 and d2.
▪ Return the temporary Distance object containing the sum.

Step 5: In the main() function:

• Create two Distance objects and initialize them with values.


• Use both forms of the + operator overloaded functions to add these Distance objects.
• Display the sum of distances obtained from both forms of + operator overloading.

Step 6: End

Sample output / Result

Using member function operator+:

Feet: 15 Inches: 9.75

Using friend function operator+:

Feet: 15 Inches: 9.75

Inferences:
Overloading the binary + operator in C++ allows you to define custom addition behaviour for
objects of a class. In this case, we'll overload the + operator for adding two Distance class objects.

Viva Questions:
1. What is operator overloading in C++? How does it differ from function overloading?
2. Why is operator overloading useful in object-oriented programming? Provide specific
advantages of overloading the + operator for adding Distance class objects.
3. Describe the implementation of the Distance class used to demonstrate operator
overloading for adding distances.
4. Discuss the concept of operator precedence and associativity in C++. How does
operator overloading affect these concepts?

56
Exp. No. 10b. Title of the Experiment Date:

Write a C++ program to set duration and distance class objects by passing them as parameter to
friend function

Aim:

To develop a C++ program that demonstrates the usage of friend functions by defining a function
that sets values of duration and distance class objects, which are private members of their
respective classes. This program aims to showcase how friend functions can access and modify
private data members of multiple classes to achieve encapsulation while allowing specific access
for designated functions.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2: Define a Distance class with private data members:

• feet of type int


• inches of type float

Step 3: Define a Duration class with private data members:

• hours of type int


• minutes of type int

Step 4: Implement the Distance class:

• Declare a friend function void setValues(Distance& d, Duration& dur); inside the Distance
class declaration.
• Define appropriate constructors and any necessary member functions to initialize and
display Distance objects.

Step 5: Implement the Duration class:

57
• Declare a friend function void setValues(Distance& d, Duration& dur); inside the Duration
class declaration.
• Define appropriate constructors and any necessary member functions to initialize and
display Duration objects.

Step 6: Define the friend function setValues:

• Define setValues function outside both Distance and Duration classes.


• This function takes parameters of type Distance& and Duration&.
• Access private members of both classes to set values for Distance and Duration objects.

Step 7: In the main() function:

• Create objects of Distance and Duration classes.


• Call the setValues function with these objects as parameters to set their values.
• Display the values of Distance and Duration objects to verify the setting operation.

Step 8: End

Sample output / Result


Distance: 10 feet 6.5 inches
Duration: 2 hours 30 minutes

Inferences:

In C++, friend functions provide access to private and protected members of a class when external
functions need to interact closely with the class but aren't members of it. Here’s how you can
design a C++ program using friend functions to set data members of Duration and Distance class
objects

Viva Questions:
1. What is a friend function in C++?
2. How does it differ from member functions and ordinary non-member functions?
3. Why is encapsulation important in object-oriented programming?
4. How does the use of friend functions impact encapsulation in the context of the
program that sets duration and distance objects?

58
Exp. No. 11 Title of the Experiment Date:

write a C++ program that handles division by zero using exception handling mechanisms (try,
catch, and throw).

Aim:

To develop a C++ program that demonstrates the use of exception handling mechanisms (try,
catch, and throw) to gracefully handle the scenario of division by zero. This program aims to ensure
that the application does not crash when encountering a division operation where the denominator
is zero, by catching the exception and providing appropriate error handling or recovery steps.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step1 : Start
Step 2: Include necessary header files:

• iostream for input/output operations.


• stdexcept for standard exceptions like std::logic_error.

Step 3: Define the main function int main().


Step 4: Declare variables int numerator, denominator, result.
Step 5: Prompt the user to enter values for numerator and denominator.
Step 6: Use try block to perform division operation:

• Inside try block:


o Read values of numerator and denominator.
o Check if denominator is zero (denominator == 0).
o If true, throw an exception using throw std::logic_error("Division by zero error!");.
o If false, calculate result = numerator / denominator.

Step 7: Use catch block to handle exceptions:

• Catch exceptions of type std::logic_error.


• Inside catch block:

59
o Print an error message indicating division by zero occurred.
o Provide appropriate error handling or recovery steps (e.g., re-prompting user for
valid input).

Step 8: Display the result of division if no exceptions were thrown.


Step 9: End

Sample output / Result


Enter numerator: 10
Enter denominator: 2
Result of division: 5
Enter numerator: 15
Enter denominator: 0
Exception caught: Division by zero error!
Please enter a non-zero denominator.
Inferences:

Handling division by zero in C++ using exception handling involves using try, catch, and throw
mechanisms to detect and manage runtime errors

Viva Questions:
1. What is exception handling in C++?
2. How does it differ from traditional error-handling techniques using return codes or global
flags?
3. How does the program handle the scenario of division by zero using exception handling
mechanisms?
4. What are the benefits of using exception handling (try, catch, throw) in the provided
program?

60
Exp. No. 12 Title of the Experiment Date:

Write a C++ program to create a simple Bank Application that allows users to perform basic
operations such as creating an account, depositing money, withdrawing money, and checking the
account balance.

Aim:

To develop a C++ program that simulates a basic Bank Application where users can create
accounts, deposit funds, withdraw funds, and check their account balances. This program aims to
provide a user-friendly interface for managing banking operations through structured classes and
functions, ensuring data integrity and security while demonstrating fundamental concepts of
object-oriented programming and basic financial transactions.

Requirements:

• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1 : Start
Step 2 Include necessary header files:

• iostream for input/output operations.


• iomanip for formatted output.

Step 3: Define classes:

• BankAccount: Represents each bank account with attributes such as account number,
account holder name, balance, etc.

Step 4: Declare class methods:

• createAccount(): Allows the user to create a new bank account.


• deposit(): Enables the user to deposit money into an existing account.
• withdraw(): Allows the user to withdraw money from an existing account, ensuring
sufficient balance.
• checkBalance(): Displays the current balance of an account.

61
Step 5: Implement the main function int main().
• Inside main:
• Declare variables to store user inputs and menu choices (choice, accountNumber, amount,
etc.).
• Use a loop to display a menu of options (create account, deposit, withdraw, check balance,
exit).
• Based on user choice, call appropriate methods of the BankAccount class to perform
operations.

Step 6: Ensure data validation:

• Validate user inputs (e.g., account number should be unique, withdraw amount should not
exceed balance).

Step 7 : Handle exceptions:

• Use exception handling (try, catch) to manage scenarios like insufficient balance during
withdrawal.

Step 8 : Display appropriate messages after each operation.


Step 9 : End

Sample output / Result


Bank Application Menu:
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 1
Enter Account Number: 1001
Enter Account Holder Name: John Doe
Enter Initial Balance: 5000
Account created successfully.
Bank Application Menu:
1. Create Account

62
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 2
Enter Account Number: 1001
Enter Deposit Amount: 1500
Deposit successful. Current balance: $6500.00
Bank Application Menu:
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 3
Enter Account Number: 1001
Enter Withdrawal Amount: 3000
Withdrawal successful. Current balance: $3500.00
Bank Application Menu:
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 4
Enter Account Number: 1001
Account Balance: $3500.00
Bank Application Menu:

63
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 5
Exiting Bank Application. Thank you!

Inferences:
Creating a simple Bank Application in C++ involves designing classes to represent account holders
and their bank accounts, implementing operations like deposit, withdraw, and balance checking,
and providing a user interface to interact with these functionalities.

Viva Questions:
1. Explain the concept of encapsulation in the context of the Bank Application program
you've implemented. How does the Bank Account class encapsulate data and operations
related to a bank account?
2. Describe the role of exception handling (try, catch, throw) in the Bank Application
program. How does it ensure robustness and reliability when performing operations such
as depositing or withdrawing money?
3. Discuss the advantages of using a menu-driven approach in the Bank Application program
to interact with users. How does this approach enhance user experience and simplify the
implementation of banking operations?
4. Explain the concept of data validation and its importance in the Bank Application program.
How does the program validate user inputs for operations like creating an account or
withdrawing money?

64

You might also like