0% found this document useful (0 votes)
10 views41 pages

NEW - OOPS - Using C++Lab Manual - 3rd - NamitaGoyal

The document is a lab manual for Object-Oriented Programming using C++ at Maharaja Agrasen Institute of Technology, detailing the institute's vision, mission, program outcomes, and educational objectives. It outlines the course structure, including hardware and software requirements, practical exercises, evaluation criteria, and record-keeping formats for students. The manual emphasizes hands-on coding, debugging, and collaboration to enhance students' programming skills and understanding of C++.

Uploaded by

Ujjwal Bansal
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)
10 views41 pages

NEW - OOPS - Using C++Lab Manual - 3rd - NamitaGoyal

The document is a lab manual for Object-Oriented Programming using C++ at Maharaja Agrasen Institute of Technology, detailing the institute's vision, mission, program outcomes, and educational objectives. It outlines the course structure, including hardware and software requirements, practical exercises, evaluation criteria, and record-keeping formats for students. The manual emphasizes hands-on coding, debugging, and collaboration to enhance students' programming skills and understanding of C++.

Uploaded by

Ujjwal Bansal
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/ 41

LAB MANUAL

OF
OBJECT ORIENTED
PROGRAMMING USING C++

(CIC-257)

Department of Information Technology


Maharaja Agrasen Institute of Technology, PSP area,
Sector-22, Rohini, New Delhi -110085
(Guru Gobind Singh Indraprastha University, New Delhi)
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

VISION OF THE INSTITUTE

To attain global excellence through education, innovation, research, and work ethics with the
commitment to serve humanity.

MISSION OF THE INSTITUTE

M1. To promote diversification by adopting advancement in science, technology, man-


agement, and allied discipline through continuous learning
M2. To foster moral values in students and equip them for developing sustainable solu-
tions to serve both national and global needs in society and industry.
M3. To digitize educational resources and process for enhanced teaching and effective
learning.
M4. To cultivate an environment supporting incubation, product development, technology
transfer, capacity building and entrepreneurship.
M5. To encourage faculty-student networking with alumni, industry, institutions, and
other stakeholders for collective engagement.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

VISION OF THE DEPARTMENT

To establish a center of excellence promoting Information Technology related education and


research for preparing technocrats and entrepreneurs with ethical values.

MISSION OF THE DEPARTMENT

M1. To excel in the field by imparting quality education and skills for software devel-
opment and applications.
M2. To establish a conducive environment that promotes intellectual growth and re-
search.
M3. To facilitate students to acquire entrepreneurial skills for innovation and product
development.
M4. To encourage students to participate in competitive events and industry interaction
with a focus on continuous learning.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

PROGRAM OUTCOMES (POs)

PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engi-


neering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first prin-
ciples 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 cul-
tural, 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 modeling to com-
plex 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 con-
sequent responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional en-
gineering 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 responsi-
bilities and norms of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a mem-
ber or leader in diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities
with the engineering community and with 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 and 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.
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 techno-
logical change.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO1 The graduates would utilize their professional skills in Information Technology to
address real-world and societal challenges.
PEO2 The graduates would become successful entrepreneurs and motivators.
PEO3 The graduates would pursue research globally and engage in producing novel prod-
ucts to serve humanity.
PEO4 The graduates would exhibit collaborative abilities with adherence to professional
ethics.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1 Students are equipped with programming technologies applied in the indus-
try.
PSO2 Students are able to provide efficient solutions for emerging challenges in
the computation domain such as Artificial Intelligence, Data Science, Web
Technologies.
PSO3 Students are able to apply domain knowledge and expertise in the field of
Information Technology for enhancing research capability to transform in-
novative ideas into reality.
CO OF THE LAB SUBJECT AND ITS MAPPING
WITH PO AND PSO
TABLE OF CONTENTS

1. Introduction of Lab Subject. (TIMES NEW ROMAN 16)


