0% found this document useful (0 votes)
319 views118 pages

Programming Methodology

This document discusses manipulators and type casting in C++. It defines manipulators as functions that modify input/output streams without changing variable values. There are parameterized manipulators like setw() and non-parameterized ones like endl. Type casting operators like static_cast, dynamic_cast, const_cast, and reinterpret_cast allow converting between data types. The document also covers functions, function prototypes, and the differences between call by value and call by reference.

Uploaded by

saniya khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
319 views118 pages

Programming Methodology

This document discusses manipulators and type casting in C++. It defines manipulators as functions that modify input/output streams without changing variable values. There are parameterized manipulators like setw() and non-parameterized ones like endl. Type casting operators like static_cast, dynamic_cast, const_cast, and reinterpret_cast allow converting between data types. The document also covers functions, function prototypes, and the differences between call by value and call by reference.

Uploaded by

saniya khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 118

Programming methodology

Unit :1
Manipulators and type cast operator:

Manipulators: manipulators are helping functions that can modify the input/output
stream. It does not mean that we change the value of a variable, it only modifies
the I/O stream using insertion (<<)and extraction(>>)operators.
1. manipulators are special functions that can be included in the I/O statement to
alter the format parameters of a system.
2.manipulators are operators that are used to format the data display.
3. to access manipulators, the file iomanip.h should be included in the program.
For example, if we want to print the hexadecimal value of 100 then we can print it
as:
Cout<<setbase(16)<<100
Types of manipulators : there are various types of manipulators:
1. manipulators without arguments: the most important manipulators defined by
the IOStream library are provided below.
(*) endI: it is defined in ostream. It is used to enter a new line and after entering a
new line it flushes(i.e. it forces all the output written on the screen or in the file) the
output stream.
(*) WS: it is defined in stream and is used to ignore the whitespaces in the string
sequence.
(*)ends: it is also defined in iostream and it inserts. Typically works with std::
iostream, when the associated output buffer needs to be null-terminated to be
processed as a C string.
(*) flush: it is also defined in iostream and it flushes the output stream, i.e. it forces
all the output written on the screen or in the file. Without flush, the output would
be the same, but may not appear in real-time.
Example: my copy
Manipulator with argument :some of the manipulators are used with the argument
like setw(20), setfill(*) and many more.these are all defined in the header file. If you
want to use these manipulator then we must include this header file in our
program. For example, you can use following manipulators to set minimum width
and fill the empty space with any character you
want:std::cout<<std::setw(6)<<std::setfill(*);
(*)some important manipulators in <iomanip> are:
1. setw(val): it is used to set the field width in output operations.
2. setfill(c): it is used to fill the character ‘c’ on output stream.
3. setprecision(val): it set val as the new value for the precision of floating-point
values.
4. setbase(vali): it is used to set the numeric base value for numeric values.
5. setiosflags(flag): it is used to set the formal flags specified by parameter mask.
6. resetiosflags(m): it is used to reset the formal flags specified by parameter mask.
(*) some imp manipulators in <ios> are:
1. showpas: it forces to show a positive sign on positive numbers.
2.noshowpas: it forces not to write a positive sign on positive numbers.
3. showbase: it indicates the numeric base of numeric values.
4. uppercase: it forces uppercase letters for numeric values.
5. no uppercase: it forces lowercase letters for numeric values.
6. fixed; it uses decimal notation for floating-point values.
7. scientific: it uses scientific floatinf-point motation.
8. hex: read and write decimal values for integers and it works same as the setbase.
9. dec: read and write decimal values for integers i.e. setbase(10).
10. oct: read and write octal values for integers i.e. setbase(10).
11. left: it adjusts output to the left.
12. right: it adjusts output to the right.
There are 2 types of manipulators used generally
1. Parameterized
2. Non-parameterized.

1. parameterized manipulators:
Manipulator meaning
Setw(int n ) to set field width to n
Setprecision(int p) the precision is fixed to p
Setfill(char f) to set the character to be filled
Setiosflags(long l) format flag is set to l.
Resetosflag(long I) removes the flags indicated by I
Setbase(int b)  to set the base of the number to b

2. non parameterized: examples are endI, fixed, showpoint and flush.


1. endI- gives a new line
2. ends- adds null character to close an output string
3.flush- flushes the buffer system
4.ws- omits the leading white spaces present before the first field
5. hex,oct,dec- displays the number in hexadecimal or octal or in decimal format

Type cast operator:


Casting is a technique by which one data type to another data type. The operator
used for this purpose is known as the cast operator. It is a unary operator which
forces one data type to be converts into another data type. It takes on the format.
A cast operator is a unary operator which forces one data type to be converted into
another data type.
C++ supports 4 types of casting:
1. static cast
2. dynamic cast
3. const cast
4. reinterpret cast

1. static cast :
This the simplest type of ast that can be used. It is a compile-time cast. It does
things like implicit conversions between types(such as int to float, or pointer to
void*), and it can also call explicit conversion functions.
2. dynamic cast:
A cast is an operator that converts data from one type to another types. In C++ ,
dynamic casting is mainly used for safe down casting at run time. To work on
dynamic cast there must be one virtual function in the base class. A dynamic cast
works only polymorphic base class because it uses this information to decide safe
down casting.

3. const cast:
Const cast is one of the type casting operators. It is used to change the constant
value of any object or we can say it is used to remove the constant nature of any
object.
Cont cast can be used in programs that have any object with some constant
value which need to be changed occasionally at some point.
4. reinterpret cast:
Reinterpret cast is a type of casting operator it is used to convert a pointer of some
data type into a pointer of another data type, even if the data types before and
after conversion are different.It does not check if the pointer type and data pointed
by the pointer is same or not.
Functions in C++
A function is a set of statement that take input, do come specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same code again and
again for different inputs, we can call the function
In simple terms, a function is a block of code that only runs when it is
called.

The main function:


The main function is a special function. Every C++ program must contain a function
named main. It serves as the entry point for the program. The computer will start
running the code from the beginning of the main function.

Types of main function:


1. without parameters:
// without parameters
Int main() [ … return 0 ;]

2. with parameters:
// with parameters
Int main(int argc, char* const argv[ ] ) { … return 0 ; }
The reason for having the parameters option for the main function is to allow input
from the command line. When you use the main function with parameters, it saves
every group of characters( separated by a space) after the program name as
elements in an array named argv
Since the main function has the return type of int, the
programmer must always have a return statement in the code. The number that is
return statement in the code. The number that is returned is used to inform the
calling program what the result of the program execution was returning 0 signals
that there were no problems.

