[go: up one dir, main page]

0% found this document useful (0 votes)
41 views29 pages

OOP Lab Manual 2024-25

Uploaded by

TECH PRANAV
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)
41 views29 pages

OOP Lab Manual 2024-25

Uploaded by

TECH PRANAV
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/ 29

Object Oriented Programming Lab

D Y Patil College of Engineering, Akurdi, Pune


Department of Artificial Intelligence & Data Science
2024-25

Lab Manual
Object Oriented Programming
SE- SEM- I
Prepared by
Mrs. Rasika V. Wattamwar
Mrs. Snehal R. Malpani
Mrs. Megha R. Mehar

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

D Y Patil College of Engineering, Akurdi, Pune


Department of Artificial Intelligence & Data Science

Vision of Institute

“Empowerment through knowledge”

Mission of Institute

To educate students to transform them as professionally competent and quality


conscious engineers by providing conducive environment for teaching, learning
and overall personality development, culminating the institute into an international
seat of excellence.

VISION of Department

Developing highly skilled and competent IT professional for sustainable growth in the
field of Artificial Intelligence and Data science.

MISSION of Department

1. To empower students for developing intelligent systems and innovative products


for societal problems.

2. To build strong foundation in Data computation, Intelligent Systems that enables


self-development entrepreneurship and Intellectual property.

3. To develop competent and skilled IT professional by imparting global skills and


technologies for serving society.
Dept. of AI & DS DYPCOE, Akurdi, Pune-44.
Object Oriented Programming Lab

D Y Patil College of Engineering, Akurdi, Pune

Department of Artificial Intelligence & Data Science

Program Outcomes (PO’s)

Apply the knowledge of mathematics, science, Engineering fundamentals,


Engineering and an Engineering specialization to the solution of complex Engineering
PO1
knowledge problems.
Identify, formulate, review research literature and analyze complex
PO2 Problem analysis Engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences and Engineering sciences.
Design solutions for complex Engineering problems and design system
Design / components or processes that meet the specified needs with appropriate
PO3 Development of consideration for the public health and safety, and the cultural, societal,
Solutions and Environmental considerations.
Use research-based knowledge and research methods including design of
Conduct
experiments, analysis and interpretation of data, and synthesis of the
PO4 Investigations of
information to provide valid conclusions.
Complex Problems
Create, select, and apply appropriate techniques, resources, and modern
Engineering and IT tools including prediction and modeling to complex
PO5 Modern Tool Usage
Engineering activities with an understanding of the limitations.

Apply reasoning informed by the contextual knowledge to assess societal,


The Engineer and health, safety, legal and cultural issues and the consequent responsibilities
PO6
Society relevant to the professional engineering practices.

Understand the impact of the professional Engineering solutions in


Environment and societal and Environmental contexts, and demonstrate the knowledge of,
PO7
Sustainability and need for sustainable development.

Apply ethical principles and commit to professional ethics and


PO8 Ethics responsibilities and norms of Engineering practice.

Function effectively as an individual, and as a member or leader in


Individual and Team
PO9 diverse teams, and in multidisciplinary settings.
Work
Communicate effectively on complex Engineering activities with the
Engineering community and with society at large, such as, being able to
Communication
PO10 comprehend and write effective reports and design documentation, make
Skills
effective presentations, and give and receive clear instructions.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Demonstrate knowledge and understanding of Engineering and


management principles and apply these to one’s own work, as a member
Project Management and leader in a team, to manage projects and in multidisciplinary
PO11
and Finance Environments.

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

Program Specific Outcomes (PSO’s)

The ability to understand, analyze and develop computer programs in the


areas related to algorithms, system software, multimedia, web design,
PSO1 Professional Skills
networking, artificial intelligence and data science for efficient design of
computer-based systems of varying complexities.

The ability to apply standard practices and strategies in software project


Problem-Solving
PSO2 development using open-ended programming environments to deliver a
Skills
quality product for business success.