2. Hardware & Software Requirement.
3. List of Practicals (As Per syllabus prescribed by G.G.S.I.P.U)
4. List of Practicals (Beyond the syllabus Prescribed by
G.G.S.I.P.U)
5. Format of the lab record to be prepared by the students.
6. Marking scheme for the practical exam.
7. For each Practical (Steps to be followed & Viva Question).
RUBRICS EVALUATION
0 1 2 3
Rubrics/ Marks Needs Im-
Missing Inadequate Adequate
provement
There are minor The problem to
Is able to identify Problem is vaguely omissions or besolved is
the problem to be No mention is identified and ob- vague details. clearly stated.
R1 solved and define made of the prob- jectives are not Objectives are Objectives are
the objective of lem to besolved. relevant or erro- conceptually complete, spe-
the experiment. neous. correct and cific, concise, and
measurable but measurable.
incomplete.
The experiment The experiment
The experiment The experiment is attempts to solve solves the prob-
Is able to design a does not solve designed to solve the problem but lemand has ge-
reliable experi- theproblem. the problem but needs improve- neric logic applica-
R2 ment that solves contains missing ment to correctly ble togeneric
the problem. Solution is not im- links. Solution is arrive atit. Solu- data.
plemented at all. attempted but im- tion is partially Solution is fully
plementation isnot implemented.
implemented.
correct.

Diagrams Diagrams and/or


Is able to com- Diagrams are and/orexperi- experimental pro-
Diagrams are
municate thede- missing and/or mental proce- cedures are clear
present but do
R3 tails of an experi- experimental dures are pre- and complete.
notproperly de-
mental procedure procedure is sent but with
scribethe proce-
clearlyand com- missing or ex- errors that may
dure.
pletely. tremely vague. result in invalid
conclusion.
All-important All important data
Is able to record dataare present, are present, orga-
Data are either Some important
R4 and represent but recorded in nized and rec-
absent or incom- dataare absent or
data in a mean- an incomprehen- orded clearly.
prehensible. incomprehensible.
ingful way. sible
way.
An acceptable An acceptable
Is able to make a No discussion is A judgment is made judgment is judgment is
R5 judgment about presented about about the results, madeabout the madeabout the
the results of the theresults of the butis not reasonable result, but the result, with valid
experiment. experiment. or coherent. reasoning conclusions.
is flawed orin-
complete.
INTRODUCTION TO LAB

The Object-Oriented Programming using C++ course is designed to provide students with a
solid foundation in object-oriented programming principles and the C++ programming lan-
guage. Throughout the course, students will learn how to design, implement, and manipulate
objects to solve complex problems. The course will cover key concepts such as classes, objects,
inheritance, polymorphism, encapsulation, and abstraction. Following is a comprehensive plan
for your Object-Oriented Programming using C++ course which describes how each compo-
nent contributes to the overall learning experience:
1. Lab Setup: The lab should provide a computer environment equipped with the necessary
software tools and compilers for C++ programming. This includes an integrated development
environment (IDE) or a text editor, a C++ compiler, and debugging tools.
2. Programming Exercises: The lab sessions typically involve a series of programming exer-
cises that cover various aspects of C++ programming. These exercises may focus on topics like
basic syntax, control structures, functions, arrays, classes, inheritance, polymorphism, data
structures, algorithms, file handling, and more.
3. Hands-on Coding: In the lab, students are encouraged to actively write code to solve pro-
gramming problems and complete the given exercises. They can experiment with different pro-
gramming techniques, implement algorithms, and practice coding best practices.
4. Debugging and Error Handling: Debugging is an essential part of programming, and the lab
provides an environment for students to practice debugging techniques. Students learn to iden-
tify and fix errors in their programs, use debugging tools to trace program execution, and handle
exceptions that may occur during program execution.
5. Experiments beyond syllabus/Practice programmes: Lab courses often include few experi-
ments that are not in GGSIPU list and practice program related to concepts given in syllabus,
requires students to work on more extensive programming tasks. This practice may involve
developing software applications, implementing algorithms, solving coding problems, or work-
ing on group projects to encourage teamwork and collaboration.
6. Code Review and Feedback: Lab instructors or teaching assistants provide guidance, review
students' code, and offer feedback on their programming solutions. This helps students improve
their coding style, understand best practices, and learn from their mistakes.
HARDWARE & SOFTWARE REQUIREMENT