Function prototyping
The function prototypes are used to tell the compiler about the number of
arguments and about the number of arguments and about the required data types
of a function parameter. It also tells about the return type of the function. By this
information, the compiler cross checks the function signatures before calling it. If
the function prototypes are not mentioned, then the program may be compiled
with some warnings, and sometimes generate some strange output.
If some function is called somewhere, but its body is not defined yet, that is defined
after the current line,then it may generate problems. The compiler does not find
what is the function and what is its signature. In that case, we need to function
prototypes. If the function is defined before then we do not need prototypes.
Example code:
#include<stdio.h>
Void function(int); // prototype
Main() {
Function(50);
}
Void function(int x) {
Printf(“ the value of x is: %d”,
}

Output: the value of x is : 50


Call by reference :
Call by reference is also a method of parameter passing . in this method address or
reference is passed to a function .The call by reference parameters is also known as
the pointer variable. The original value of the function changes with a call by
reference. In languages such as C++ or java, call by reference is preferred to call by
value.

Call by value:
Call by value is known as the method for parameter passing. In this method of
calling by value, the actual parameter’s value is copied in the formal parameters. In
this, a different memory is allocated for each type of parameter. The advantage of
using the call by value method is that the original variable does not change with the
change in calling by value.
This method makes it impossible to change or modify the actual
parameter’s value by using a formal parameter. The actual value of this actual
argument is not varied either.

Que 1.Difference b/w call by value and call by reference :


Ans : 1 call by value call by reference
1. copying variables pass values 1. Values are passed by coping the
Address of the variables.
2. copies are passed 2. Variable is passed.
3. changes do not reflect the 3. Changes affect the variable of
Original function. The function.
4.the actual variable 4.The actual variable can be modified
Can not be changed.
5.used in C++, PHP 5. Used in java, C++, etc.
C#, etc.

Call by address:
Call by address is a way of calling a function in which the address of the actual
arguments is copied to the formal parameters. In the call by address method, both
actual and formal parameters indirectly share the same variable.
In this type of call mechanism, pointer variables are used as formal parameters.
The formal pointer variable holds the address of the actual parameter, hence the
changes done by the formal parameter is also reflected in the actual parameters .

Return by reference :
A C++ function can return a reference in a similar way as it returns a pointer. When
a function returns a reference .it means, it returns an implicit pointer to its return
value. Return by reference is very different form call by reference. Functions behves
a very imp role when variable or pointers are returned as reference .

Inline function:
C++ provides inline function to reduce the function call overhead. An inline function
is a function that is expanded in line when it is called. When the inline function is
called whole code of the inline function gets inserted or substituted at the point of
the inline function call/ this substitution is performed by the C++ compiler at
compile time. An inline function may increase efficiency if it is small.
Advantages of inline function:
1. function call overhead doesn’t occur.
2. it also save the overhead of a return call form a function
3. it also save the overhead of puch/pop variable on the stack when a function is
called.

Default argument:
A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the calling function doesn’t provide a
value for the argument . in case any value is passed, the default value is overridden.
Advantages of default value:
1. it helps in reducing the size of a program.
2. it provides a simple and effective programming approach.
3. default argument improve the consistency of a program.

Constant argument :
A constant argument is the one whose modification cannot take place by the
function. Furthermore, in order to make an argument constant to a function, the
use of a keyword const can take place like-int sum ( const int a , const int b).
Moreover, the qualifier const in the function prototype tells the compiler that
modification of the argument must not take place by the function.

Function overloading in C++:


Function overloading is a feature of object-oriented programming when two or
more functions can have the same name but different parameters. when a function
name is overloaded with different job it is called function overloading . in function
overloading “function” name should be the same and the arguments should be
different .
If multiple functions having the same name but parameters of the functions
should be different is known as function overloading .
Function in its array copy me he

Unit : 6
Graph:
Que: what is graph ADT
A graph is an abstract data type(ADT) that consists of a set of object that are
connected to each other via links. These objects are called vertices and the links are
called edges. In other word, A graph is a non-linear data structure consisting of
vertices and edges.

Usually a graph is represented as G= {V,E}


Where G is the graph space, V is the set of the vertices and E is the set of edges. If E
is empty, the graph is known as forest.
Before we proceed further, let’s familiarize ourselves with some important terms:
1. vertex: A graph G={V,E} consists of a set of object V={v1, v2, ...} whose elements
are called vertices (or points or nodes) . each nodes of the graph is represented as a
vertex and also each points of the graph is represented as a vertex.

2. edges: A graph G={V,E} consists of a set of object E={e1,e2,...} whose elements


are called edges( or lines or branches) . each lines of the graph is represented as a
edges and also each branches of the graph is represented as a edges.
3. Adjaceny: two node or vertices are adjacent if they are connected to each other
through an edge. If the following example, B is adjacent to A,C is adjacent to B, and
so on.

4. path : path represents a sequence of edges between the two vertices. In the
following example, ABCD represents a path from A to D.

Representation of graph:
While representing graphs, we must carefully depict the element (vertices and
edges) present in the graph and the relationship between them. Pictorially, a graph
is represented with a finite set of nodes and connecting links between them.
However, we can also represent the graph in other most commonly used ways like:
1. Adjacency Matrix
2. Adjacency list
1. Adjacency matrix:
The adjacency matrix is a V*V matrix where the values are filled with either 0 or 1 .
1. Adjacency matrix is a sequential representation.
2. it is used to represent which nodes are adjacent to each other i.e., is there any
edge connecting nodes to a graph.
3. if there is any weighted graph then instead of 1s or 0s, we can store the weight of
the edge.

2. adjacency list: the adjacency list is a list of the vertices directly connected to the
other vertices in the graph.
1. adjacency list is a linked representation
2. adjacency list save a lot of space.
3. we can easily insert or delete as we use linked list.
Types of graphs:
There are two basic types of graph
1. directed graph
2. undirected graph

Directed graph: A directed graph (or in short a diagraph) as the name suggests,
consists of edges that possess a direction that goes either away from a vertex or
towards the vertex. Undirected graph have edges that are not directed at all.
Diagram copy mehe

Spanning tree:
A spanning tree is a subset of an undirected graph that contains all the vertices of
the graph connected with the minimum number of edges in the graph.
1. spanning tree does not have any circle.
2. any vertex can be reached from any other vertex.
Example : the following path, the highlighted edges form a spanning tree.
Diagram copy mehe
Shortest path:
The shortest path in a graph is defined as the minimum cost route from one vertex
to another. This is most commonly seen in weighted graph but are also applicable
to undirected graphs.
A popular real-world application of finding the shortest path
in a graph is a map. Navigation is made easier and simpler with the various shortest
path algorithms where destination are considered vertices of the graph and route
are the edges. The two common shortest path algorithms are:
1. dijkstra’s shortest path algorithms
2. bellman ford’s shortest path algorithms.
Example copy mehe graph ka

Operations of graph:
The primary operations of a graph include creating a graph with vertices and
edges, and displaying the said graph. However, one of the most common and
popular operation performed using graphs are traversal, i.e. visiting every vertex of
the graph in a specific order.
There are two types of traversal in graphs
1. depth first search traversal.
2. breadth first search traversal.

1. depth first search traversal.


depth first search is a traversal algorithm that visits all the vertices of a graph in the
decreasing order of its depth. In this algorithm, an arbitrary node is chosen as the
starting point and the graph is traversed back and forth by making unvisited
adjacent nodes until all the vertices are marked.
The DFS traversal used the stack data structure to keep track of the
unvisited nodes.

2.breadth first search traversal:


breadth first search is a traversal algorithms that visits all the vertices of a graph
present at one level of the depth before moving to the next level of depth. In this
algorithm, an arbitrary node is chosen as the starting point and the graph is
traversed by visiting the adjacent vertices on the same depth level and marking
them until there is no vertex left.
The DFS traversal uses the queue data structure to keep track of the
unvisited nodes.
Hashing :
Hashing is a technique to convert a range of key values into a range of indexes of an
array. We are going to use modulo operator to get a range of key values. Consider
an example of hash table of size 20, and the following items are to be stores. Item
are in the (key, value) format.
Iska diagram copy me he or table bhi copy mehe

Definition : 2
Hashing is a technique or process of mapping keys, and values into the hash table
by using a hash function. It is done for faster access to elements. The efficiency of
the has table used.
Let a hash function H(x) maps the value x at the index x%10 in an array. For example
if the list of values is [11,12,13,14,15] it will be stored at positions { 1,2,3,4,5} in the
array or hash table respectively.
Iska diagram copy me he

Hash table:
Hash table is a data structure which stores data in an associative manner. In a hash
table, data is stored in an array format, where each data value has its own unique
index value. Access of data becomes very fast if we know that index of the desired
data.
Thus, it becomes a data structure in which insertion and search operations
are vary fast irrespective of the size of the data. Hash tables uses an array as a
storage medium and uses hash technique to generate an index where an element is
to be inserted or is to be located from.
Hash table:
Table and diagram copy me he

Hash function:
A hash function is a mathematical function that converts a given input value into a
resulting hash value. A hash function can be used to generate a checksum for data,
index data in a data base, or encrypt data.
In data structures, a hash function is used to
calculate the hash value of a key, which is then used to store and retrieve the
corresponding data.
Hash function are often used in conjunction with an array,
where the hash value is used as an index in the array.

Types of hash function:


There are many hash functions that use numeric or alphanumeric keys. This article
focuses on discussing different hash function.
1. division methods
2. mid square method
3. folding method
4. multiplication method
1. division method:
This is the most simple and easiest method to generate a hash value. The hash
function divides the value k by M and then uses the remainder obtained.
Formula:
H(k)= k mod M
Here, k is the key value and
M is the size of the hash table

2. mid square method:


The mid square method is a very good hashing method. It involve two steps to
continue the hash value:
1. square the value of the key k i.e.k2
2. extract the middle r digits as the hash value.
Formula: H(k)=h(k*K)
Here, k is the key value and

3. digit folding method:


This method involves two steps:
1. divide the key value k into a number of parts i.e., k1,k2,k3,......kn, where each
part has the same number of digits except for the last part that can have lesser
digits than the other parts.
2. add the individual parts. The hash values is obtained by ignoring the last carry if
any.
Formula:
K=k1,k2,k3,k4....kn
S= k1+k2+k3+k4+....+kn
H(K)=s
Here ,
s is obtained by adding the parts of the key k.
4. multiplication method:
This method involves the following steps:
1. choose a constant value A such that o<A<1.
2. multiply the key value with A
3. extract the fractional part of kA
4. multiply the result of the above step by the size of the hash table i.e., M.
5. the resulting hash value is obtained by taking the floor or the result obtained in
step 4.
Formula:
H(k) = floor (M (KA mod 1)
Here,
M is the size of the hast table
K is the key value
A is a constant value.

Over flow handling:


An overflow occurs at the time of the home bucket for a new pair(key, element ) is
full.
We may tackle overflows by
Search the hash table in some systematic manner for a bucket that is not full
(!) linear probing(linear open addressing)
(!) quadratic probing
(!) random probing
Eliminate overflows by allowing each bucket to keep a list of all pairs for which it is
the home bucket
(!) array linear list
(!) chain
Open addressing is performed to ensure that all elements are stores directly into
the hash table, thus it attempt to resolve collisions implementing various methods.
Linear probing is performed to resolve collisions by placing the data into the next
open slot in the table.

Performance of linear probing:


1. worst-case find/insert/earse time is 0(m), where m is treated as the number of
pairs in the table
2. this occurs when all pairs are in the same cluster.

Problem of linear probing:


1. identifiers are tending to clutser together
2. adjacent clusters are trending to coalesce
3. increase or enhance the search time

Quadratic probing:
Linear prbing searches buckets (H(x)+i2)%b; H(x) indicates hash function of X
Quadratic probing implements a quadratic function of I as the increment.
Examine buckets H(X) , H(X)+i2)%b, (H(X)-i2)%b, for 1<=i<=(b-1)/2
B is indicated as a prime number of the form 4j+3, j is an integer

Random probing:
Random probing performs incorporating with random number.
H(x) : = (H’(X)+S(i) % b
S(i) is a table along with size b-1
S(i) is indicate as a random permutation of integers [1, b-1].
Sorting:
Sorting refers to arranging data in a particular format. Sorting algorithm specifies
the way to arrange data in a particular order. Most common orders are in numerical
or lexicographical order.
A sorting algorithm is used to rearrange a given array or list of elements according
to a comparison operator on the elements. The comparison operator is used to
decide the new order of elements in the respective data structure .
For example: the below list of characters is sorted in increasing order of their ASCII
values. That is , the character with a lesser ASCII value will be placed first than the
character with a higher ASCII value.
2 1 4 3
Unsorted array

1 2 3 4
Array sorted in ascending order

4 3 2 1
Array sorted in descending order
Sorting algorithm:
1.Bubble sort
2. selection sort
3. insertion sort
4. quick sort
5. merge sort

1. bubble sort:
Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order. This algorithm is not suitable for
large data as its average and worst case time complexity is quite high.

Que 1. Where is the bubble sort algorithm used


Ans 1. Due to its simplicity, bubble sort is often used to introduce the concept of a
sorting algorithm
In computer graphics, it is popular for its capability to detect a tiny error
(like swap of just two elements) in almost-sorted arrays and fix it with just linear
Complexity(2 N).
Advantages :
1. bubble sort is easy to understand and implement
2. it does not require any additional memory space
3. its adaptability to different types of data
4. it is a stable sorting algorithm
Disadvantage:
1. bubble sort has a time complexity of O(n^2) which makes it very slow for large
data sets.
2. it is not efficient for large data sets, because it requires multiple passes through
the data.

2. selection sort:
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element form the unsorted portion of the list and
moving it to the sorted portion of the list. The algorithm repeatedly selects the
smallest (or largest) element form the unsorted portion of the list and swap it with
the first element of the unsorted portion. This process is repeated for the remaining
unsorted portion of the list until the entire list is sorted. One variation of selection
sort is called ”bidirectional selection sort” which goes through the list of element by
alternating between the smallest and largest element , this way the algorithm can
be faster in some case.
Advantage :
1. simple and easy to understand
2. work well with small datasets.
3. it is adaptable to various types of data type
4. it is easy to modify to sort in ascending or descending order.
5. it does not require any special memory or auxiliary data structures, making it a
lightweight solution.
6.It is easy to understand, making it a popular choice for teaching purposes.
Disadvantages:
1. selection sort has a time complexity of O(n^2) in the worst and average case
2. does not work well on large datasets.
3. it has poor cache performance
4.not a good choice for large data set with slow RAM
5.selection sort has poor cache performance and hence it is not cache friendly.
3.insertion sort:
Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and as unsorted
part values from the unsorted part values from the unsorted part are picked and
placed at the correct position in the sorted part.
Characteristic :
1. this algorithm was one of the simplest algorithm with simple implementation
2. basically, insertion sort is efficient for small data values
3. insertion sort is adaptive in nature

Que 1. When is the insertion sort used


Ans 1. Insertion sort is used when number of elements is small. It can also be useful
when input array is almost sorted. Only few elements are misplaced in complete big
array.

4. merge sort:
Merge sort is defined as a sorting algorithm that works by dividing an array into
smaller subarrays, sorting each subarray, back together to form the final sorted
array.
In simple term, we can say that the process of merge sort is to divide the array
into two halves, sort each half, and then merge the sorted halves back together.
This process is repeated until the entire array is sorted.

5. quick sort:
Quick sort is a sorting algorithm based on the divide and conquer algorithm that
picks an element as a pivot and partitions the given array around the picked pivot
by placing the pivot in its correct position in the sorted array.
Advantages:
1. it is a divide-and-conquer algorithm that makes it easier to solve problems
2. it is efficient on large data sets
3. it has low overhead, as it only requires a small amount of memory to function

Disadvantages:
1. it has a worst-case time complexity of O(N2), which occurs when the pivot is
chosen poorly.
2.it is not a good choice for small data sets

Comparison based sorting:


In comparison based sorting, element of an array are compared with each other to
find the sorted array.
1. bubble sorting and insertion sort:
Average and worst case time complexity:n^2
Best case time complexity: n when array is already sorted.
Worst case: when the array is reverse sorted.

2. selection sort:
Best average and worst case time complexity : n^2 which is independent of
distribution of data

3. merge sort: Best average and worst case time complexity : nlogn which is
independent of distribution of data.

4. quick sort: it is a divide and conquer approach with recurrence relation:


T(n)= T(K)+T(N-K-1) + cn

1. worst case: when the array is sorted or reverse sorted, the partition algorithm
divides the array in two sub arrays with 0 and n-1 elements. Therefore,
T(n)=T(0)+ T(n-1)+cn
Solving this we get, T(n)=0(n^2)

2. best case and average case: on average, the partition algorithm divides the array
in two sub arrays with equal size. Therefore,
T(n)=2T(n/2) + cn
Solving this we get, T(n)=0(nlogn)

Non-comparison based sorting: in non-comparison based sorting, elements of array


are not compared with each other to find the sorted array.

1. Radix sort: best average and worst case time complexity :nk where k is the
maximum number of digits in elements of array.

2. count sort: best, average and worst case time complexity: n+k where k is the size
of count array.

3. bucket sort: best and average time complexity: n+k where k is the number of
buckets. Worst case time complexity: n^2 if all elements belong to same bucket.
Search trees:
Binary search trees : binary search tree (BST) is a special type of binary tree in which
the left child of a node has a value less than the node’s value and the right child has
a value greater than the node’s value. This property is called BST property and it
makes it possible to efficiency search, insert, and delete elements in the tree.
Binary search tree is a node based binary tree data structure which has the
following properties:
1. the left sub tree of a node contains only nodes with keys lesser than the nodes
key.
2. the right sub tree of a node contains only nodes with keys greater than the
node’s keys.
3. the left and right subtree each must also be a binary search tree. There must be
no duplicate nodes( BST may have duplicate values with different handling
approaches)
Diagram copy mehe

Handling approaches for duplicate values in the BST


1. you can not allow the duplicated values at all.
2. we must follow a consistent process throughout i.e. either store duplicate value
at the left or store the duplicate value at the right of the root, but be consistent
with your approach.
3. we can keep the counter with the node and if we found the duplicate value, then
we can increment the counter.

AVL trees:
An AVL tree defined as a self-balancing Binary search tree(BST) where the difference
B/W heights of left and right subtrees for any node cannot be more than one.
The difference B/W heights of left and right subtrees for any node is known as the
balance factor of the node.
Example copy mehe
The above tree is AVL because the difference B/w the heights to left and right
subtrees for every node are less than or equal to 1.
Application of AVL tree:
1. it is used to index huge records in a database and also to efficiently search in that
2. for all types of in memory collections, including sets and dictionaries, AVL trees
are used.
3. databases application, where insertions and deletions are less common but
frequent data lookups are necessary
4. software that needs optimized search.(OS)
5. it is applied in corporate areas and storyline games.
6. most in memory sets and dictionaries are stored using AVL trees.
7. it may be used in games and plotlines as well.
8. a balanced BST called an AVL tree uses rotation to keep things balanced.
9. AVL trees are mostly used for in memory sorts of sets and dictionaries.
Advantages of AVL:
1.AVL tree can self balance themselves
2. it is surely not skewed
3. it provides faster lookups than red-black trees.
4. better searching time complexity compared to other tress like binary tree.
5. height cannot exceed log(N) , where, N is the total number of nodes in the tree.

Disadvantages of AVL:
1. It is difficult to implement
2. it has high constant factor for some of the operations
3. less used compared to red-black trees.
4. take more processing for balancing

Traversal tree:
Traversal is a process to visit all the nodes of tree and may print their values too.
Because, all nodes are connected via edges(links) we always start from the root
(head) node. This is, we cannot randomly access a node in a tree. There are three
ways which we use to traverse a tree
1. in-order traversal
2. pre-order traversal
3. post-order
Generally, we traverse a tree to search or locate a given item or key in the tree or to
print all the values it contains.

In-order traversal:
In this traversal method, the left subtree is visited first, then root and later the right
sub-tree. We should always remember that every node may represent a subtree
itself.
If a binary tree is traversed in-order, the output will peoduce key values in an
ascending order.
Diagram copy mehe
We start from A, and following in-order traversal, we move to its left subtree B.B is
also traversal in-order. The process goes on until all the nodes are visited. The
output of in-order traversal of this tree will be:
DBEAFCG

Pre-order traversal:
In this traversal method, the root node is visited first, then the left subtree and
finally the right subtree.
Diagram copy mehe
We start from A, and following pre-order traversal, we first A itself and then move
to its left subtree B.B is also traversed pre-order. The process goes on until all the
nodes are visited . the output of pre-order traversal of this tree will be:
ABDECFG

Post order traversal:


In this traversal method. The root node is visited last, hence the name. First we
traverse the left subtree, then the right subtree and finally the root node.
Diagram copy mehe

We start from A, and following pre-order traversal, we first the left subtree B.B is
also traversed post-order. The process goes on until all the nodes are visited. The
output of post-order traversal of this tree will be :
DEBFGCA

Unit : 5
Linked list :

Starring second paragraph


Representation of trees:
A tree is representation of the non-linear data structure. Because it does not store
in a sequential manner. A tree can be shown using different user-defined or
primitive types of data. It is a hierarchical structure as elements in a tree are
arranged in multiple levels. In the tree data structure , the topmost node is known
as a root node. Each node contains some data, and data can be of any type.
What is binary tree:
Binary tree is defined as a tree data structure where each node has at most 2
children. Since each element in a binary tree can have only 2 children, we typically
name them the left and right child. The binary tree is a special type of tree.

Properties of binary tree:


1. each node in a binary tree can have at most two child nodes
2. the node at the top of the tree is called the root node
3.the height of a binary tree is defined as the number of edges from the root node
to the deepest leaf node
4. in a full binary tree , every node except the leaves has exactly two children
5. the in-order, pre-order and post order traversal of a binary tree are three
common ways to traverse the tree
6. in a complete binary tree, every level of the tree is completely filled except for
the last level, which can be partially filled
7. in a balanced binary tree, the height of the left and right subtrees of every node
differ by at most 1

Representation of binary tree


A binary tree can be represented using a linked list and also using an array,
representation of this tree, using both(array and linked list) is explained below.

Array representation:
The binary tree can be represented using an array of size 2n+1 if the depth of the
binary tree is n. If the parent element is as the indexp, then the left child will be
stored in the index (2p)+1, and the right child will be stored in the index(2p)+2
The array representation of the above binary tree is:
As in the above binary tree , A was the root node , so it will be stored in the 0 th
index. The left child of A will be stored in the 2(0)+1 that is equal to the 1 st location.
So, B is stored in index 1. And, similarly the right child of A will be stored in the
2(0)+2index. For every node, the left and right child will be stored accordingly.
Linked list representation:
For the linked list representation we will be using the doubly linked list which has
two pointers so that we can point to the left and right children of a node of a binary
tree. NULL is given to the pointer as the address when no child is connected it.

Threaded binary tree:


A threaded binary tree is a type of binary tree data structure where the empty left
and right child pointers in a binary tree are replaced with threads that link nodes
directly to their in order predecessor or successor, thereby providing a way to
traverse the tree without using recursion or a stack.
Threaded binary trees can be useful when space is a concern,
as they can eliminate the need for a stack during traversal. However, they can be
more complex to implement than standard binary trees.

There are two type of threaded binary trees:


1. single threaded: where a NULL right pointers is made to point to the inorder
successor (if successor exists)
2.Double threaded: where both left and right NULL pointers are made to point to
inorder predecessor and inorder successor respectively. The predecessor threads
are useful for reverse inorder traversal and postorder traversal.
The threads are also useful for fast accessing ancestor of a node.
Following diagram show an example single threaded binary tree. The dotted lines
represent threads.

What is linked list:


A linked list is a linear data structure which looks like a chain of nodes, where each
node is a different element. Unlike arrays, linked list elements are not stored at a
contiguous location.
It is basically chain of nodes, each node contain information such as data and a
pointer to the next node in the chain. In the linked list there is a head pointer,
which points to the first element of the linked list, and if the list is empty then it
simply points to null or nothing.
Types of linked lists:
There are mainly three types of linked lists:
1. single-linked list
2. double-linked list
3. circular linked list

1. single linked list:


Traversal of item can be done in the forward direction only due to the linking of
every node to its next node.
Diagram copy mehe

Commonly used operations on singly linked list:


The following operations are performed on a single linked list
1. insertion: the insertion operation can be performed in three ways. They are as
follow:
3 operations copy mehe iske

2. deletion: the deletion operation can be performed in three ways. They are as
follows:
3 operations copy mehe iske

3. search: it is a process of determining and retrieving a specific node either from


the front , the end or anywhere in the list.
4. display: this process displays the elements of a single-linked list.

2. double linked list:


Traversal of items can be done in both forward and backward directions as every
node contains an additional prev pointer that points to the previous node.
Diagram copy mehe

Commonly used operations on double-linked list:


In a double linked list, we perform the following operations
1. Insertion: the insertion operation can be performed in three ways as follow:
4 operations copy mehe iske
2.Deletion: the deletion operation can be performed in three ways as follows:
3 operations copy mehe iske

3. display: this process displays the elements of a double-linked list.

3 circular linked list:


A circular linked list is a type of linked list in which the first and the last nodes are
also connected to each other to form a circle, there is no NULL at the end.
Diagram copy mehe
Commonly used operation on circular linked list:
1. insertion: the insertion operations can be performed in three ways:
4 operations copy mehe iske

2. deletion: the deletion operation can be performed in three ways:


3 operations copy mehe iske

3. display: this process display the elements of a circular linked list.

Linked list Vs. Array


Array : linked list
1. arrays are stored in contiguous 1. LL Are not
2. fixed in size 2. Dynamic in size
3.memory is allocated at complete 3. Memory is allocated at run time
Time
4.usses less memory than linked list 4. Uses more memory because it
Stores both data & address of next
Node.
5. element can be accessed easily 5. Element accessing requires the
Traversal of whole linked list
6. insertion and deletion operation 6. Insertion & deletion operation
Takes time is faster.

Advantage LL:
1. dynamic nature: LL are used for dyanamic memory allocation
2. memory efficient: memory consumption of a linked list is efficient as its size can
grow or shrink dynamically according to our requirements , which means effective
memory utilization hence, no memory wastage.
3. ease of insertion and deletion: insertion and deletion of nodes are easily
implemented in a linked list at any position.
4. implementation : for the implementation of stacks and queue and for the
representation of trees and graphs
5. the linked list can be expanded in constant time.

Disadvantage :
1. memory usage: the use of pointers is mor in linked list hence , complex and
requires more memory.
2. accessing a node: random access is not possible due to dynamic memory
allocation.
3. search operation costly : searching for an element is costly and requires 0(n)time
complexity
4. traversing in reverse order: traversing is more time-consuming and reverse
traversing is not possible in singly linked lists.

Circular doubly linked list:


Circular doubly lined list has properties of both doubly linked list and circular linked
list in which two consecutive elements are linked or connected by the previous and
next pointer and the last node points to the first node by the next pointer and also
the first node points to the last node by the previous pointer.
Diagram ke baad

Note: we will be using the singly circular linked list to represent the working of the
circular linked list.

Header linked list:


A header node is a special node that is found at the beginning of the list. A list that
contains this type of node, is called the header linked list. This type of list is useful
when information other than that found in each node is needed.
Types of header linked list
1. grounded header linked list:
It is a list whose last node contains the NULL pointer. In the header linked list the
start pointer always points to the header node. Start next=NULL indicates that
the grounded header linked list is empty. The operations that are possible on this
type of linked list are insertion , deletion, and traversing .
2. circular header linked list:
A list in which last node points back to the header node is called circular linked list.
The chains do nit indicates first or last nodes. In this case, external pointer provide a
frame of reference because last node of a circular linked list does not contain the
NULL pointer. The possible operations on this type of linked list are insertion,
deletion and traversing.

3 concatenate
The term concatenate is defined as an operation to join or link something together .
the same concept is taken to define the operation of concatenation in computer
programming . computer programmers commonly use concatenation for joining
end-to-end character strings.
For example , the concatenation of “Hello” + “world” will fetch you the output as
“Helloworld”. or the coders can concatenate two or more strings in the program
using the ‘+’ (plus) operator.

Unit: 3
Inheritance in C++:
Inheritance is a feature or process in which, new classes are created from the
exisiting classes. The new class created is called derived classes or child class and
the exisiting class is known as the base class or parent class . the derived class now
is said to be inherited from the base class.
When we say derived class inherits the base class, it
means , the derived class inherits all the properties of the base class, without
changing the properties of base class and my add new features to its own. These
new features in the derived class will not affect the base class. The derived class is
the specialized class for the base class.
1. sub class: the class that inherits properties from another class is called subclass or
derived class.
A class that is created from an existing class. The derived class inherits
all membes and members function of a base class. The derived class can have more
functionality with respect to the base class and can easily access the base class. A
derived class is also called a child class or subclass.

2. super class: the class whose properties are inherited by a subclass is called base
class or super class.
A base class is a class in object-oriented programming language
from which other classes are derived. the class which inherits the base class has all
members of a base class as well as can also have some additional properties. The
base class members and member functions are inherited to object of the derived
class. A base class is also called parent class or super class.
Types of inheritance:
1. single inheritance: in single inheritance , a class is allowed to inherit from only
one class .i.e. one subclass is inherited by one base class only.
Diagram copy mehe

2. multiple inheritance: multiple inheritance is a feature of C++ where a class can


inherit from more than one class. i.e. one subclass is inherited from more than one
base class.
Diagram copy mehe

3. multilevel inheritance: in this type of inheritance, a derived class is created from


another derived class.
Diagram copy mehe

4. hierarchical inheritance: in this type of inheritance, more than one sub class is
inherited from a single base class, i.e. more than one derived class is created from a
single base class.
Diagram copy mehe

5. hybrid inheritance : hybrid inheritance is implemented by combining more than


one type of inheritance. For example: combining hierarchical inheritance and
multiple inheritance.
Below image show the combination of hierarchical and multiple inheritances:
Diagram copy mehe

Making a private member inheritable:


A private member of a class cannot be inherited and , as a result, is not available for
the derivative class directly. What happens if private data is to be inherited by a
derived class?
C++ provides a third, protected, visibility modifier for restricted inheritance use. A
member declared protected is accessible by the functions of the member in his class
and any class immediately deriving form it. It is not accessible by functions outside
of both classes.
A class is now able to use all 3 modes of visibility as shown below:
Class a
{
Private :
Int a;
---
Protected:
Int b;
--
Public:
//members of the class
}

Virtual base class:

Virtual base class are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using
multiple inheritances.
Program bhi copy mehe

Abstract class:
Abstract classes are used to express broad concepts form which more concrete
classes can e derived. an abstract class type object cannot be created. A abstract
class is a class that is designed to be specifically used as a base class. For example, a
vehicle parent class with truck and motorbike inheriting from it is an abstraction
that easily allows more vehicle to be added.

Constructor in derived class in C++:

1.We can use constructor in derived classes in C++


2. if the base class constructor does not have any arguments, there is no need for
any constructor in the derived class
3. but if there are one or more arguments , in the base class constructor , derived
class need to pass argument to the base class constructor.
4. if both base and derived classes have constructors , base class constructor is
executed first.

Nesting of class :
A nested class is a class which is declared another enclosing class. A nested class is a
number and as such has the same access rights as any other member. The member
of an enclosing have no special access to members of a nested class; the usual
access rules shall be obeyed.
A nested class is a class that is declared in another class. The nested class
is also a member variable of the enclosing class and has the same access rights as
the other members. However, the member functions of the enclosing class have no
special access to the members of a nested class.
Program bhi copy mehe

Operator overloading :
Operator overloading is a compile-time polymorphism. It is an idea of giving special
meaning to an existing operator in C++ without changing its original meaning
In C++ , we can make operators work for user -defined classes. This means
C++ has the ability to provide the operators with a special meaning for a data type,
this ability is knwn as operator overloading.
For example: Program bhi copy mehe

Operators that can be overloaded:


We can overload:
1. unary operator
2. binary operator
3. special operator ( [] , (), etc).

That cannot be overloaded:


1.Scope resolution operator
2. member selection operator
3. member selection through *

Type conversion:
A type cast is basically a conversion from one type to another. There are two types
of type conversion:
1. implicit type conversion: also known as ‘automatic type conversion’.
1. done by the compiler on its own, without any external trigger form the user.
2. generally takes place when in an expression more than one data type is present.
In such condition type conversion (type promotion) takes place to avoid lose of
data.
3. all the data type of the variables are upgraded to the data type of the variable
with largest data type.
4. it is possible for implicit conversions to lose information, sign can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when lone long
is implicitly converted to float)
Program bhi copy mehe

2. explicit type conversion: this process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type. In
C++ , it can be done by two ways:
1. converting by assignment: this is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful
casting.
2. conversion using cast operator : a cast operator is an unary operator which forces
one data type to be converted into another data type.
C++ supports four type of casting:
1. static cast
2. dynamic cast
3. const cast
4. reinterpret cast
Advantage of type conversion:
1. this is done to take advantage of certain features of type hierarchical or type
representations
2. it helps to compute expressions containing variables of different data types.
Program bhi copy mehe

Polymorphism :
The word “ polymorphism” meas having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one
form. A real-life example of polymorphism is a person who at the same time can
have different characteristics. A man at the same is a father, a husband , and an
employee. So the same person exhibits different behaviour in different situations.
This is called polymorphism. Polymorphism is considered one of the important
features of object-oriented polymorphism.

Types of polymorphism:
1. compile-time poly...
2. runtime poly....
Diagram copy mehe
1. compile time polymorphism: this type of polymorphism is achieved by function
overloading or operator overloading.
A. function overloading: when then are multiple functions with the same name but
different parameters, then the functions are said to be overloaded, hence this is
known as function overloading . functions can be overloaded by changing the
number of arguments or/and changing the type of arguments.
In simple terms, it is a features of object-oriented programming
providing many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name. There are certain rules of
function overloading that should be followed while overloading a function.

Program copy me rahega

2. operator overloading : C++ has the ability to provide the operators with a special
meaning for a data type, this ability is known as operator overloading. For example,
we can make use of the addition operator(+) for string class to concatenate two
strings. We known that the task of this operator is to add two operands. So a single
operator’+’ when placed between integer operands, adds them and when placed
between string operands, concatenate them.
Program copy me rahega

2. runtime polymorphism : this type of polymorphism is achived by function


overriding. Late binding and dynamic polymorphism are other names for runtime
polymorphism. The function call is resolved at runtime in runtime polymorphism,
the compiler determines which function call to bind to the object after deducing it
at runtime.
A. function overriding :
Function overriding occurs when a derived class as a definition for one of the
member functions of the base class. That base function is said to be overridden.
Program copy me rahega

Runtime polymorphism with data members:


Runtime polymorphism can be achieved by data members in C++. Let’s see an
example where we are accessing the filed by reference variable which refers to the
instance of the derived class.
Program copy me rahega
Pointers in C++:
pointers are symbolic representation of addresses. They enable programs to
simulate call by reference as well as to create and manipulated dynamic data
structures. Iterating over elements in array or other data structures is one of the
main use of pointers.
The address of the variable you’re working with is assigned to the
pointer variable that points to the same data type(such as an int or string).

Pointer expressions and pointer arithmetic :


A limited set of arithmetic operations can be performed on pointers which are:
1. incremented(++)
2. decremented(--)
3.an integer may be added to a pointer(+ or +=)
4. an integer may be subtracted form a pointer (- or -=)
4. difference B/W two pointers(p1-p2)

Array name as pointer:


An array name contains the address of the first element of the array which acts like
a constant pointer. It means, the address stored in the array name can’t be
changed. For example , if we have an array named val then val and &val[0] can be
used interchangeably.
Pointer and two dimensional arrays:
1. pointers and two dimensional arrays: in a two dimensional array, we can access
each element by using two subscripts, where first subscript represents the column
number. The elements of 2-D array can be accessed with the help of pointer
notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the
array using the pointer expression *(*arr+i)+j). Now we’ll see how this expression
Can be derived.
Let us take a two dimensional array arr[3][4]:
Diagram copy mehe