Successful Career The ability to employ modern computer languages, environments and
PSO3 and platforms in creating innovative career paths to be an entrepreneur and to
Entrepreneurship have a zest for higher studies.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

D Y Patil College of Engineering, Akurdi, Pune

Department of Artificial Intelligence & Data Science

Course Objectives:

To understand basics of Computer Graphics, apply various methods and


techniques for implementing line-circle drawing, projections, animation, shading,
illumination and lighting using concepts of Object Oriented Programming.

Course Outcomes “Empowerment


(CO’s) through knowledge”

CO1: Understand and apply the concepts like inheritance,


polymorphism, exception handling and generic structures for
implementing reusable programming codes.

CO2: Analyze the concept of file and apply it while storing


and retrieving the data from secondary storages.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

D Y Patil College of Engineering, Akurdi, Pune

Department of Artificial Intelligence & Data Science

Course- Object Oriented Programming Lab (OOPL-21043) Semester – III

List of Practical’s
Sr. CO PO / PSO
Title of Experiments
No Mapped Mapped

Implement a class Complex which represents the Complex Number


data type. Implement the following. PO-1, PO-2,
i) Constructor (including a default constructor which creates PO-4, PO-5
the complex number 0+0i). ,PO-9, PO-11,
1 ii) Overload operator+ to add two complex numbers. CO-1 PO-12
iii) Overload operator* to multiply two complex numbers. PSO-1,PSO-2,
iv) Overload operators << and >> to print and read Complex PSO-3
Numbers.

Develop a program in C++ to create a database of student’s


information system containing the following information: Name, Roll PO-1, PO-4,
number, Class, Division, Date of Birth, Blood group, Contact address, PO-5, PO-9,
Telephone number, Driving license no. and other. Construct the PO-11, PO-12
2 CO-1
database with suitable member functions. Make use of constructor,
default constructor, copy constructor, destructor, static member PSO-1,PSO-2,
PSO-3
functions, friend class, this pointer, inline code and dynamic memory
allocation operators-new and delete as well as exception handling.

Imagine a publishing company which does marketing for book and


audiocassette versions.
Create a class publication that stores the title (a string) and price (type PO-1, PO-4,
float) of a publication. PO-5, PO-9,
PO-11, PO-12
3 From this class derive two classes: book, which adds a page count CO-1
(type int), and tape, which adds a playing time in minutes (type float). PSO-1,PSO-2,
Write a program that instantiates the book and tape classes, allows user PSO-3
to enter data and displays the data members. If an exception is caught,
replace all the data member values with zero values.

PO-1, PO-4,
Write a C++ program that creates an output file, writes information to PO-5, PO-9,
PO-11, PO-12
4 it, closes the file, open it again as an input file and read the information CO-2
from the file. PSO-1,PSO-2,
PSO-3

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

PO-1, PO-2,
Write a function template for selection sort that inputs, sorts and PO-4, PO-5,
PO-9, PO-11,
outputs an integer array and a float array. CO-1,
5 PO-12
CO-2
PSO-1,PSO-2,
PSO-3
PO-1, PO-4,
Write C++ program using STL for sorting and searching user defined PO-5, PO-9,
CO-1, PO-11, PO-12
6 records such as Item records (Item code, name, cost, quantity etc)
CO-2
using vector container. PSO-1,PSO-2,
PSO-3

PO-1, PO-2,
Write a program in C++ to use map associative container. The keys PO-4, PO-5,
will be the names of states and the values will be the populations of the PO-9, PO-11,
CO-1,
7 states. When the program runs, the user is prompted to type the name PO-12
CO-2
of a state. The program then looks in the map, using the state name as
PSO-1,PSO-2,
an index and returns the population of the state.
PSO-3

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 1

TITLE: Program to implement Operator Overloading

PROBLEM STATEMENT: Implement a class Complex which represents the Complex