CPU : Intel Core i5


8 GB RAM
1 TB HDD
Key board
Mouse
TFT

Printer : LaserJet Printer


Software : Code Block
LIST OF PRACTICALS (AS PER SYLLABUS
PRESCRIBED BY G.G.S.I.P.U)
LIST OF PRACTICALS (BEYOND THE LIST
PRESCRIBED BY G.G.S.I.P.U)

1.Write a program to illustrate how template function can be over-


loaded.
2. Write a program that simulates a simple banking system with multi-
ple account types, transactions, and error handling.
3. Write a program that models a simplified library management sys-
tem using object-oriented programming principles.
FORMAT OF THE LAB RECORDS TO BE PRE-
PARED BY THE STUDENTS

The students are required to maintain the lab records as per the in-
struction:
1. All the record files should have a cover page as per the for-
mat.
2. All the record files should have an index as per the format.
3. All the record should have the following:
I. Date
II. Aim
III. Algorithm or The Procedure to be followed
IV. Program
V. Output
VI. Viva Questions
MARKING SCHEME
FOR THE
PRACTICAL EXAMINATION

There will be two practical exams in each semester.


1. Internal Practical Exam
2. External Practical Exam

INTERNAL PRACTICAL EXAMINATION


It is taken by the concerned lecture of the batch.
MARKING SCHEME FOR INTERNAL EXAM IS:
Total Marks: 40
Division of 40 Marks is as follows
1. Regularity: : 05
2. File : 15
3. Quiz : 10
5. Viva Voce: : 10
EXTERNAL PRACTICAL EXAMINATION
It is taken by the concerned lecturer of the batch and by an external
examiner. In this exam student needs to perform the experiment allotted
at the time of the examination, a sheet will be given to the student in
which some details asked by the examiner needs to be written and at
the last viva will be taken by external examiner.

MARKING SCHEME FOR THIS EXAM IS:


Total Marks : 60

Division of 60 marks is as follows


1. Sheet filled by the student : 15
2. Viva Voce : 20
3. Experiment performance : 15
4. File submitted : 10
NOTE:
● Internal marks + External marks = Total marks given to the stu-
dents
▪ (40 marks) (60 marks) (100 marks)
ANNEXURE I
COVER PAGE OF THE LAB RECORD TO BE
PREPARED BY THE STUDENTS
OBJECT ORIENTED PROGRAMMING USING
C++
CIC-257
(Size 20”, italics bold, Times New Roman)

Faculty Name:
(16”, Times New Roman) Student Name:
Roll No.:
Semester:
Batch:
(16”, Times New Roman)

Department Of Information Technology


Maharaja Agrasen Institute Of Technology, PSP area,
Sector-22, Rohini, New Delhi -110085
(18” bold Times New Roman)
ANNEXURE II
FORMAT OF THE INDEX TO BE PREPARED BY
THE STUDENTS
Student’s Name:
Roll No.:
1. Index for the Lab File is as follows:

OBJECT ORIENTED PROGRAMMING USING C++


PRACTICAL RECORD
PAPER CODE : CIC-257
Name of the student :
University Roll No. :
Branch :
Section/ Group :
PRACTICAL DETAILS
a) Experiments according to the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks
(15)
R1 R2 R3 R4 R5

1.

2.

3.

4.

5.
b) Experiments beyond the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks
(15)

R1 R2 R3 R4 R5
1.

2.

3.

4.

5.
EXPERIMENT – 1

AIM:
Write a program for multiplication of two matrices using OOP.