Stream c:
A stream is a logical entity that represents a file or device, that can accept input or
output. All input and output functions in standard c, operate on data streams.
Streams can be divided into text, streams and binary streams.
A C++ stream is a flow of data into or out of a program.

C++ stream classes:


In C++ streams refers to the stream of characters that are transferred between the
program thread and I/O.
Stream classes in C++ are used to input and output operations on files and
IO devices. These classes have specific features and to handle input and output of
the program

The iostream.h library hold all the stream classes in the C++ programming
language.
Let’s see the hierarchy and learn about them.
Diagram copy mehe
Now lets learn about the classes of the iostream library.
1. ios class: this class is the base class for all stream classes. The streams can be
input or output streams. This class defines members that are implemented of how
the templates of the class are defined.

2. istream class: the istream class handles the input stream in C++ programming
language. These input stream objects are used to read and interpret the input as a
sequence of characters. The cin handles the input.
3. ostream class: the ostream class handles the output stream in c++ programming
languages. These output stream objects are used to write data as a sequence of
characters on the screen, cout and puts handle the out streams in C++ programming
languages.
Program copy me rahega
Unformatted or formatted I/O:
C++helps you to format the I/O operations like determining the umber of digits to
be displayed after the decimal point, specifying number base etc.
Example :
1. if you want to add+ sign as the prefix of out output,we can use the formatting to
do so:
Stream.setf(ios::showpas)
If input=100, output will be +100