Number data type. Implement the following:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overload operator+ to add two complex numbers.
3. Overload operator* to multiply two complex numbers.
4. Overload operators << and >> to print and read Complex Numbers.

OBJECTIVE:
• To understand the concept of operator overloading.

THEORY:

C++ Overloading (Function and Operator)

If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
• methods,
• constructors, and
• indexed properties
• It is because these members have parameters only.

Types of overloading in C++ are:


Function overloading
Operator overloading

C++ Function Overloading


Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can differentiate between the
functions.
The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

C++ Operators Overloading


Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type. For example, C++ provides the ability to add the variables of the
user-defined data type that is applied to the built-in data types.
The advantage of Operators overloading is to perform different operations on the same operand.

Operator that cannot be overloaded are as follows:


1. Scope operator (::)
1. Sizeof
2. member selector(.)
3. member pointer selector(*)
4. ternary operator(?:)

Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)

// body of the function.

Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
Rules for Operator Overloading
o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

Write down an example of operator overloading.

CONCLUSION: Thus, operator overloading is implemented successfully for arithmetic


and insertion and extraction operator.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 2

TITLE: Program to create Students Database using C++ Concepts

PROBLEM STATEMENT: Develop a program in C++ to create a database of student’s


information system containing the following information: Name, Roll number, Class, Division,
Date of Birth, Blood group, Contact address, Telephone number, Driving license no. and other.
Construct the database with suitable member functions. Make use of constructor, default
constructor, copy constructor, destructor, static member functions, friend class, this pointer,
inline code and dynamic memory allocation operators-new and delete as well as exception
handling
OBJECTIVE:
• To understand the C++ concepts.

THEORY:

Constructor: 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. Constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object which is why it is known as
constructors.

• Constructor is a member function of a class, whose name is same as the class name.
• Constructor is a special type of member function that is used to initialize the data members for
an object of a class automatically, when an object of the same class is created.
• Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
• Constructor do not return value; hence they do not have a return type.

Constructor can be defined inside the class declaration or outside the class declaration

a. Syntax for defining the constructor within the class


<class-name>(list-of-parameters)
{
//constructor definition
}

b. Syntax for defining the constructor outside the class

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}

Characteristics of constructor
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the class though it can be
declared in the private section of the class.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• Constructor cannot be inherited.
• Addresses of Constructor cannot be referred.
• Constructor make implicit calls to new and delete operators during memory allocation.

Types of Constructors

1.Default Constructor: A constructor without any arguments or with the default value for every
argument is said to be the Default constructor. A constructor that has zero parameter list or in
other sense, a constructor that accept no arguments is called a zero argument constructor or
default constructor.
If default constructor is not defined in the source code by the programmer, then the
compiler defined the default constructor implicitly during compilation. If the default constructor
is defined explicitly in the program by the programmer, then the compiler will not defined the
constructor implicitly, but it calls the constructor implicitly.

2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically,


these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the object.

3.Copy Constructor: A copy constructor is a member function that initializes an object using
another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class,
a default constructor( without parameters ) should also be explicitly defined as the compiler will
not provide a default constructor in this case. However, it is not necessary but it’s considered to

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

be the best practice to always define a default constructor. Copy constructor takes a reference to
an object of the same class as an argument.

Destructor: 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.
A destructor is also a special member function like a constructor. Destructor destroys the
class objects created by the constructor.
• Destructor has the same name as their class name preceded by a tilde (~) symbol.
• It is not possible to define more than one destructor.
• The destructor is only one way to destroy the object created by the constructor. Hence
destructor can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when an object goes out of scope.
• Destructor release memory space occupied by the objects created by the constructor.
• In destructor, objects are destroyed in the reverse of an object creation.

The syntax for defining the destructor within the class:


~ <class-name>() {
// some instructions
}

The syntax for defining the destructor outside the class:

<class-name> :: ~<class-name>() {
// some instructions
}

A destructor function is called automatically when the object goes out of scope:
• the function ends
• the program ends
• a block containing local variables ends
• a delete operator is called