THEORY:
Matrix is a rectangular array of m × n numbers (real or complex) in the form of m horizontal
lines (called rows) and n vertical lines (called columns) is called a matrix of order m by n,
written as m × n matrix.
Create a matrix class that represents a matrix with basic operations such as setting values,
getting values, displaying the matrix and matrix multiply function performs matrix multipli-
cation. In addition to simple illustration, in a real-world scenario, you can to add more error
handling, optimize the matrix multiplication algorithm, and perhaps implement additional
matrix operations.

ALGORITHM:
Step 1: If the original matrices are of size n1 x n2 and m1 x m2, create a resultant matrix of
size n1 x m2.
Step 2: Three nested loops will be used for the multiplication of the matrices.
Step 3: The first two loops are used to iterate over the rows and columns of the result ma-
trix, respectively.
Step 4: The innermost loop performs the multiplication of corresponding elements from the
current row of the first matrix and the current column of the second matrix.
Step 5: Add these products to get the element of the result matrix.
Step 6: Repeat these steps for all elements of the result matrix.
Step 7: Stop the program.

VIVA QUESTIONS:
a. How to check if two given matrices are identical?
b. How will you check for an identity matrix?
c. Create a spiral matrix from the given array.
d. Find the longest route in the matrix.
e. Count all paths in a matrix from first cell to last cell
EXPERIMENT 2

AIM:
Write a program to perform addition of two complex numbers using constructor overloading.
The first constructor which takes no argument is used to create objects which are not initial-
ized, second which takes one argument is used to initialize real and imag parts to equal values
and third which takes two argument is used to initialized real and imag to two different val-
ues.

THEORY:
Constructor overloading means having more than one constructor with the same name. Con-
structors are methods invoked when an object is created. You must use the same name for all
the constructors which is the class name. This is done by declaration the constructor with a
different number of arguments.

ALGORITHM:
Step 1: Create a class Complex.
Step 2: Declare real and imaginary members.
Step 3: Create constructor to accept real and imaginary part.
Step 4 Defining add () method for adding two complex number
a. Creating temporary variable.
b. Adding real part of complex numbers.
c. Adding Imaginary part of complex numbers.
d. Return sum
Step 7: Stop the program.

VIVA QUESTIONS:
a. What is virtual Constructor? Explain with example?
b. Explain the order in which constructors are called when object of derived class
is created?
c. What are restrictions applied to constructor and destructor?
d. What is copy constructor? What is its use
e. What is significance of destructor in the program?
EXPERIMENT 3

AIM:
Write a program to find the greater of two given numbers in two different classes using friend
function.

THEORY:
A friend function can be granted special access to private and protected members of a class
in C++. They are the non-member functions that can access and manipulate the private and
protected members of the class for they are declared as friends.

ALGORITHM:
Step 1: Create two class A and class B.
Step 2: Create a friend function greatest common to both class A and class B.
Step 3: Define greatest function having objects of both class as argument:
void greatest(A a1,B b1)
{
if(a1.number>b1.number)
{
cout<<"\n Number in class A is greatest i.e. "<<a1.number;
}
else if(a1.number<b1.number)
{
cout<<"\n Number in class B is greatest i.e. "<<b1.number;
}
else
{
cout<<"\n Number in both classes are equal";
}
}
Step 4: Inside main take values for both numbers (belong to class A and class B).
Step 5: Call greatest function.
Step 6: Return greatest number.
Step 7: Stop the program.

VIVA QUESTIONS:

a. Explain the characteristics of friend function?


b. Which keyword is used to declare friend function?
c. List the advantages of using friend function?
d. Where does the keyword friend function should be placed?
e. What are friend classes? What are the advantages of using friend classes?
EXPERIMENT 4

AIM:
Implement a class string containing the following functions:
a. Overload + operator to carry out the concatenation of strings.
b. Overload = operator to carry out string copy.
c. Overload <= operator to carry out the comparison of strings.
d. Function to display the length of a string.
e. Function tolower( ) to convert upper case letters to lower case.
f. Function toupper( ) to convert lower case letters to upper case.