2. if you want to add trailing zeroes in out output to be shown when needed using
the formatting:
Stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
Note : here, stream is referred to the streams defined in C++ like cin, cout, cerr,
clog.
There are two ways to do so:
1. using the ios class or various ios member functions.
2. using manipulators (special functions)

1. formatting using the ios members: the stream has the format flags that control
the way of formatting it means using this setf function, we can set the flags, which
allow us to display a value in a particular format. The ios class declare a bitmask
enumeration called fmtflags in which the values(show base, showpoint , oct, hex,
etc) are defined. These values are used to set or clear the format flags.

Few standard ios class functions are:


1. width(): the width method is used to set the required field width. The output will
be displayed in the given width.

2.presision(): the precision method is used to set the number of the decimal point
to a float value.
3. fill(): the fill method is used to set a character to fill in the blank space of a filed.
4. setf(): the setf method is used to set various flags for formatting output.
5. unsetf(): the unsetf method is used to remove the flag setting
Program copy mehe iska

2. formatting using manipulators : the second way you can alter the format
parameters of a stream is through the use of special functions called manipulators
that can be included in an I/O expression.
The standard manipulators are shown below:
1. boolalpha: the boolalpha manipulators of stream manipulators in C++ is used to
turn on bool alpha flag

2. dec: the dec manipulators of stream manipulators in C++ is used to turn on the
dec flag.

