Programming Methodology
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
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.
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”,
}
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.
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.
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.
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.
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.
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.
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
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
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.
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)
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
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:
DBEAFCG
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:
ABDECFG
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 :
DEBFGCA
Unit : 5
Linked list :
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.
2. deletion: the deletion operation can be performed in three ways. They are as
follows:
3 operations copy mehe iske
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.
Note: we will be using the singly circular linked list to represent the working of the
circular linked list.
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
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
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.
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
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.
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
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.
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.
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.
6. fixed: the fixed manipulator of stream manipulators in C++ is used to turn on the
fixed flag.
8. hex: the hex manipulators of stream manipulators in C++ is used to turn on hex
flag
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:
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.
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.
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.
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.
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
Sparse matrix representation can be done in many ways following are two common
representations:
1. array representation
2. linked list representation
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
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
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
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.
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).
Unit : 2
Classes and objects:
A simple C++ program with class:
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.
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
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
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