THEORY:
Function overloading is a feature of object-oriented programming where two or more func-
tions can have the same name but different parameters. When a function name is overloaded
with different jobs it is called Function Overloading. In Function Overloading “Function”
name should be the same and the arguments should be different.
Operator overloading is a compile-time polymorphism. It is an idea of giving special mean-
ing to an existing operator in C++ without changing its original meaning.

ALGORITHM:
Step 1: Class Definition- Define a class named String that will encapsulate the string data
and its operations.
Step 2: Constructor- Implement a constructor that takes an initial string as a parameter and
initializes the internal string variable with it.
Step 3: Overload + operator to concatenate two String objects. Inside the operator
overloading method, concatenate the two strings values and return a new String object
with the result
Step 4: Overload = Operator for String Copy to copy one String object into another. Inside
the operator overloading method, assign the value of the right-hand side String to the left-
hand side String.
Step 5: Overload <= Operator for Comparison to compare two String objects. Inside the
operator overloading method, compare the values of the two String objects and return True
if the left-hand side is less than or equal to the right-hand side, and False otherwise.
Step 6: Function to Display Length- Implement a method (function) within the class to
calculate and return the length of the string. This can be done by counting the number of
characters in the string.
Step 7: Function to Convert to Lowercase (tolower)- Implement a method (function) to
convert all uppercase letters in the string to lowercase. You can iterate through the charac-
ters of the string and use the lower () function to transform them.
Step 8: Function to Convert to Uppercase (toupper)- Implement a method (function) to
convert all lowercase letters in the string to uppercase. You can iterate through the charac-
ters of the string and use the upper () function to transform them.
Step 9: Stop Algorithm.

VIVA QUESTIONS:
a. Explain overloading unary operator.
b. Explain difference between overloaded function and overridden function?
c. How to declare operator function?
d. In case of non- static member functions how many maximum object argu-
ments a unary operator overloaded function can take?
e. What is operator overloading in C++?
EXPERIMENT 5

AIM:
Create a class called LIST with two pure virtual function store () and retrieve (). To store a
value call store and to retrieve call retrieve function. Derive two classes stack and queue from
it and override store and retrieve.

THEORY:
A pure virtual function (or abstract function) in C++ is a virtual function for which we can
have an implementation, but we must override that function in the derived class, otherwise,
the derived class will also become an abstract class. A pure virtual function is declared by
assigning 0 in the declaration.

ALGORITHM:
Define an Abstract Base Class - LIST
Create a base class named LIST.
Declare two pure virtual functions within LIST: store() and retrieve(). These func-
tions will serve as interfaces to store and retrieve values.
Derive Stack Class from LIST:
Create a derived class named Stack that inherits from the LIST base class.
Override the store() function in the Stack class to implement storing values for a
stack.
Override the retrieve() function in the Stack class to implement retrieving values
for a stack.
Derive Queue Class from LIST:
Create another derived class named Queue that also inherits from the LIST base
class.
Override the store() function in the Queue class to implement storing values for a
queue.
Override the retrieve() function in the Queue class to implement retrieving values
for a queue.
Implement store() and retrieve() Functions in Derived Classes:
In the Stack class, the store() function should push values onto the stack, and the
retrieve() function should pop values from the stack.
In the Queue class, the store() function should enqueue values, and the retrieve()
function should dequeue values.

By following this algorithm, you will have created an abstract base class LIST with two pure
virtual functions that define the interface for storing and retrieving values. You will then derive
two classes, Stack and Queue, from the base class and override the store() and retrieve() func-
tions to implement the specific behavior for stacks and queues.
VIVA QUESTIONS:
a. What is a virtual function in C++?
b. Why are virtual functions used in object-oriented programming?
c. How is a virtual function different from a regular member function in a class?
d. Can a constructor or destructor be declared as a virtual function? Why or why
not?
e. How is function overriding related to virtual functions?
EXPERIMENT 6