3. endl: the endl manipulators of stream manipulators in C++ is used to output a


newline character
4. and; the and manipulators of stream manipulators in C++ is used to flush the
stream.

5. ends: the ends manipulators of stream manipulators in C++ is used to output a


null.

6. fixed: the fixed manipulator of stream manipulators in C++ is used to turn on the
fixed flag.

7. flush: the flush manipulator of stream manipulators in C++ is used to flush a


stream.

8. hex: the hex manipulators of stream manipulators in C++ is used to turn on hex
flag

9. internet : the internal manipulators of stream manipulators in C++ is used to


turns on internal flag.
10. left: the left manipulator of stream manipulators in C++ is used to turns on the
left flag.

Unformatted I/O operations in C++:


In this article, we will discuss the unformatted input/output operations in C++ using
objects cin and cout for the input and the output of data of various types in possible
because of overloading of operator >> and << to recognize all the basic C++ types.
The operator >> is overloaded in the istream class and operator << is overloaded in
the ostream class.

The general format for reading data from the keyboard:


Cin>>var>>var2>>.....>>var_n;
1 here , var1, var2....varn are the variable names that are declared already.
2. the input data must be separated by white space characters and the data type of
user input must be similar to the data type of the variables which are declared in
the program.
3. the operator>> reads the data character by character and assigns it to the
indicated location.
4. reading of variables terminates when white space occurs or character type occurs
that does not match the destination type.
Program copy mehe