We can call the destructors explicitly using the following statement:


object_name.~class_name()

Static Member Functions and Data Member: Static data members are class members that are
declared using static keywords. A static member has certain special characteristics which are as
follows:

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
It is initialized before any object of this class is created, even before the main starts.
It is visible only within the class, but its lifetime is the entire program.

Syntax:
static data_type data_member_name;

Static Member Function: Static Member Function in a class is the function that is declared as
static because of which function attains certain properties as defined below:
• A static member function is independent of any object of the class.
• A static member function can be called even if no objects of the class exist.
• A static member function can also be accessed using the class name through the scope
resolution operator.
• A static member function can access static data members and static member functions
inside or outside of the class.
• Static member functions have a scope inside the class and cannot access the current
object pointer.
• You can also use a static member function to determine how many objects of the class
have been created.
The reason we need Static member function:
• Static members are frequently used to store information that is shared by all objects in a
class.
• For instance, you may keep track of the quantity of newly generated objects of a specific
class type using a static data member as a counter. This static data member can be
increased each time an object is generated to keep track of the overall number of objects.

Friend Class: A friend class can access private and protected members of other classes in which
it is declared as a friend. It is sometimes useful to allow a particular class to access private and
protected members of other classes.
We can declare a friend class in C++ by using the friend keyword. For example,
Class one
{
Friend class two;
}
Class two
{
//here class two can access private data members of class one

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

This pointer: A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address.
The general form of a pointer variable declaration is −
datatype *pointer_name;
C++ provides a keyword 'this', which represents the current object and passed as a
hidden argument to all member functions. The this pointer is a constant pointer that holds the
memory address of the current object. The this pointer is not available in static member
functions as static member functions can be called without any object. static member functions
can be called with class name.

Inline Function: Functions can be instructed to compiler to make them inline so that compiler
can replace those function definition wherever those are being called. Compiler replaces the
definition of inline functions at compile time instead of referring function definition at runtime.
Syntax:
inline returnType functionName(parameters)
{
// code
}
- The use of keyword inline is before the function definition.
- Reduces the function call overhead.
- Inline function is a function that is expanded in line when it is called.
- This substitution is performed by the C++ compiler at compile time.
- Inline function may increase efficiency if it is small.

Dynamic memory allocation operators: Dynamic memory allocation in C++ refers to


performing memory allocation manually by a programmer. Dynamically Memory is allocated
with Keyword – new. Dynamically Memory is deallocated with Keyword – delete.
Syntax to use new operator:
pointer-variable = new data-type;
Syntax to use delete operator:
delete pointer-variable;

CONCLUSION: Thus, different concepts of C++ are successfully studied and implemented.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 3

TITLE: Implementation of Inheritance

PROBLEM STATEMENT: Imagine a publishing company which does marketing for book
and audio cassette versions. Create a class publication that stores the title (a string) and price
(type float) of publications. From this class derive two classes: book which adds a page count
(type int) and tape which adds a playing time in minutes (type float). Write a program that
instantiates the book and tape class, allows user to enter data and displays the data members. If
an exception is caught, replace all the data member values with zero values.

OBJECTIVE:
• To understand the concept Inheritance in C++.

THEORY:

Inheritance:

The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.

In C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance

2. Multiple Inheritance

3. Hierarchical Inheritance

4. Multilevel Inheritance

5. Hybrid Inheritance (also known as Virtual Inheritance)

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Single Inheritance in C++


In this type of inheritance one derived class inherits from only one base class. It is the most
simplest form of Inheritance.

Multiple Inheritance in C++


In this type of inheritance a single derived class may inherit from two or more than two base
classes.

Hierarchical Inheritance in C++


In this type of inheritance, multiple derived classes inherits from a single base class.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Multilevel Inheritance in C++


In this type of inheritance the derived class inherits from a class, which in turn inherits from
some other class. The Super class for one, is sub class for the other.

Hybrid (Virtual) Inheritance in C++


Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Write an example demonstrating the hierarchical inheritance.

CONCLUSION: Thus, program for inheritance is successfully studied and


implemented.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 4

TITLE: File handling

PROBLEM STATEMENT: Write a C++ program that creates an output file, writes
information to it, closes the file, open it again as an input file and read the information from the
file.

OBJECTIVE:
To understand the concepts File handling in C++

THEORY:

Sr.No Data Type & Description

1 ofstream
This data type represents the output file stream and is used to create files and to write
information to files.

2 ifstream
This data type represents the input file stream and is used to read information from files.

3 fstream
This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and read
information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is
used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.

Sr.No Mode Flag & Description

1 ios::app
Append mode. All output to that file to be appended to the end.

2 ios::ate
Open a file for output and move the read/write control to the end of the file.

3 ios::in
Open a file for reading.

4 ios::out
Open a file for writing.

5 ios::trunc
If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists, following
will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.

Write an example demonstrating creating, opening, writing and reading from a file.

CONCLUSION: Thus, program for file handling is successfully studied and


implemented.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 5

TITLE: Program to implement Selection Sort using Function


Template

PROBLEM STATEMENT: Write a function template for selection sort that inputs, sorts and
outputs an integer array and a float array.

OBJECTIVE:
To understand the concept of function template

THEORY:

Template:

Templates are the foundation of generic programming, which involves writing code in
a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The
library containers like iterators and algorithms are examples of generic programming
and have been developed using template concept. There is a single definition of each
container, such as vector, but we can define many different kinds of vectors for
example, vector <int> or vector <string>.
You can use templates to define functions as well as classes, let us see how do they
work:

Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be
used within the function definition.

Selection Sort:
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has
O(n2) time complexity, making it inefficient on large lists, and generally performs
worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

performance advantages over more complicated algorithms in certain situations,


particularly where auxiliary memory is limited

How selection sort works?


Example

For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.

So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in
linear manner.

We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.

After two iterations, two least values are positioned at the beginning in the sorted
manner.
The same process is applied on the rest of the items in the array.

Pictorial depiction of entire sorting process is as follows –

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Write down an example of function template:

Write down ALGORITHM of selection sort:

CONCLUSION: Thus, selection sort is implemented using function template.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 6

TITLE: Program to use STL for sorting and searching

PROBLEM STATEMENT: Write C++ program using STL for sorting and searching
user defined records such as Item records (Item code, name, cost, quantity etc) using
vector container.

OBJECTIVE:

To learn the concept STL, searching, sorting and vector container.

THEORY:

STL:
The Standard Template Library (STL) is a set of C++ template classes to provide
common programming data structures and functions such as lists, stacks, arrays, etc. It
is a library of container classes, algorithms, and iterators. It is a generalized library and
so, its components are parameterized. A working knowledge of template classes is a
prerequisite for working with STL.

STL has four components


• Algorithms
• Containers
• Functions
• Iterators

Algorithms
• The algorithm defines a collection of functions especially designed to be used on
ranges of elements. They act on containers and provide means for various operations
for the contents of the containers.
• Algorithm
• Sorting
• Searching
• Important STL Algorithms
• Useful Array algorithms
• Partition Operations
• Numeric

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

Containers
• Containers or container classes store objects and data. There are in total seven
standard “first-class” container classes and three container adaptor classes and only
seven header files that provide access to these containers or container adaptors.
• Sequence Containers: implement data structures which can be accessed in a
sequential manner.
• vector
• list
• deque
• arrays
• forward_list( Introduced in C++11)

• Container Adaptors : provide a different interface for sequential containers.


• queue
• priority_queue
• stack

• Associative Containers : implement sorted data structures that can be quickly


searched (O(log n) complexity).
• set
• multiset
• map
• multimap

• Unordered Associative Containers : implement unordered data structures that can be


quickly searched
• unordered_set
• unordered_multiset
• unordered_map
• unordered_multimap

Functions
• The STL includes classes that overload the function call operator. Instances of such
classes are called function objects or functors. Functors allow the working of the
associated function to be customized with the help of parameters to be passed.

Iterators
• As the name suggests, iterators are used for working upon a sequence of values. They
are the major feature that allow generality in STL.

Utility Library

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

• Defined in header <utility>.


• pair

Vectors in C++ STL:


Vectors are same as dynamic arrays with the ability to resize itself automatically when
an element is inserted or deleted, with their storage being handled automatically by the
container. Vector elements are placed in contiguous storage so that they can be accessed
and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end
takes differential time, as sometimes there may be a need of extending the array.
Removing the last element takes only constant time because no resizing happens.
Inserting and erasing at the beginning or in the middle is linear in time.

Sorting:
It is one of the most basic functions applied to data. It means arranging the data in a
particular fashion, which can be increasing or decreasing. There is a builtin function in
C++ STL by the name of sort(). This function internally uses IntroSort. In more details it
is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it
uses QuickSort but if QuickSort is doing unfair partitioning and taking more than
N*logN time, it switches to HeapSort and when the array size becomes really small, it
switches to InsertionSort.

Searching:
It is a widely used searching algorithm that requires the array to be sorted before search
is applied. The main idea behind this algorithm is to keep dividing the array in half
(divide and conquer) until the element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it
returns true otherwise if the middle term is greater than the target, the search is
performed in the left sub-array. If the middle term is less than target, the search is
performed in the right sub-array.

FUNCTIONS USED OF VECTOR:

ALGORITHM:

CONCLUSION: Thus, concepts of Vector using STL in C++ are successfully studied
and implemented.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

ASSIGNMENT NO. 7

TITLE: Program in C++ to use map associative container.

PROBLEM STATEMENT: Write a program in C++ to use map associative container.


The keys will be the names of states and the values will be the populations of the states.
When the program runs, the user is prompted to type the name of a state. The program
then looks in the map, using the state name as an index and returns the population of
the state.

OBJECTIVE:
To learn the concept of map associative container.

THEORY:

Map associative container:


Map associative container are associative containers that store elements in a mapped
fashion. Each element has a key value and a mapped value. No two mapped values can
have same key values.
map::operator[]
This operator is used to reference the element present at position given inside the
operator. It is similar to the at() function, the only difference is that the at() function
throws an out-of-range exception when the position is not in the bounds of the size of
map, while this operator causes undefined behaviour.
Syntax :
mapname[key]
Parameters : Key value mapped to the element to be fetched.
Returns : Direct reference to the element at the given key value.

Some basic functions associated with Map:


begin() – Returns an iterator to the first element in the map
end() – Returns an iterator to the theoretical element that follows last element in the
map
size() – Returns the number of elements in the map
max_size() – Returns the maximum number of elements that the map can hold
empty() – Returns whether the map is empty
pair insert(keyvalue, mapvalue) – Adds a new element to the map
erase(iterator position) – Removes the element at the position pointed by the iterator

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.


Object Oriented Programming Lab

erase(const g)– Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map

Examples:
Input : map mymap;
mymap['a'] = 1;
mymap['a'];
Output : 1
Input : map mymap;
mymap["abcd"] = 7;
mymap["abcd"];
Output : 7

//Sample Program
#include <map>
#include <iostream>
#include<string>
usingnamespacestd;
intmain()
{
// map declaration
map<int,string>mymap;
// mapping integers to strings
mymap[1] = "Hi";
mymap[2] = "This";
mymap[3] = "is";
mymap[4] = "DYP";
// using operator[] to print string
// mapped to integer 4
cout<<mymap[4];
return0;
}
Output:
DYP

CONCLUSION: Thus, program in C++ to use map associative container inheritance is


successfully studied and implemented.

Dept. of AI & DS DYPCOE, Akurdi, Pune-44.

You might also like