AIM:
Write a program to define the function template for calculating the square of given numbers
with different data types.

THEORY:
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data
type as a parameter so that we do not need to write the same code for different data types.
For example, a software company may need to sort () for different data types. Rather than
writing and maintaining multiple codes, we can write one sort () and pass the datatype as a
parameter.

ALGORITHM:
Define the Function Template:
Start by declaring a function template with the keyword template followed by
the template parameter.
Define the function with a return type and parameters using the template pa-
rameter.

Template Parameter:
Choose a template parameter name, commonly denoted as T, to represent the
data type for which the square will be calculated.

Function Definition:
Inside the function template, define the function with the chosen template pa-
rameter.
Use the template parameter for the function parameter type to allow flexibility
for different data types.

Calculate Square:
Within the function body, calculate the square of the given number using the
formula value * value.

Function Call:
In your program, when you call the function, provide the appropriate data type
for the template parameter.

Use the Result:


The result of the function call will have the squared value of the input, which
you can then use as needed in your program.
VIVA QUESTIONS:
a. What is a function template in C++?
b. How do you declare a function template?
c. What is the purpose of using function templates?
d. Can you give an example of a function template?
e. How does the compiler generate code for a function template?
EXPERIMENT 7

AIM:
Write a program to demonstrate the use of special functions, constructors, and destructor in
the class template. The program is used to find the bigger of two entered numbers.

THEORY:
The default constructors, destructors, copy constructors, and copy assignment operators are
special member functions. These functions create, destroy, convert, initialize, and copy class
objects.
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor
in C++ has the same name as the class or structure. It constructs the values i.e. provides data
for the object which is why it is known as constructor.
Destructor is an instance member function that is invoked automatically whenever an object
is going to be destroyed. Meaning, a destructor is the last function that is going to be called
before an object is destroyed.

ALGORITHM:
Class Template Definition:
Start by defining a class template named BiggerFinder that takes a template
parameter T for the data type.

Private Data Members:


Declare private data members to store the two numbers.

Define Constructor:
Define a constructor that takes two parameters of type T and initializes the private
data members with the provided values.

Special Function for Bigger Number:


Create a special function (e.g., findBigger()) that compares the two numbers and re-
turns the bigger one.

Destructor:
Implement a destructor to perform any necessary cleanup. This is optional but can be
used to release resources.
VIVA QUESTIONS:
a. What is the purpose of a constructor in a class template?
b. How is the constructor declared and defined in a class template for finding the
bigger of two numbers?
c. Why use a class template for finding the bigger of two numbers?
d. What is the purpose of a destructor in the class template?
e. How is the destructor declared and defined in the class template?
EXPERIMENT 8

AIM:
Write a program to perform the deletion of white spaces such as horizontal tab, vertical tab,
space, line feed, new line and carriage return from a text file and store the contents of the file
without the white spaces on another file.

THEORY:
By default, there are six types of whitespace characters - space, line feed, horizontal tab, ver-
tical tab, carriage return, and form feed. We can write programs to remove whitespace from a
string in C++. These programs include the std::remove_if function, the std::regrex_re-
place function, and the boost library.
.

ALGORITHM:
Open Input File:
Open the input text file in read mode.

Open Output File:


Open an output text file in write mode to store the contents
without white spaces.

Read Input File Line by Line:


Read each line from the input file.

Remove White Spaces:


For each line, iterate through the characters and remove white spaces (horizontal tab,
vertical tab, space, line feed, new line, and carriage return).

Write to Output File:


Write the modified line (without white spaces) to the output file.

Repeat Steps 3-5:


Repeat steps 3-5 until the end of the input file is reached.

Close Files:
Close both the input and output files.

VIVA QUESTIONS:
a. What is the purpose of deleting white spaces from a text file?
b. Which white space characters are typically targeted for deletion in this process?
c. Why is it important to open the files in different modes (read and write) during this
process?
d. Why is the check for white space essential in the iteration process?
e. How does the algorithm handle the end of the input file?
EXPERIMENT 9