Put() and get() functions:


The class istream and ostream have predefined functions get() and put() to handle
single character input and output operations, the function get() can be used in two
ways, such as get(char*) and get(void) to fetch characters including blank spaces,
newline characters, and tab. The function get(char*) assigns the value to a variable
and get(void) to return the value of the character.
Program copy mehe

Getline() and write() functions:


In C++ the function getline() and write() provide a more efficient way to handle line-
oriented input and output . getline ()function read the complete line of text that
ends with the new line character . this function can be invoked using the cin object.
The reading is terminated by the “\n” (newline) character. The new
character is read by the function, but it does not diaplay it, instead, it is replaced
with a NULL character. After reading a particular string the cin automatically adds
the newline character at end of the string.
The write() function displays the entire line in one go and its syntax is
similar to the getline() function only that here cout objects is used to invoke it.
The key point to rememberis that the write () function does not stop
displaying the string utomatically when a NULL character occurs. If the sixe is
greater than the length of the line then, the write() function displays beyond the
bound of the line.
Program copy mehe

C++ manipulators managing output with manipulators:


The header file iomanip provides a set of functions called manipulators which can
be used to the manipulate the output formats. They provide the same features as
that of the ios(input ouptput system) member functions and flags. Some
manipulators are more convenient to use than their counterparts in the class(input
output system) ios. Such that, two or more manipulators can be used as a chain in
one statement as shown below:
Cout<<manip1<<manip2<<manip3<<item;
Cout<<manip1<<item<<manip2<<item2;
This kind of concatenation is useful when we want to displays several columns of
output. The most commonly used manipulators are shown in table 10.6. the table
also gives their manipulators, we must include the file iomanip in the program.

Manipulators without arguments:


The imp manipulators defined by the header iostrem library are provided below.
Endl: it is defined in header ostrem. It is used for enter a new line and end1 after
entering a new line it flushes the output stream.

Ws: it is defined in header istream and is used for ignore the whitespaces in the
string sequences.

Ends:
Flush: it also defined in header ostream and this flushes the output stream.

Exception handling:
An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstances that arises while a program
is running , such as an attempt to divde by zero.
Exception provide a way to transfer control form one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.

1. thorw: a program throws an exception when a problem shows up. This is done
using a throw keyword.
2.catch: a program catches an extension with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
3. try: a try block identifies a block of code for which particular exception will be
activated. It’s followed by one or more catch blocks.

Unit: 4
Data structure:

What is data structure:


A data structure is a storage that is used to store and organize data. It is way of
arranging data on a computer so that it can be accessed and updated efficiently.
A data structure is not only used for oraganizing the data. It is also used
for processing , retrieving , and storing data. There are different basic and advanced
type of data structures that are used in almost every program or software system
that has been developed. So we must have good knowledge about data structures.

Classification of data structure:


Chart copy me rahega
1. linear data structure: data structure in which data elements are arranged
sequentilay or linearly, where each element is attached to its previous and next
adjacent elements, is called a linear data structure.
Example of linear data structures are array, stack, queue, linked list, etc.
1. static data structure: static data structure has a fixed memory size. It easier to
access the elements in a static data structure.
An example of this data structure is an array.
2. dyamaic data structure: in dynamic data structure, the size is not fixed. It can be
randomly updated during the runtime which may be considered efficient concering
the memory(space ) complexity of the code.
Example of this data structure: are queue, stack, etc.

Non linear data structure: data structure where data elements are not
placed sequentially or linearly are called non-linear data structure . in a non-linear
data structure, we can’t traverse all the elements in a single run only.
Example of non-linear data structure are trees and graphs.
For example: we can store a list of item having the same data-type using the array
data structure.
Diagram copy mehe
This page contains detailed tutorials on different data structure (DS) with topic wise
problems.

Algorithm specification:
The world algorithm means” a set of finite rules or instruction to be followed in
calulatons or other problem-solving operations”or” a procedure for solving a
mathematical problem in a finite number of steps that frequently involves recursive
operations”.
Therefore algorithm refers to a sequence of finite steps to solve a particular
problem.
Uses of the algorithm :
Algorithm play a crucial role in various fields and have many applications. Some of
the key areas where algorithms are used include:
1. computer science
2. mathematics
3.operations research
4. artificial intelligence
5. data science
Needed of algorithm:
1. algorithms are necessary for solving complex problem efficiently and effectively.
2. they help to automate processes and make them more reliable, faster, and easier
to perform.
3. they are used in various fields such computer science , Mathematics, operations
research, artificial intelligence, data science , analyze data etc.
Characteristics of algorithm :
1. clear and unambiguous
2. well-defined inputs
3. well-defined outputs
4. finite-ness
5. feasible
6. language independent
7. input and output
8. definiteness
9. finiteness
10. effectiveness
Properties of algorithms;
1. it should terminate after a finite time.
2. it should produce at least one output
3. it should take zero or more input
4. it should be deterministic means giving the same output for the same input case.
5. every step in the algorithm must be effective. i.e. every step should be effective.

Types of algorithm:
There are several types of algorithm available some important algorithm are:
1. brute force algorithm: it is the simplest approach for a problem. A brute force
algorithm is the first approach that comes to finding when we see a problem.
2. recursive algorithm : a recursive algorithm is based on recursion. In this case, a
problem is broken into several sub-parts and called the same function again and
again.

3. backtracking algorithm: the backtracking algorithm basically builds the solution


by searching among all possible soluiotns. Using this algorithm, we keep on building
the solution following criteria. Whenever a solution fails we trace back to the failure
point and builds on the next solution and continue this process till we find the
solution or all possible solutions are looked after.

4. greedy algorithm: in the greedy algorithm . the solution is built part by part. The
decision to choose the next part is done on the basis that it gives an immediate
benefit. It never considers the choice that had been taken previously some common
problems that can be solved through the greedy algorithm
5.randomized algorithm : in the randomized algorithm, we use a random number. It
helps to decide the expected outcome. The decision to choose the random number
so it gives the immediate benefit.
Some common problems that can be solved through the
randomized algorithm are quicksort: in quicksort we use the random number for
selecting the pivot.

6. sorting algorithm : the sorting algorithm is used to sort data in maybe ascending
or descending order. Its also used for arranging data in an efficient and useful
manner.
Some common problems that can be solved through the sorting algorithm
are bubble sort, insertion sort........and quick sort are examples of the sorting
algorithms.

5. searching algorithms: the searching algorithm is the algorithm that is used for
searching the specific key in particular sorted or unsorted data. Some common
problems that can be solved through the searching algorithm are binary search or
linear search is one example of a searching algorithm .

6. hashing algorithm: hashing algorithm work the same as the searching algorithm
but they contain an index with a key ID i.e. a key-value pair. can be solved through
the hashing algorithm in password verification.
Recursion :
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called a recursion function, certain problems can
be solved quite easily.

Recursive algorithm :
This type of algorithm is based on recursion. In recursion, a problem is solved by
breaking it into sub problems of the same type and calling own sel again and again
until the problem is solved with the help of a base condition. Some common
problem that is solved using recursive algorithms are factorial of a number,
Fibonacci series, tower of Hanoi ,DFS for graph, etc.

Program copy mehe

Data abstraction:
Database system comprise complex data structures. In order to make the system
efficient in terms of retrieval of data, and reduce complexity in terms of usability of
users, developers use abstraction i.e. hide irrelevant details form the users. This
approach simplifies database design.
There are mainly 3 levels of data abstraction:
1. physical : this is the lowest level of data abstraction. It tells us how the data is
actually stored in memory . the access methods like sequential or random acess and
file organization methods like B++ trees and hashing are used for the same .
usability , size of memory, and the number of times the records are factors that we
need to know while designing the database.
Suppose we need to store the details of an employee. Blocks f storage and the
amount of memry used for these purposes are kept hidden from the user.

2. logical : the level comprises the information that is actually stored in the data
bases in the form of tables. It also stores the relationship among the data entities in
relatively simple structures. At this level, the information available to the user at
the view level is unknown.
We can store the various attributes of an employee and relationships, e.g. with the
manager can also be stored.
3. view: this is the highest level of abstraction only a part of the actual databse is
viewed by the users. This level exists to ease the accessibility of the databse by an
individual user. Users view data in the form of rows and columns. Tables and
relations are used to store data. Multiple view of the same databse may exist. Users
can just view the data and interact with the databse, storage and implementation
details are hidden form them.

Example: in case of storing customer data,


Physical level: it will contains block of storages (bytes,GB,TB,etc)
Logical level: it will contain the fields and the attributes of data.
View level: it works with CLI or GUI access of database
Diagram copy mehe
The main purpose of data abstraction is to achieve data independence in order to
save the time and cost required when the database is modified or altered.

Performance analysis:
Performance analysis is a specialised discipline that provides athletes and coaches
with objective information that helps them understand performance. This process is
underpinned by systematic observation, which provide valid, reliable and detailed
information relating to performance .
Representation of single and two dimensional array:
The terms array refers to a collection of common name variables that have a similar
type of data each.
The one-dimensional array basically consists of a list of variables that have the
very same data type. On the other hand, a two dimensional array consists of a list of
arrays that have similar data types.

One dimensional arrays:


A one dimensional array, sometimes known as a single-dimensional array, is one in
which the elements are accessed in sequence. The subscript of a column or row
index will be used to access this type of array. A single subscript, in this case,
represents each element. The itmes are saved in memory in sequential order.