AIM:
Write a program to read the class object of student info such as name, age, sex, height, and
weight from the keyboard and to store them on a specified file using read () and write ()
functions. Again, the same file is opened for reading and displaying the contents of the file
on the screen.

THEORY:
File handling is used to store data permanently in a computer. Using file handling we can
store our data in secondary memory (Hard disk). Following operations can be performed
with file:
a) Naming a file
b) Opening a file
c) Writing data into the file
d) Reading data from the file
e) Closing a file.

ALGORITHM:
Define a Class for Student Information:
Create a class named StudentInfo with attributes such as name, age, sex, height, and
weight.

Implement Read Function in the Class:


Implement a function in the class (read()) to read the student information from the
keyboard and store it in the class object. Implement Write Function in the Class:
Implement another function in the class (write()) to write the student information to a
specified file.

Open the File for Writing:


Open the specified file in write mode.

Read Student Info from Keyboard:


Create an object of the StudentInfo class.
Call the read() function to input student information.

Write Student Info to File:


Call the write() function to write the student information to the opened file.

Close the File:


Close the file after writing.

Open the File for Reading:


Open the same file in read mode.
Implement Read Function to Read from File:
Implement a function in the class (readFromFile()) to read student information from
the opened file.

Display Student Info on the Screen:


Create another object of the StudentInfo class.
Call the readFromFile() function to read from the file.
Display the student information on the screen.

Close File.

VIVA QUESTIONS:
a. What is the purpose of the program you have written?
b. Explain the role of the read () function in your program.
c. How does the write () function work in this program?
d. What happens if the specified file is not accessible or does not exist during the write
operation?
e. Can you describe the process of reading data from the file using the read () function?
EXPERIMENT 10

AIM:
Write a program to raise an exception if any attempt is made to refer to an element whose
index is beyond the array size.

THEORY:
One of the advantages of C++ over C is Exception Handling. Exceptions are runtime anom-
alies or abnormal conditions that a program encounters during its execution. There are two
types of exceptions: a) Synchronous, b) Asynchronous (i.e., exceptions which are beyond the
program’s control, such as disc failure, keyboard interrupts etc.). C++ provides the following
specialized keywords for this purpose:
try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws but
does not handle itself.

ALGORITHM:
Initialize Array:
Declare an array and initialize it with the desired size.

Prompt for Index:


Prompt the user to enter the index they want to access.

Check Index Validity:


Check if the entered index is within the valid range (0 to size-1) of the array.

Raise Exception if Invalid:


If the index is beyond the valid range, raise an exception. The exception should con-
tain a message indicating that the index is out of bounds.

Access Element if Valid:


If the index is valid, access the element in the array at the specified index.

Handle the Exception (if needed):


In your programming language, you may need to include appropriate exception han-
dling mechanisms (try-catch blocks) to catch and handle the raised exception.
VIVA QUESTIONS:
a. What is the purpose of exception handling in programming?
b. Why is it important to handle exceptions when accessing array elements using
an index?
c. What is an "IndexOutOfBoundsException," and when is it typically encoun-
tered?
d. What is the role of the try-catch block in handling exceptions?
e. Can you provide an example code snippet for handling the exception when ac-
cessing an element beyond the array size?
List of Practical (Beyond the List Prescribed by G.G.S.I.P.U)

EXPERIMENT 1

AIM:
Write a program to illustrate how template function can be overloaded.

THEORY:
Template background information has been given already.

ALGORITHM:
Define the First Template Function:
Start by defining a template function named printElement that takes a single parame-
ter of type T and prints it.

Overload the Template Function for Different Data Types:


Create additional template functions with the same name (printElement) but with dif-
ferent parameter types. Overload the function for various data types (e.g., int, double,
char).

Function Calls:
In your program, call the template function with different data types to demonstrate
the overloading.// Calls the generic template function
Print Char: A Generic Print: Hello

VIVA QUESTIONS:
a. How template helps in real life?
b. What are the advantages of template overloading?
c. Give real life example where we can make use of function overloading?
d. Differentiate between function overloading and template overloading?
e. Why is template known as generic programming technique?
EXPERIMENT 2

AIM:
Write a program that simulates a simple banking system with multiple account types, transac-
tions, and error handling.

THEORY:
It will use almost all OOPS concepts.

ALGORITHM:
Define Account Classes:
Create base classes like Account and derived classes such as SavingsAccount, Check-
ingAccount, and LoanAccount. Each class should have attributes like account num-
ber, balance, and relevant methods.

Implement Transactions:
Include transaction methods like deposit, withdraw, and transfer in each account type.
Ensure that these methods update the account balance accordingly.

Error Handling:
Implement robust error handling mechanisms. For instance, handle insufficient funds
during withdrawals, check if the account exists before transferring, and validate user
input.

Store Account Information:


Use file I/O to store and retrieve account information. Each account type can have a
separate file for persistent data storage.

User Interface:
Create a user interface for interacting with the banking system. Utilize a menu system
that allows users to perform operations like creating accounts, making transactions,
and checking balances.

Note:
This is a broad overview, and the actual implementation may involve creating various
classes, error-checking mechanisms, and a well-designed user interface. You can add
additional features like interest calculation, account history, or security measures
based on your requirements.
VIVA QUESTIONS:
a. What is the purpose of the program you have described?
b. Why is it important to have multiple account types in the banking system sim-
ulation?
c. Can you explain the role of the Account base class and its derived classes in
the program?
d. How are transactions implemented in the program?
e. What kind of error handling mechanisms are included in the program?
f. Can you suggest additional features that could be added to enhance the bank-
ing system simulation?
g. What could be potential challenges or complexities in implementing a more
realistic banking system simulation?
EXPERIMENT 3

AIM:
C++ program that models a simplified library management system using object-oriented pro-
gramming principles?

THEORY:
It will use almost all OOPS concepts.

ALGORITHM:
Define Classes:
Create classes such as Book, Library, and Member to represent entities in the library
system. Each class should have attributes and methods that capture their functionali-
ties.

Implement Inheritance:
Utilize inheritance to represent a hierarchy. For example, a Book class may be a base
class, and derived classes like FictionBook and NonFictionBook inherit from it.

Use Polymorphism:
Implement polymorphism by allowing functions to operate on objects of different
types. For instance, a function to display book information should work for both fic-
tion and non-fiction books.

Handle Transactions:
Develop methods to handle library transactions, such as checking out and returning
books. Ensure proper updates to book availability and member records.

1. Incorporate Encapsulation:
Encapsulate data by making attributes private and providing public methods for ac-
cessing and modifying them. This enhances data integrity and security.

Implement File I/O:


Use file I/O to persistently store and retrieve information about books, library mem-
bers, and transaction history.

Apply Exception Handling:


Incorporate exception handling to deal with scenarios like trying to check out a book
that is not available or searching for a member that does not exist.

Create User Interface:


Develop a user interface allowing users to interact with the library system. Include op-
tions to search for books, check out, return, and display member information.

Note:
• This program is a comprehensive example that covers various object-oriented pro-
gramming principles, including inheritance, polymorphism, encapsulation, file I/O,
and exception handling.

VIVA QUESTIONS:
a. What is the purpose of the library management system program you've de-
scribed?
b. Explain the concept of inheritance in the context of your program.
c. How is polymorphism implemented in your program, and why is it beneficial?
d. Can you provide an example of encapsulation in your program?
e. How does the program handle library transactions, such as checking out and
returning books?
f. Explain the role of file I/O in your program.
g. How is exception handling incorporated in the program, and why is it im-
portant?
h. Describe the user interface of the library management system.
i. What advantages does using object-oriented programming principles provide
for this library management system?

You might also like