Two dimensional arrays:


The 2D array is originate as matrices which can be represented as the collection of
rows and columns. However, 2D arrays are created to implement a relational
database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.
Difference B/W one dimensional & two dimensional array:
A. one dimensional array b. Two dimensional array
1. a one dimensional array 1. A two dimensional array store an
Stores a single list of various array of various arrays, or a list of
Elements having a similar various lists, or an array of various
Data type. One dimensional array

2. it represent multiple 2. It represents multiple data items


Data items in the form of in the form of a table that contain
A list. Columns and rows.

3.it has only one 3. It has a total of two dimensions


dimensional

4. one can easily receive 4. The parameters that receive it must


It in a pointer, an unsized define an array’s rightmost dimension.
Array, or a sized array.
Triangular arrays:
In mathematics and computing, a triangular array of numbers, polynomials , or the
like, is doubly indexed sequence in which each row is only as long as the row’s own
index. That is, the ith row contains only i elements.

Sparse matrix array linked representations:


A matrix is a two-dimensional data object made of m rows and n columns, therefore
having total m*n values. If most of the elements of the matrix have 0 value, then it
is called a sparse matrix.

Why to use sparse matrix instead of simple matrix:


1. storage: there are lesser non-zero elements than zeroes and thus lesser memory
can be used to store only those elements.

2. computing time: computing time can be saved by logically designing a data


structure traversing only non-zero elements.

Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as


zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes
with non-zero elements. This means storing non-zero elements with triples (row,
column, value).

Sparse matrix representation can be done in many ways following are two common
representations:
1. array representation
2. linked list representation

Method 1: using arrays:


2D array is used to represent a sparse matrix in which there are three rows named
as:
1. row: index of row, where non-zero element is located.
2. columns: index of column, where non-zero element is located.
3. value: value of the non-zero element located at index(row, column)
0 0 3 0 4
0 0 5 7 0  row 0 0 1 1 3 3
0 0 0 0 0 column 2 4 2 3 1 2
0 2 6 0 0 value 3 4 5 7 2 6

Implementations of array: copy mehe


Method 2: linked lists:
In linked list, each node has four fields. These four fields are defined as:
1. row: index of row, where non-zero element is located.
2. column: index of column, where non-zero elements is located.
3. value: value of the non zero element located at index(row, column)
4. next node: address of the next node

Diagram copy mehe


Implementations of array: copy mehe
Other representation :
As a dictionary where row and column numbers are used as keys and values are
matrix entries. This method saves space but sequential access of item is costly.
What is stack:
A stack is a linear data structure in which the insertion of a new element and
removal of an existing element takes place at the same and represented as the top
of the stack.
To implement the stack, it is required to maintain the pointer to the top of
the stack, which is the last element to be inserted because we can access the
elements only on the top of the stack.

LIFO(last in first out):


This strategy states that the element that in inserted last will come out first. You
can take a pile of plates kept on top of each other as a real-life example. The plate
which we put last is on the top and since we remove the plate that is at the top, we
can say that the plate that was put last comes out first.

Basic operations on stack:


In order to make manipulations in stack, there are certain operations provided to
us.
1. push() to insert an elements into the stack
2. pop()to remove an element from the stack
3.top()returns the top element of the stack
4.isEmty() returns true if stack is empty else false.
5.size()returns the size of stack
Diagram copy mehe

1. push:
Adds an item to the stack. If the stack is full, then it is said to be an overflow
condition
Algorithm for push:
Begin
If stack is full
Return
Endif
Else
Increment top
Stack[top]assign value
End else
End procedure
2. pop:
Removes an item form the stack. The item are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an underflow
condition.
Algorithm for pop:
Begin
If stack is empty
Return
Endif
Else
Store value of stack[top]
Decrement top
Return value
End else
End procedure
3.Top:
Returns the top element of the stack.
Algorithm for top:
Begin
Return stack[top]
End procedure

4. isEmpty:
Returns true if the stack is empty, else false.
Algorithm for isEmpty
Begin
If top<1
Return true
Else
Return false
End procedure

Application of the stack:


1. infix to postfix/prefix conversion
2. red-undo features at many places like editors, photoshop
3. forward and backward features in web browsers
4. used in many algorithm like Tower of Hanoi tree traversals, stock span problem
and histogram problems
5. backtracking is one of the algorithm designing techniques. Some example of
backtracking are the knight-tour problem, N-queen problem, find your way through
a maze, and game-like chess or checkers in all these problems we dive into
someway f that way is not efficient we come back to the previous state and go into
some another path. To get back from a current state we need to store the previous
state for that purpose we need a stack.
6. in graph algorithm like topological sorting and strongly connected components
7. in memory management, any modern computer uses a stack as the primary
management for a running in a computer system has its own memory allocations
8.stacks also helps in implementing function call in computers. The last called
function is always completed first.
9. stacks are also used to implement the undo/redo operation in text editor.

Implementation of stack:
A stack can be implemented using an array or a linked list. In an array-based
implementation, the push operation is implemented by incrementing the index of
the top element and storing the new element at that index. The pop operation is
implemented by decrementing the index of the top element and returning the vale
stored at that index. In a linked list-based implementation, the push operation is
implemented b creating a new node with the new element and setting the next
pointer of the current top node to the new node. The pop operation is implemented
by setting the next pointer of the current top node to the next node and returning
the value of the current top node.
There are two ways to implement a stcak:
1. using array
2. using linked list

Implementation copy me rahega

Infix expression : the expression of the form a op.b when a n operator is in between
every pair of operands.

Postfix expression: the expression of the form a b op. When an operator is followed
for every pair of operands.
Postfix notation, also known as reverse polish notation, is a syntax for
mathematical expressions in which the mathematical operator is always placed
after the operands. Though postfix expressions are easily and efficiently evaluated
by computers, they can be difficult for humans to read. Complex expressions using
standard parenthesized infix notation are often more readable than the
coreesponding postfix expressions. Consequently , we would sometimes like to
allow end users to work with infix notation and then convert it to postfix notation
for computer processing. Sometimes, moreover, expressions are stored or
generated in postfix and we would like to convert them to infix for the purpose of
reading and editing.
Example;
Input : abc++
Output: (a + (b+c))

Input: ab*c+
Output: ((a*b)+c)
Implementation copy mehe
Evolution of postfix expression:
Given a postfix expression, the task is to evaluate the postfix expression
Postfix expression: the expression of the form “a b operator” (ab+) i.e., when a pair
of operands is followed by an operator.
Examples:
Input: str=”2 3 1* + 9-“
Output:-4
Explanation: if the expression is converted into an infix expression, it will be
2+(3*1)-9=5-9=-4

Input: str=”100 200+2/5*7+”


Output:757

Follow the steps mentioned below to evaluate postfix expression using stack:
1. create a stack to store operands (or values)
2. scan the given expression from the left to right and do the following for every
scanned element.
1. if the element is anumber, push it into the stack.
2. if the element is an operator, pop operands for the operator form the stack.
Evaluate the operator and push the result back to the stack.
Evaluate value of postfix expression

What is recursion:
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called recursive function. using a recursive
algorithm, certain problems can be solves quite easily.examples of such problems
are inorder/preorder/postorder etc. Recursion in an amazing technique with the
help of which we can reduce the length of our code amd make it easier to read and
write.
Properties of recursion:
1. performing the same operations multiple time with different inputs.
2. in every steps, we try smaller inputs to make the problem smaller.
Let us example of how recursion work by taking a simple function .
Program copy mehe
Direct recursion : a function fun is called direct recursion if it calls the same function
fun.
Indirect recursion: a function fun is called indirect recursion if it calls another
function say fun_new and fun_new calls fun indirectly and directly.

Recursion iteration
1. terminates when the 1. Terminates when the condition
Base case becomes becomes false .
True.

2. used with functions 2. Used with loops

3.Every recursive call 3. Every iteration does not require


Needs extra space in any extra space.
The stack memory.

4. smaller code size. 4. Larger code size.

Write a program and recurrence relation to find the fibonaci series of n wheren>2.
Program copy me rahgea

Queue :
A queue is a linear structure that follows a particular order in which the operations
are performed. The order in first in first out (FIFO). A good example of a queue is
any queue of consumers for a resource where the consumer that came first is
served first. In this article, the different types of queue are discussed.
Types of queues: there are five different types of queue that are used in different
scenarios. They are:
1. Input restricted queue (this is a simple queue)
2. output restricted queue (this is a simple queue)
3. circular queue
4. double ended queue(deque)
5. priority queue.
1. ascending priority queue
2. descending priority queue
Diagram copy mehe
1. circular queue: circular queue is a linear data structure in which the operations
are performed based on FIFO(first in first out) principle and the last position is
connected back to the first position to make a circle. It is also called ‘ring buffer’ this
queue is primarily used in the following cases:
1. memory management : the unused memory locations in the case of ordinary
queues can be utilized in circular queues.
2. traffic system: in a computer-controlled traffic system, circular queues are used to
switch on the traffic lights one by one repeatedly as per the time set.
3. CPU scheduling :OS often maintain a queue of processes that are ready to
execute or that are waiting for a particular event to occur.
The time complexity for the circular queue is O(1).

2. input restricted queue: in this type of queue, the input can be taken form one
side only(rear) and deletion of elements can be done form both sides(front and
rear). This kind of queue does not follow FIFO. This queue is used in cases where the
consumption of the data needs to remove the recently inserted data for some
reason and one such case can be irrelevant data, performance issue , etc.
Diagram copy me rahgea
3. output restricted queue: in this type of queue, the input can be taken form both
sides(rear and front) and the deletion of the element can be done form only one
side(front). This queue is used in the case where the inputs have some priority
order to be executed and the input can be placed even n the first place so that it is
executed first.
Diagram copy me rahgea

4. double ended queue: double ended queue is also a queue data structure in which
the insertion and deletion operations are performed at both the ends(front and
rear). That means, we can insert at both front and rear positions. Since deque
supports both stack and queue operations, it can be used as both. The deque data
structure supports clockwise and anticlockwise rotations in O(1) time which can be
useful in certain applications. Also, the problems where elements need to removed
and or added both ends can be efficiently solved using deque.
Diagram copy me rahgea

5. priority queue: a priority queue is a special type of queue in which each element
is associated with a priority and is served according to its priority. There are two
types of priority queues. They are:
1. ascending priority queue: element can be inserted arbitrarily but only smallest
element can be removed. For example, suppose there is an array having elements
4,2,8 in the same order. So, while inserting the elements, the insertion will be in the
same sequence but while deleting, the order will be 2,4,8.

2. descending priority queue: element can be inserted arbitrarily but only the
largest element can be removed first from the given queue. For example, suppose
there is an array having elements 4,2,8 in the same order. So, while inserting the
elements, the insertion will be in the same sequence but while deleting, the order
will be 8,4,2.
The time complexity of the priority queue is O(logn).

Circular queue insertion deletion program copy mehe

Unit : 2
Classes and objects:
A simple C++ program with class:
Program copy mehe

Nesting of member function:


A member function can be called by using its name inside another member function
of the same class. This is known as nesting of member functions.
Program copy mehe

Memory allocation for object:


The way memory is allocated to variable and functions of the class is different even
though they both are from the same class. The memory is only allocated to the
variables of the class when the object is created.
The memory is not allowed to the variable when the class is
declared. At the same time, single variables can have different values for different
objects, so every object has an individual copy of all the variables of the class. But
the memory is allocated to the function only once when the class is declared. So the
objects don’t have individual copies of functions only one copy is shared among
each object.

Static data members:


When a static data member is created, there is only a single copy of the data
member which is shared between all the objects of the class. Usually, every object
has an individual copy of the attributes unless specified statically. Static member
are not defined by any object of the class. They are exclusively define outside any
function using the scope resolution operator.
An example of how static variables are define is:
Copy mehe

Static member functions:


The static keyword is used with a variable to make the memory of the variable
static once a static variable is declared its memory can’t be changed.
Static member function in a class is the function that is declared as
static because of which function attains certain properties as defined below:
1. A static member function is independent of any object of the class.
2. a static member function can be called even if no objects of the class exist.
3. a static member functions can also be accessed using the class name through the
scope resolution operator.
4. A static member function can access static data members and static member
functions inside or outside of the class.
5. static member function have a scope inside the class and cannot access the
current object pointer.
6. you can also use a static member function to determine how many objects of the
class have been created.
Program copy mehe

Array of objects:
An array in C/C++ or be it any programming languages is a collection of similar data
items stored at contiguous memory locations and elements can be accessed
randomly using indices of an array. They can be used to store the collection of
primitive data types such as int, float, double, char,etc of any particular type. To
add to it, an array in C/C++ can store derived data types such as structures, pointers,
etc. Given below is the picture representation of an array.
Example copy me rahega

Array of object:
When a class is defined, only the specification for the object is defined; no memory
or storage is allocated. To use the data and access functions defined in the class,
you need to create objects.
Syntax and example and implementation copy mehe
Advantage of array of object:
1. the array of objects represent storing multiple objects in a single name.
2. in an array of objects, the data can be accessed randomly by using the index
number.
3. reduce the time and memory by storing the data in a single variable.

Objects as a function arguments:


The objects of a class can be passed as arguments to member functions as well as
non-member functions either by value or by reference. When an object is passed by
value, a copy of the actual object is created inside the function. This copy is
destroyed when the function terminates.
Program copy mehe

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. For example, a linkedlist class may
be allowed to access peivate members of node.
Program copy mehe

Friend function:
Like a friend class, 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.
A friend function can be:
1. a global function
2. a member function of another class
Diagram copy mehe

1. global function as friend function:


We can declare any global function as a friend function. The following example
demonstrates how to declare a global function as a friend function in C++.
Program copy mehe
2. member function of another class as friend function:
We an declare a member function of another class as a friend function in C++. The
following example demonstrates how to use a member funation of another class as
a friend function in C++.
Program copy mehe

A function friendly to multiple class program

Advantages of friend function:


1. a friend function is able to access members without the need of inheriting the
class.
2. the friend function acts as a bridge between two classes by accessing their private
data.
3. it can be used to increase the versatility of overloaded operators.
4. it can be declared either in the public or private or protected part of the class.

Disadvantages of friend function:


1. friend function have access to private members of a class form outside the class.
Imp points about this :
1.Friendship is not mutual
2. friendship is not inherited
3. the concept of friend is not in java.

Virtual function in C++:


A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined.
(overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that
object and execute the derived class’s version of the method.
1. virtual functions ensures that the correct function is called or an object,
regardless of the type of reference(or pointer) used for the function call.
2. they are mainly used to achieve runtime polymorphism.
3. functions are declared with a virtual keyword in a base class.
4. the resolving of a function call is done at runtime.

Limitation of virtual function:


1. slower
2. difficult to debug
Program copy mehe
Passing and returning object:
In C++ we can pass class’s objects as arguments and also return them form a
function the same way we pass and return other variables. No special keyword or
header file is required to do so.

Passing an object as argument:


To pass an object as an argument we write the object name as the arguments while
calling the function the same way we do it for other variables.
Example : Program copy mehe

Returning object as arguments:


An object is an instance of a class. Memory is only allocated when an object is
created and not when a class is defined. An object can be returned by a function
using the return keyword.
Program copy mehe
Const member function :
Constant member function are thode functions which are denied permission to
change the values of the data members of their class. To make a member function
constant, the keyword ”cont” is appended to the function prototype and also to the
function definition header.
Like member functions and member function arguments, the object of a
class can also be declared as const. An object declared as const cannot be modified
and hence, can invoke only const member functions as these functions ensures not
to modify the object
A const object can be created by prefixing the const keyword to the
object declaration. Any attempt to change the data member of const objects results
in a compile-time error.
A function becomes when the const keyword is used in the functions
declaration. The idea of const functions is not to allow them to modify the object on
which they are called. It is recommended practice to make as many functions const
as possible so that accidental changes to object are avoided.
Program copy mehe
When a function is declared as const, it can be called on any type of object.
Non-const functions can only be called by non-const objects.
Pointers to member :
Pointers to members allow you to refer to nonstatic members of class objects. You
cannot use a pointer to member to point to a static class member because the
address of a static member is not associated with any particular object. To point to
a static class member, you must use a normal pointer.
You can use pointers to member functions in the same manner
as pointers to functions. You can compare pointers to member functions, assign
values to them, and use them to call member functions. Note that a member
function does not have the same type as a non-member function that has the same
number and type of arguments and the same return type.
Program copy mehe

Local classes in C++:


A class declared inside a function becomes local to that function and is called local
class in C++.
1. a local class name can only be used locally i.e., inside the function and not
outside it.
2. the methods of a local class must be defined inside it only.
3. a local class can have static functions but, non static data members.
Program copy mehe
Constructor in C++:
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 constructor.
1. constructor is a member function of a class whose name is same as the class
name.
2. constructor do not return value, hence they do not have a return type.

Characteristics of constructor:
1. constructor can be overloaded.
2. constructor do not return value; hence they do not have a return type
3.the name of constructor is same as its class name.
4. constructor cannot be inherited
5.address of constructor cannot be referred.

Types of constructor :
1. default
2. parameterized
3. overloaded
4. constructor with default value
5. copy constructor
6. inline constructor

1. parameterized constructor: 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.
Program copy mehe
Uses of parameterized constructor :
1. it is used to initialize the various data elements of different objects with different
values when they are created.
2. it is used to overload constructor.
2. copy constructor: a copy constructor is a member function that initializes an
object using another object of the same class.
Whenever we define one or more non-default constructor (with
parameters) for a class, a default constructor (without parameters) should 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 be the best practice to always
define a default constructor.
Program copy mhe

Destructor :
A destructor is also a special member function as 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 cannot be overloaded. Destructor neither requires
any argument nor returns any value. It is automatically called when the 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 object
creation.
Program copy mehe

Dynamic initialization of object:


The dynamic initialization of object using dynamic constructor:
1. dynamic initialization of object refers to initializing the objects at a run time i.e.
the initial value of an object is provided during run time.
2. it can be achieved by using constructor and by passing parameters to the
constructors.
3. this comes in really handy when there are multiple constructor of the same class
with different inputs.
Program copy mehe
Dynamic constructor :
1. the constructor used for allocating the memory at runtime is known as the
dynamic constructor.
2. the memory is allocated at runtime using a new operator and similarly, memory
is deallocated at runtime using the delete operator.

Constructor with Default arguments:


Default arguments of the constructor are those which are provided in the
constructor declaration. If the values are not provided when calling the constructor
uses the default arguments automatically.
A constructor can contain default parameters as well. A default
constructor can either have no parameters or parameters with default arguments:
Program copy me rahega 3 point wala krna he

You might also like