Sei sulla pagina 1di 33

DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING

Unit I
1. Describe in detail about arrays.
Arrays
An array is a fixed size sequence collection of elements of the same data type.
It is simply a grouping of like type data .
In its simplest form an array can be used to represent a list of numbers or a list of names.
1.8.1 One Dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is called
single subscripted variable or a one dimensional array.
For eg : if we want to represent a set of five numbers say (3,4,5,6,7) by an array variable number then we
may declare the variable number as follows.
int no.[5];
The values to the array elements can be assigned as follows:
No.[0] =35;
No.[1] = 40;
No.[2] =20;
No .[3]= 51;
No .[4]=19;
Eg: Float height [50];
Declaration of One Dimensional Array
Datatypevariable -name [size];
Eg: int group [10];
Initialization of One Dimensional Array
After an array is declared, its elements must be initialized.
Otherwise ,they will contain garbage
An array can be initialized at either at the following stages
compile time
run time
Compile Time Initialization
The general form of initialization of array is :
Type array - name [size] ={ list of values}
The values in the list are repeated by commas. For eg : the statements,
int number [3]={0,0,0}
Will declare the variable number as an array of size 3 and will assign zero to each element.
Run Time Initialization
An array can be explicitly initialized at runtime.
This approach is usually applied for initializing large arrays.
For eg consider the following segments of C program.
..

for(i=0;i<100;i=i+1)
{
ifi<50
sum[i]=0.0;
else
sum[i]=1.0
}..
.
The first 50 elements of the array are initialized to 0 while the remaining 50 elements are initialized to
1.0 at runtime
Two Dimensional Array
In maths ,we represent a particular value m by a matrix by using two subscript such as Vij.
V[4][3]
Syntax:
Type array name [ row-size] [column-size]
Initializing two dimensional array:
Like the one dimensional array,two dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces.
For eg:
int table [2] [3] ={ 0,0,0,1,1,1}
Multidimensional Array
The general form of multidimensional array is
Type array- name[s1][s2][s3][sn]
Where s1 is the size
Eg:
int survey [3][5][12];
If we are reading or writing two-dimensional array, two loops are required. Similarly
the array of n dimensions would require n loops.
2. Describe in detail about creating & analysing program.
Creating Programs
It contain five phases:
1. Requirements
2. Design
3. analysis
4. coding
5. verification.
(i) Requirements.:
Make sure you understand the information you are given (the input) and what results you are to produce
(the output).
Try to write down a rigorous description of the input and output which covers all cases. You are now
ready to proceed to the design phase.
(ii) Design:
Designing an algorithm is a task which can be done independently of the programming language you
eventually plan to use.
In fact, this is desirable because it means you can postpone questions concerning how to represent your
data and what a particular statement looks like and concentrate on the order of processing.
(iii) Analysis:
Can you think of another algorithm? If so, write it down.
Next, try to compare these two methods. It may already be possible to tell if one will be more desirable
than the other.
If you can't distinguish between the two, choose one to work on for now and we will return to the second
version later.
(iv) Refinement and coding:
You must now choose representations for your data objects and write algorithms for each of the
operations on these objects.
The order in which you do this may be crucial, because once you choose a representation, the resulting
algorithms may be inefficient.
(v) Verification:
Verification consists of three distinct aspects:
program proving,
testing and
debugging.
Before executing your program you should attempt to prove it is correct.. Testing is the art of creating
sample data upon which to run your program. If the program fails to respond correctly then debugging
is needed to determine what went wrong and how to correct it.
Analyzing Programs
Performance Analysis
Space Complexity
Time Complexity
1.Space Complexity:
The space complexity of an algorithm is the amount of money it needs to run to compilation,
Example:
Algorithm abc(a,b,c)
{
returna+b++*c+(a+b-c)/(a+b) +4.0;
}
The Space needed by each of these algorithms is seen to be the sum of the following component.
A fixed part that is independent of the characteristics (eg:number,size)of the inputs and outputs.
o The part typically includes the instruction space (ie. Space for the code), space for simple variable and
fixed-size component variables (also called aggregate) space for constants, and so on.
A variable partthat consists of the space needed by component variables whose size is dependent on the
particular problem instance being solved, the space needed by referenced variables and the recursion
stack space.
The space requirement s(p) of any algorithm p may therefore be written as,
S(P) = c+ Sp(Instance characteristics)
Where c is a constant.
2.Time Complexity
The time complexity of an algorithm is the amount of computer time it needs to run to compilation.
We introduce a variable, count into the program statement to increment count with initial value 0.Statement
to increment count by the appropriate amount are introduced into the program.
This is done so that each time a statement in the original program is executes
count is incremented by the step count of that statement.
Algorithm:
Algorithm sum(a,n)
{
s= 0.0;
count = count+1;
for I=1 to n do
{
count =count+1;
s=s+a[I];
count=count+1;
}
count=count+1;
count=count+1;
return s;
}
If the count is zero to start with, then it will be 2n+3 on termination. So each invocation of sum execute a
total of 2n+3 steps.
3. What is searching? Explain in detail about binary search.
Searching Techniques:
searching is an operation to find the location of the given data in the array, linked list.
Searching is said to be successful if the data is present, otherwise it is said to be unsuccessful.
There are 2 types of searching
1. Internal searching
2. External searching
1. Internal searching:
If all the data to be searched are in the main memory, then it is called as internal searching.
2. External searching:
If the data to be searched are in the main memory, secondary memory, then it is called as external searching.
internal searching can be categorized as
o Linear search
o Binary search
1.5.1 Linear Search
Logic:To Find The Position Or Location Of An Element
linear searching is otherwise called as sequential searching.
Let A be the array of n nos.
X is an element to be searched.
Our aim is to find whether X is present or not.
Implementation:
Compare X with A[0], if it equals, then return the position of A[0], else compare X with A[1], then
return the position of A[1].. and so on.
We can repeat the process until a[n-1] times.
If no matching occurs, then print data is not present.
Algorithm:LINEAR(A,N,X)
REPEAT FOR I=0,1,2..N-1
IF A[I]==X THEN
PRINT DATA FOUND
RETURN
END OF STEP 1 FOR LOOP
PRINT DATA NOT FOUND
Example:
a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]

20 35 18 8 14 41 3 39

If x=20 then element is found at the first location.


Data found,Successful Search
If x=5 then element is not found,Unsuccessful Search.
1.5.2 Binary Search
Binary search method is solved by using the Divide and Conqueor Strategy where the probem is divided into
sub problems and each subproblem is solved separately .
finally all the solutions are combined into a single solution which inturn is the solution for the original
problem.
The input for binary search must be given in the sorted order.it has three cases
Case1:X= Middle Element
Case2:X>Middle Element
Case3:X<Middle Element
Algorithm : binary search
Input : A, vector of n elements
K, search element
Output :low index of k
Method : low=1,high=n
While(low<=high-1)
{
mid=(low+high)/2
if(k<a[mid])
high=mid
else
low=mid
if end
}
while end
if(k=A[low])
{
write("search successful")
write(k is at location low)
exit();
}
else
write (search unsuccessful);
if end;
algorithm ends.
Example
9 11 17 20 25 30 33
Let us search for the element 17.
Is low >high ? NO
Mid=(0+6)/2 = 3.

Fig 1.2 (a)Binary Search


Is 17 = = A[3] ? No
17 <A[3], repeat the steps with low =0 and high = mid-1=2
Is low >high ? NO
Mid=(0+2)/2 = 1.

Fig 1.2 (b) Binary Search


Is 17 = = A[1] ? No
17 >A[1], repeat the steps with low = mid +1 =2 and high = 2
Is low >high ? NO
Mid=(2+2)/2 = 2.

Fig 1.2 (c) Binary Search


Is 17 = = A[2] ? Yes
Return (2).
4. Write a short notes on.
a. Quick sort.
b. Merge sort.
c. Insertion sort.
d. Selection sort
Quick Sorting
Quick sort is otherwise called as partition exchange sorting.
It uses divide and conquer method.
Let A be the array of n nos.
Our aim is to sort the numbers by ascending order.
Principle:
1. Choose any one in the array and name it as partition element or pivot element (P). For simplicity we take
the first no as the partition element. i.e., A[0]=P.
2. With respect to P, divide the array into two partitions i.e., left, right partition. The numbers which are less
than P are placed in the left side of P. And the numbers which are greater than P are placed in the right
side of P,Implementation
For now,assume that pivot=A[(left/right)/2]
We want to partition array A[leftright]
First ,get the pivot element out of the way by swapping it with the last element(swap pivot and A[right]
Let i start at the first element and j start at the next to last element(i=left,j=right-1)

When i< j
Move i right, skipping over elements smaller than the pivot
Move j left, skipping over elements greater than the pivot
When both i and j have stopped
A[i] pivot
A[j] pivot A[i] and A[j] should now be swapped

When i and j have stopped and i is to the left of j (thus legal)


Swap A[i] and A[j]
The large element is pushed to the right and the small element is pushed to the left
After swapping
A[i] pivot
A[j] pivot
Repeat the process until i and j cross

When i and j have crossed


swap A[i] and pivot
Result:A[k] pivot, for k<I A[k] pivot, for k>i

Merge Sorting
It uses divide and conquer rule for its operation.It divides input array in two halves, calls itself for the two
halves and then merges the two sorted halves.

Algorithm:
merge(k,first,second,third)
1. [initialize]
ifirst
jsecond
l0
2. [compare elements and find smallest]
repeat while i<second and jthird
if k[i]k[j] then
ll+1
temp [l] k[i]
ii+1
else
ll+1
temp[l] k[j]
jj+1
3. [copy remaining elements]
ifisecond
repeat while jthird
ll+1
temp [l] k[j]
jj+1
else
repeat while i<second
ll+1
temp[l] k[i]
ii+1
4. [copy temp into k]
fori=1,2,3..l
k[first-1+i] temp[i]
5. [finished]
return
Selection Sorting
Let A be the array of n numbers.
Our aim is to sort the numbers in ascending order.
First find the smallest element position in the array(say i) then interchange zeroth position and ith
position element.
Find the second smallest element position in the array(say j),then interchange first position and jth
position element.
We can repeat the process up to (n-1) times. Finally we will be getting sorted array
Algorithm:
Algorithm Selection_Sort (A,n)
{
fori := 1 to n-1 do
{
min := i;
m:=a[min];
forj: = i+1 to n do
{
if (a[j] < m) then
min = j;
}
t := a[i];
a[min] := a[i];
a[i] = t;
}
}

Insertion sorting
Let A be the array of n numbers.
Our aim is to sort the numbers in ascending order.
Scan the array from A[1] to A[n-1] and find the smallest element A[R] where R=1,2,3(N-1) and
insert into the proper position previously sorted sub-array, A[1],A[2]..A[R-1]
If R=1, the sorted sub-array is empty, so A[1] is sorted itself.
If R=2, A[2] is inserted into the previously sorted sub-array A[1], i.e., A[2] is inserted either before A[1]
or after A[1].
If R=3, A[3] is inserted into the previously sorted sub-array A[1],A[2] i.e., A[3] is inserted either before
A[1] or after A[2] or in between A[1] and A[2].
We can repeat the process for(n-1) times, and finally we get the sorted array.
Algorithm:
Algorithm Insertion_Sort(A,n)
1. For j = 2 to length [A] do
2. key = A[j]
3. {Put A[j] into the sorted sequence A[1 . . j-1]
4. i j -1
5. while i> 0 and A[i] > key do
6. A[i+1] = A[i]
7. i = i-1
8. A[i+1] = key

Unit II
1. What is stack? Explain in detail about application of stack.
A stack is a list with the restriction that inserts and deletes can be performed in only one position, namely the
end of the list called the top.
Applications of stack
1.Infix To Postfix Conversion
2.Postfix Expression Evaluation
3.Dynamic Memory Management
Infix to Postfix Conversion
The stack is used to convert the infix expression to postfix expression. Infix In Infix notation, the
arithmetic operator appears between the two operands to which it is being applied.
For example: A / B + C
Postfix
Also called reverse polish notation.
((A/B) + C)
For example: - AB / C +
Algorithm
1. Read the infix expression one character at a time until we reach the end of input
a) If the character is an operand, place it on to the output.
b) If the character is a left parenthesis, push it onto the stack.
c) If the character is a right parenthesis, pop all the operators from the stack until we encounters a left
parenthesis, discard both the parenthesis in the output.
d) If the character is an operator, then pop the entries from the stack until we find an entry of lower priority
(never pop (). The push the operator into the stack.
2. Pop the stack until it is empty, writing symbols onto the output.
Example
Suppose we want to convert the infix expression
a+b*c+(d*e+f)*g
into postfix expression.
First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed onto the
stack. Next b is read and passed through to the output. The state is as follows:

Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing is
output and '*' is put on the stack. Next, c is read and output. Thus far, we have

The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the output, pop the
other '+', which is not of lower but equal priority, on the stack, and then push the '+'.

The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then dis
read and output.

We continue by reading a '*'. Since open parentheses do not get removed except when a closed
parenthesis is being processed, there is no output. Next, e is read and output.

The next symbol read is a '+'. We pop and output '*' and then we push '+'. Then we read and output

Now we read a ')', so the stack is emptied back to the '('. We output a '+'.
We read a '*' next; it is pushed onto the stack. Then g is read and output.

The input is now empty, so we pop and output symbols from the stack until it is empty.

Evaluation of Arithmetic Expression


Once the expression has been parsed into postfix form, another stack can be used to evaluate postfix
expression.
To evaluate such an expression,
i)we repeatedly read characters from the postfix expression.
ii)If the character read is an operand, push the value associated with it onto the stack.
iii) If it is an operator, pop two values from the stack, apply the operator to them and push the result back on
the stack.
The process is illustrated in the following figure2.15 .

2. Explain in detail about operation of queue. List out it applications.


Queue ADT
Queue is an ordered collection of elements in that insertion is done at one end called rear, whereas deletion is
performed at the other end called front.
The basic operations on a queue are
Enqueuer=, which inserts an element at the end of the list (called the rear)
dequeue, =which deletes (and returns) the element at the start of the list (known as the front).
Queue followed the principle of FIFO(first in first out)
Start of the queue is known as front and End of the queue is known as rear
ImplementatioOf Queue
1. Array implementation of queue
2. Linked list implementation of queue
First kind of representation uses one-dimension array and it is a better choice where a queue of fixed size is
requiredThe other representation uses a linked list and provides a queue whose size can vary during
processing.
Array implementation of queue:
A one dimensional array can be used to represent a queue, figure shows a instant of such a queue
.with this representation ,two pointers,namely FRONT and REAR are used to indicate two end of queue.for
the insertion of next element, pointer REAR will be consultant and for deletion pointer FRONT will be
consultant

Array implementation of queue


Three states of the queue with this representation
Queue is empty
FRONT=0
REAR-0
Queue is full
REAR=N
FRONT=1
Queue contain element >= 1
FRONT<= REAR
NUMBER OF ELEMENT =REAR-FRONT+1
Operations
Enqueue :
To enqueueanelement , we increment queue size and queue rear, then set QUEUE[rear] = element.
Ex: Insert/enqueue 8

After Insertion On aQueue

Routine for Enqueue in Queue Routine for Dequeue


If (rear = N) then If(front=0)then
Printqueue is full Printqueue is empty
Exit Exist
Else Else
If(rear=0) and (front=0) then Item=Q(front)
Front=1 If(front=rear)
Endif Rear=0
Rear=rear+1 Front=0
Q(rear)=item Else
End if Front=front+1
stop Endif
Endif
Stop
Dequeue:
To dequeuean element, we set the return value to QUEUE[front], decrement queuesize, and then increment
queuefront.
Example:

After Deletion On a Queue


Operation Of Queue Example
Operation of Queue
3. Define linked list. Illustrate and explain in detail about types of linked list.
Linked List
Linked list consist of a series of structures, which are not necessarily in adjacent in memory. The structure is
called as Node.
Each structure (node) contains :
Element
Pointer to a structure containing next element. It is called as Next Pointer
The Last cells Next pointer point to NULL,
A single node is represented as follows
Pointer :A pointer is a variable that contains the address of another variable

A1 800 A2 712 A3 0
1000 800 700
Linked list with actual pointer value
Single Linked List
A singly linked list is a list in which each node contains only one link field pointing to the next node in the
list.
Basic linked List Operations
The basic operations to be performed on linked lists are as
Creation - Create a linked list
Insertion - insert a new node at the specified position
Deletion - delete the specified node
Traversing - to display every node information
Find - Search a particular data
Implementation
For easy implementation of all linked list operation a sentinel node is maintained to point the beginning of
the list. This node is sometimes referred to as a header or dummy node. To access the list, we must know
the address of the header Node.
To insert a new node at the beginning of the list, we have to change the pointer of the head node. If we miss
to do this we can lose the list. Likewise deleting a node from the front of the list is also a special case,
because it changes the head of the list.
Creating Linked List
The malloc( ) function is used to allocate a block of memory to a node in a linked list. The create function is
used to create a dummy header node.
List Create( )
{
List L;
L=(struct Node *)malloc(sizeof(struct Node));
L->Element=0;
L->Next=NULL;
return L;
}
Insertion
Insertion requires obtaining a new cell from the system by using a malloc call and then executes two pointer
change

Insertion in single linked list


Routine to insert an Element to the List
void Insert (ElementType X, List L, Position P)
{
Position Tmpcell;
Tmpcell = (struct Node*)malloc (size of (Struct Node));
If (Tmpcell == NULL)
Printf(Error! No Space in memory);
Else
{
Tmpcell->Element = X;
Tmpcell->Next = P->Next;
P->Next = Tmpcell;
}
}
Deletion:
This function deletes the first occurrence of an element from the linked list.This can be shown in
below figure.

Deletion in single linked list


Routine to Delete an Element from the List
void Delete(int x, List L)
{
position P, temp;
P = Findprevious (x,L);
If (!IsLast(P,L))
{
temp = P->Next;
P ->Next = temp->Next;
Free (temp);
}
}
Advantage
1. Insertions and Deletions can be done easily.
2. It does not need movement of elements for insertion and deletion.
3. Elements may or may not be stored in consecutive memory
4. It is less expensive.
Disadvantage
1. It requires more space as pointers are also stored with information.
2. If we have to go to a particular element then we have to go through all those elements that come
before that element.
3. we cannot traverse it from last
4. It is not easy to sort the elements stored in the linear linked list
Doubly Linked List
A node contains pointers to previous and next element. One can move in both directions.A node
contain three fields.
i)dataii)address to previous celliii)address to next cell

Doubly linked list


Insertion
This function is used to insert an element X into the list after the position X. The insert action can be shown
below

insertion in Doubly linked list


Deletion
This function deletes the first occurrence of an element from the linked list.This can be shown in below
figure.

Deletion in Doubly linked list


Advantages
1. We can traverse in both directions i.e. from starting to end and as well as from end to starting.
2. It is easy to reverse the linked list.
3. If we are at a node, then we can go to any node. But in linear linked list, it is not possible to reach
the previous node.
Disadvantages
1. It requires more space per space per node because one extra field is required for pointer to previous
node.
2. Insertion and deletion take more time than linear linked list because more pointer operations are
required than linear linked list.
Circular Linked List
The last node points to the first one.

circular Linked List


Advantages:
1. If we are at a node, then we can go to any node. But in linear linked list it is not possible to go to
previous node.
2. It saves time when we have to go to the first node from the last node. It can be done in single step
because there is no need to traverse the in between nodes. But in double linked list, we will have to
go through in between nodes.
Disadvantages:
1. It is not easy to reverse the linked list.
2. If proper care is not taken, then the problem of infinite loop can occur.
If we at a node and go back to the previous node, then we can not do it in single step. Instead we
have to complete the entire circle by going through the in between nodes and then we will reach the
required node.
Unit III
1. What is binary tree? Explain in types of binary tree traversals.
Binary Trees
A binary tree is a tree, which is, either empty or consists of a root node and two disjoint binary trees
called the left sub-tree and right sub-tree.

In a binary tree , no node can have more than two children. So every binary tree is a tree, not every
tree is a binary tree.
Traversals of a binary tree:
Traversing a tree means processing the tree such that each node is visited only one.Traversal of a binary tree
is useful in many applications. For example, in searching for particulars nodes compilers commonly build a
binary trees in the process of scanning, parsing , generating code and evaluation of arithmetic expression.
Let T be a binary tree, there are a number of a different ways to proceed. The methods differ primarily in the
order in which they visit the nodes. The three different traversals of T are
Preorder traversal
Inorder traversal
Postorder traversal
Preorder traversal
In this traversal , the root is visited first, then the left sub-tree in preorder fashion, and then the right sub-tree
in preorder fashion. such a traversal can be defined as follow:
Root
Left subtree
Right subtree
Example

Solution: A B D E C
Routine:
Ptr=root
If(ptrNULL)then
Visit(ptr)
Preorder(ptr->LC)
Preorder(ptr->RC)
Endif
stop
Inorder traversal
In this Traversal ,the left sub-tree of the root is visited, then the root node and after that the right sub tree of
the root node is visited.visiting both the sub tree is in the same fashion as the tree itself.
Left subtree
Root
Right subtree
Example

Solution: D B E A C
Routine:
Ptr=root
If(ptrNULL)then
Inorder(ptr->LC)
Visit(ptr)
Inorder(ptr->RC)
Endif
stop
Post Order
In this Traversal ,the left sub-tree of the root is visited, then the right sub tree of the root node is visited,
after that root is visited last. visiting both the sub tree is in the same fashion as the tree itself.
Left subtree
Right subtree
Root
Example

Solution D E B C A
Routine:
Ptr=root
If(ptrNULL)then
Postorder(ptr->LC)
Postorder(ptr->RC)
Visit(ptr)
Endif
Stop
2. Explain in detail about minimum spanning tree.
Minimum Spanning Trees
The spanning tree of a graph G can be defined as a tree which includes all the vertices of
G.Ingraphtraversal,we have seen that the DFS and BFS traversal result in two trees
DFS spanning tree and BFS spanning tree
The minimum spanning tree problem is related to the weighted graph, where we find a spanning
tree so that the sum of all the weighted of all edges in the tree is minimum.
Two efficient method available for finding a spanning tree are
1.kruskals algorithm
2.prims algorithm
kruskals algorithm
To obtain a minimum spanning tree of a graph, a novel approach was devised by J.B KRUSKAL known as
kruskals algorithm.
Algorithm kruskal
1.list all the edges of the graph G in the increasing order of weights.
2.Select the smallest edge from the list and add it into the spanning tree, if the inclusion of this edge does
not make a cycle
3.if the selected edge with smallest weight forms a cycle, remove it from the list.
4.repeat step 2-3 until the tree contains n-1 edges or list is empty
If the tree contains less than n-1 edges and the list is empty, no spanning tree is possible for the graph, else
return minimum spanning tree

Primss Algorithm
According to prims algorithm ,a minimum spanning tree grows in successive stages.The prims
algorithm find a new vertex to add it to the tree by choosing the edge <vi,vj>,the smallest among all edges,
where vi I the tree and vjis yet to be included in the tree.
The prims algorithm can easily be implemented using the adjacency matrix representation of a
graph.Let us now illustrate the above method of finding a minimum spanning tree

We start with v1 and pick the smallest entry;thus v4 is the nearest neighbor to v1
3. What is graph? Write short notes on BFS,DFS.
Graph Traversals
Traversing a graph means visiting all the vertices in the graph exactly once. We have two standard
ways to do the traversal. They are
1.Depth First Search(DFS)
2.Breadth First Search(BFS)
Depth First Search(DFS)
In graphs, we do not have any start vertex or any special vertex singled out to start traversal from. Therefore
the traversal may start from any arbitrary vertex.
Approach behind DFS traversal, starting from the given node, this traversal visits all the nodes up to the
deepest level and so on
(i)visit the vertex v then the vertex immediate adjacent to V,let it be Vx.
(ii)ifVx has an immediate adjacent,say,vy then visit it ans so on,till there is a dead end. This result in
path,P(v-vx-vy.)
Dead end means a vertex which does not have an immediate adjacent or its immediate adjacent,already been
visited.
(iii) After coming to dead end,we backtrack along P to V to see if it has another adjacent vertex other than
vx ant then continue the same from it else from the adjacent of the adjacent(which is not visited earlier)
A stack can be used to maintain the track of all paths from any vertex so as to help backtracking.

1)Let us select start with vertex v1


The vertices adjacent to v1 are v2,v3,v4, push these adjacent vertices on to the stack

Visited vertices: v1

2)Pop the stack for the next vertex to be visited, here v4 is popped and its adjacent
vertices v2,v3 and v7 are pushed onto the stack

Visited vertices: v1,v4


3)Pop the stack for the next vertex to be visited, v7 is popped and its adjacent pushed on to the stack

Visited vertices: v1,v4,v7

4)Pop the stack for the next vertex to be visited, here v6 is popped and its adjacent pushed on to the stack

Visited vertices: v1,v4,v7,v6


5) Pop the stack for the next vertex to be visited, here v5 is popped and its adjacent
vertices pushed on to the stack

Visited vertices: v1,v4,v7,v6,v5


6) Pop the stack for the next vertex to be visited, here v3 is popped and its adjacent vertices pushed on to the
stack

Visited vertices: v1,v4,v7,v6,v5,v3


7) Pop the stack for the next vertex to be visited, here v2 is popped and its adjacent vertices pushed on to the
stack

Visited vertices: v1,v4,v7,v6,v5,v3,v2


The output of depth first traversal is v1,v4,v7,v6,v5,v3,v2
Algorithm
Input: v, the starting vertex
Output: A list VIST giving the order of vertices during traversal
If Gptr = NULL then
Print Graph is empty
Exit
EndIf
U= V
Open.Push(u)
While (open.Top NULL) do
u= OPEN.POP()
If (search_SL(VISIT,u) = FALSE) then
InsertEnd_SL(VISIT, u)
Ptr = GPTR[u]
While(ptr -> LINK NULL) do
vptr = ptr->LINK
OPEN.PUSH(vptr->LABEL)
EndWhile
EndIF
EndWhile
Return(VISIT)
Stop
Breadth First Search (BFS)
In BFS , we first visit all the adjacent vertices of the start vertex and then visit all the unvisited
vertices adjacent to these and so on.
This traversal is very similar to the level-by-level traversal of a tree.here,any vertex in the level I will be
visited only after the visit of all the vertices in its precedinglevel,thatis,at i-1.
A Queue can be used to maintain the track of all paths in breadth first search

1)Let us select starting vertex as v1


The vertices adjacent to v1 are v2,v3,v4, enqueue these adjacent vertices on to the queue

V2 V3 V4 Visited vertices: v1

2)De queue the Queue for the next vertex to be visited, here v2 is removed and its adjacent vertices v5 and
v4 are inserted onto the queue
V3 V4 V5 Visited vertices: v1,v2

3)De queue the Queue for the next vertex to be visited, here v3 is removed and its adjacent vertices inserted
onto the queue

V4 V5 V6 Visited vertices: v1,v2,v3

4) De queue the Queue for the next vertex to be visited, here v4 is removed and its adjacent vertices
inserted onto the queue

V5 V6 V7 Visited vertices: v1,v2,v3,v4

5) De queue the Queue for the next vertex to be visited, here v5 is removed and its adjacent vertices
inserted onto the queue
V6 V7 Visited vertices: v1,v2,v3,v4,v5

6) De queue the Queue for the next vertex to be visited, here v6 is removed and its adjacent vertices
inserted onto the queue
V7 Visited vertices: v1,v2,v3,v4,v5,v6

7) De queue the Queue for the next vertex to be visited, here v6 is removed and its adjacent vertices
inserted onto the queue
Visited vertices: v1,v2,v3,v4,v5,v6,v7

The output of Breadth First Search(BFS) is v1,v2,v3,v4,v5,v6


Algorithm BFS_LL
Input: V is the starting vertex
Output: A list VISIT giving the order of visit of vertices during the traversal
Steps:
If (GPTR = NULL) Then
Print Graph is empty
Exit
EndIf
u=V
OPENQ.ENQUEUE(u)
While(OPENQ.STATUS( ) EMPTY)do
U=OPENQ.DEQUEUE( )
If (search_SL(VISIT,u) = FALSE) then
InsertEnd_SL(VISIT,u)
Ptr = Gptr[u]
While (ptr->LINK NULL) do
Vptr = ptr ->LINK
OPENQ.ENQUEUE(vptr->LABEL)
EndWhile
EndIf
EndWhile
Return (VISIT)
Stop
Unit IV
1. Describe in detail about basic oops concepts.
Basic concepts of OOP
Objects.
Classes.
Data abstraction and Encapsulation.
Inheritance.
Polymorphism.
Dynamic binding.
Message passing.
In OOP concepts, all the functions are written in the classes and then we move to the main program.
This approach is called as Bottom-up approach.
Objects
Objects are basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle. Each object has the data
and code to manipulate the data and theses objects interact with each other.
Example: The definition for a player object could be:
Player Object:
data:
health
strength
agility
type of weapon
type of armor
actions:
move
attack monster
get treasure
end;
Class

Fig 4.3 Structure of Class


Collection of object is called class. The entire set of data and code of an object can be made a user-
defined data type with the help of a class. Once a class has been defined,
We can create any number of objects if the class is defined once.
Classes are user-defined data types and behave like built-in types of the programming language.
A class in C++ is an encapsulation of data members and functions that manipulate the data.
The entire set of data and code of an object can be made a user defined data type with the help of a
class.
Objects are variables of the type of class.
A class is collection of objects with similar data type.
For example mango, apple and orange are members of the class fruit
Data abstraction
Data abstraction is abstract values of the data. Data abstraction is mainly used of data hiding. Data
hiding is to hide the background details.
The insulation of data from direct access by the program is called as data hiding or information binding.
Data Encapsulation
Wrapping up of data and function into a single unit called as encapsulation.Encapsulation is combine the
data and function in single unit. The encapsulation example is capsule one capsule all particle in correct
ratio. The object has own data and function the process is handle in encapsulation.
Inheritance
The inheritance means derive a new class in existing one. Derive class is called child class and old
class is parent class. Mainly used for inheritance is code reusability. All properties of parent class to be
shared by the child class also child class contains some additional properties.
Object of one class can acquire the properties of object of another class
It supports the concept of hierarchical classification.
Without using hierarchies, we have to define all of its characteristics once again.
Using hierarchies, an object need only define those qualities that make it unique withinits class.
It can inherit its general attributes from its parent.
One object act as specific instance of a more general case.
ANIMALS

PET ANIMALS WILD ANIMALS

CAT DOG LION TIGER


Polymorphism
Polymorphism is ability to take more than one form. Many form means one interface and many
method. Or Single thing with different action is called polymorphism. Polymorphism is dividing into two
types. Compile time polymorphism and run time polymorphism
Polymorphism (many forms) means one interface, multiple methods.
-It is possible to design a generic interface to a group of related activities.
-It reduces the code complexity by allowing the same interface to specify a general class of
action.
-It is the compilers job to select the specific action (ie., method) as it applies to each situation.
Dynamic binding or late binding
Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic
binding means that the code associated with a given procedure call is not known until the time of the call at
the run-time.
Classes are known as abstract data types since classes use the concept of data abstraction.
Message passing (Communication)
A message indicates 1.Object name, 2.Function name and 3.Information to be sent to the object.

Fig 4.5 Message structure


2. What is constructor? Explain the types of constructor.
Constructors
Constructor is a special member function for automatic initialization of an object. Whenever an object is
created the special member function will be executed automatically.
General format
classclass_name
{
private:
//data
public:
class_name(); // constructor declaration
};
class_name::class_name() // constructor definition
{
//statements;
}
Syntax rules for writing constructor function
Constructor name must be the same as that of its class name.
It is declared with no return type (not even void)
It will not return any value.
It may be declared either within a class or outside the class.
It may not be static.
It should have public or protected access within a class and only in rare occasion it should be
declared private.
Default Constructor
Like default arguments to functions, the constructors can also have the default arguments.
For example #include<iostream.h>
class sample
{
private:
floata,b,c;
public:
sample(float x=1.1, float y=2.2, float z=3.3) // default argument
{
a=x;
b=y;
c=z;
}
void display()
{
cout<<a<<b<<c;
}
};
void main()
{
sample s1(2.2,4.4),s2(5.5),s3(6.5,5.5,2.2),s4;
s1.display();
s2.display();
s3.display();
s4.display();
}
Output:
2.2 4.4 3.3 //(default args are 3.3)
5.5 2.2 3.3 //( default arg. is 2.2 3.3)
6.5 5.5 2.2
1.1 2.2 3.3
4.8.2 Parameterized constructors (Constructor with parameter)
If arguments are passed to constructors then those constructors are called constructors with
parameters or Parameterized constructor.
Arguments to the constructors should be given when an object is created.
The argument data type should match the member data type.
Example:
#include<iostream.h> test(int x, int y, int z)
class test {
{ a=x;
private: b=y;
inta,b,c; c=z;
public: }
test() voiddisp()
{ {
a=5; cout<<a<<b<<c;
b=10; }
c=15; };
} void main()
{ t2.disp();
test t1,t2; t3.disp();
test t3(4,8,12); }
t1.disp();
Output
5 10 15
5 10 15
4 8 12
4.8.3 Copy constructor
Copy constructor is used to declare and initialize an object from an already existing object.
Syntax
classnamenewobject(old object);
classnamenewobject = oldobject;
For example :
#include<iostream.h> a=x.a;
class sample b=x.b;
{ c=x.c;
private: }
inta,b,c; void display()
public: {
sample() // no argument constructor cout<<a<<b<<c;
{ }
a=10; };
b=15; void main()
c=20; {
} sample s1;
sample(int x, int y, int z) sample s2=s2;//copy constructor
{ sample s3(4,8,12);
a=x; sample s4(s3);//copy constructor
b=y; s1.display();
c=z; s2.display();
} s3.display();
sample(sample &x) s4.display();
{ }

Output
10 15 20
10 15 20
4 8 12
4 8 12
3. Explain in detail about operating overloading.
Operator Overloading
It is the process of defining an additional task to a predefined operator is called operator overloading.
Existing operator can only be overloaded.
Operator overloading can be carried out by means of either member functions or friend functions.
Syntax:
return_type operator operator_to_be_overloaded(list of parameters)
{
statements;
}
To define an additional task to an operator, we must specify what it means in relation to the class to
which the operator is applied. This is done with the help of a special function called operator function which
described the task.
Rules for overloading an operator
Operators that are predefined in the C++ compiler can be overloaded. Users cannot create new
operators such as $,@etc.
The overloaded operator must have at least one operand that is of user defined type.
Users cannot change operator templates.
Each operator in C++ comes with its own template which defines certain aspects of its use such as
whether it is a binary operator or a unary operator and its order of precedence. This template is fixed
and cannot be altered by overloading.
The following operators cannot be used for overloading purposes:
.(dot operator)
.* (Direct pointer to member)
:: Scope resolution operator
?: Conditional operator
sizeof(size in bytes operator)
#,## (preprocessing symbols)
Unary Operators
As the name implies takes operate on only one operand. Some unary operators are namely
++ - Increment operator
-- - Decrement Operator
! - Not operator
- - unary minus.
Binary Operators
The arithmetic operators, comparison operators, and arithmetic assignment operators come under
this category. Both the above classification of operators can be overloaded. So let us see in detail each of
this.
Overloading of Binary operator
The operators that operate on two operands are called binary operators.
The binary operators are +,-,*,/,%,<,> etc.
Whenever an arithmetic operator is used for overloading, the object oriented function is invoked with
single class objects.
For example:
/* This is the program to illustrate the use of + for finding the sum of two given objects*/
#include<iostream.h> cout<<real<<I<<img<<\n;
#include<conio.h> }
classcomplex complex operator+(complex &c1)
{ {
private: complex temp;
intreal,img; temp.real=real+c1.real;
public: temp.img=img+c1.img;
complex() return temp;
{ }
real=0; };
img=0; void main()
} {
complex(intx,int y) complex c1(10,20),c2(15,25),c3;
{ c3=c1+c2;
real=x; c1.display();
img=y; c2.display();
} c3.display();
void display() getch();
{ }
4. Explain about.
Function overloading
Function polymorphism or function overloading is a concept that allows multiple functions to share
the same name with different argument types. Function polymorphism implies that the function definition
can have multiple forms. Assigning one or more function body to the same name is known as function
overloading or function name overloading.
Example
#include<iostream.h>
#include<conio.h>
classfunctover
{
public:
void add(inta,int b)
{
cout<<add two integer no:;
cout<<a+b:<<a+b;
}
void add(inta,intb,int c)
{
cout<<add three integer no:;
cout<<a+b+c<<a+b+c;
}
void add(inta,float b)
{
cout<<add one integer and one float no:;
cout<<a+b<<a+b;
}
void add(float a,int b)
{
cout<<add two float no:;
cout<<a+b<<a+b;
}};
void main()
{
functover fn1;
fn1.add(20,30);
fn2.add(20,30,40);
fn1.add(20,20.4);
fn1.add(20.5,20.2);
getch();
}
Output
Add two integer no:
A+B: 50
Add three integer no:
A+B+C : 90
Add one integer and one float no:
A+B : 40.4
Add two float no:
A+B : 40.7
4.5.5 Friend Functions
Non-member function should not access an objects private and protected members as per the concept
of encapsulation and data hiding.
Friend functions are special functions grant a special privilege to access private & protected variables of
the class.
This privilege must be given by the class itself.
o Functions outside of class need to access and manipulate the private members of the class. This is
achieved by friend concept.
o Using friend function, we can access a different classs private members.
o The function declaration must be prefixed by the keyword friend whereas the function definition must
not.
o Friend function can be defined anywhere in the program just like ordinary function.
o The functions that are declared with the keyword friend are called friend functions. A function can be a
friend to multiple access.
General Format:
friend return type function_ name(arguments list)
{
//statement
}
Example program:#include <iostream.h>
class sample
{
inta,b;
public:
voidsetdata()
{
a=10;
b=20;
}
friend float mean(sample S);
};
float mean (sample S)
{
return float (S.a + S.b)/2.0;
}
void main()
{
sample a;
a.setdata();
cout<<mean(a);
}

Unit V
1. Define Inheritance. Explain the types of Inheritance.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class.
It supports the concept of hierarchical classification.
It provides the idea of reusability. We can add additional features to an existing class without modifying it
by deriving a new class from it.
Types of Inheritance:
Single : one base class and derived class
Multiple : Many base class to one derived class
Multilevel : derived classes in a sequential order
Hierarchical : one base class and many derived class
Hybrid : A class derived from a base class and an inheritance class
Syntax:
class base_class_name
{
//data members //member functions
};
class derived_class_name:visibility-mode base_class_name
{
//data members
//member functions
}
Single inheritance(only one base class):
If a single class is derived from a single base class is called single inheritance.

Eg:

Single inheritance
Here class A is the base class from which the class B is derived. Class A is the public derivation of
class B hence it inherits all the public members of A. But B cannot access private members of A.
Example
#include<iostream.h>
#include<conio.h>
class person
{
private:
char *name;
cahr sex;
int age;
public:
void get()
{
coout<<name:;
cin>>name;
cout<<sex;
cin>>sex;
cout<<age:;
cin>>age;
}
void displ()
{
cout<<name;<<name;
cout<<sex:<<sex;
cout<<age:<<age;
}
};

class student:public person


{
private:
int roll;
char *dept;
public:
void gets();
{
person::get();
cout<<roll no:;
cin>>roll;
cout<<dept:;
cin>>branch;
}
void displs()
{
person::despl();
cout<<roll no:<<roll;
cout<<dept:<<dept;
}};
void main()
{
student s1;
s1.gets();
s1.displs();
}
Output
Name : Mohan
Sex :M
Age : 26
Roll no : 1202
Dept : cse
Multiple Inheritance(several base class):
If a class is derived from more than one base class, it is called multiple inheritance.
Eg:

Multiple Inheritance
Here class C is derived from two base classes A & B.
General Format
class A
{
.
.
};
class B
{
..
.
};
class C:public A, public B
{
....

};
Hierarchical inheritance(One base class, many sub class):
If a number of classes are derived from a single base class then it is called hierarchical inheritance.
Eg :

Hierarchical Inheritance
General format
class A
{
.
.
};
class B:public A
{
..
.
};
class C:public A
{
....

};
class D:public B
{
.
.
};
class E:public B
{
..
.
};

class F:public C
{
.
.
};
class G:public C
{
..
.
};
Multilevel inheritance(derived from a derived class):
If a class is derived from a class, which in turn is derived from another class, is called multilevel
inheritance. This process can be extended to any number of levels.
Eg:
Multilevel Inheritance
General format
class A
{
.
.
};
class B:public A
{
..
.
};
class C:public B
{
....

};
Hybrid inheritance(combination of two inheritance):
In some situations we need to apply more than one inheritance to design a program. In such
situations we use hybrid inheritance. It is the combination of one or more types of inheritance.
Eg : Processing of students results. Adding marks obtained and weightage for sports calculate result. Marks
are obtained from class test and weightage is obtained from the class Sports. Class test is derived from the
base class student.

Hybrid Inheritance
The class result will have both the multilevel and multiple inheritances.
2. Explain about :
a. Virtual function. b. Function Template.
Virtual functions
A virtual function is a member function that is declared within a base class and redefined by a derived class.
Virtual function supports dynamic binding.
A class that declares or inherits a virtual function is called a polymorphic class.
The virtual keyword is used to declare a virtual function in a base class.
Rules for virtual functions
The virtual function must be precede by virtual keyword in the base class.
The function in the derived class must have the same name as of the virtual function defined in the
base class and the same prototype.
The function in the derived class need not be preceded by virtual keyword.
If a function with the same name is not defined in the derived class, the original base class function is
invoked.
To use virtual function, a class hierarchy should be present.
The constructor function cannot be a virtual
General Format:
virtual return_type function_name(arg list)
{
//statements
}
Example:
#include<iostream.h>
#include<conio.h>
class shape
{
public:
virtual void draw()
{
cout<<shape is drawn;
}
};
class circle:public shape
{
public:
void draw()
{
cout<<circle is drawn;
}
};
void main()
{
shape *ptrs,s;
circle c;
ptrs=&s;
ptrs->draw();
ptrs=&c;
ptrs->draw();
}
Output
Shape is drawn
Circle is drawn

Virtual Function
The variable ptrs is a pointer object to the base class shape. When the address of the base class
object is assigned to this pointer object, it can be used to call the base class draw() function. Suppose,
the address of the derived class is assigned to this pointer object, then it can be used to class the derived
class draw() function. Thus the same pointer object is used to call the base class as well as derived class
functions.
Function Templates
The templates declared for functions are called function template. Function templates are generic
function, which work for any data type that is passed to them. The data type is not specified while declaring
the function. It performs the suitable operations according to the data type we pass to them. The general
form of the function template is,
Syntax
template<typename T,>
returntype Function-name(arguments)
{
function body
}
Where template is a keyword, typename T is a template data type.
/* Program to illustrate the use of function template with multiple arguments*/
#include<iostream.h>
#include<conio.h>
template<class T>
void Max(T x, T y) // template function
{
if(x>y)
cout<<x<<is bigger \n;
else
cout<<y<<is bigger \n;
}
void main()
{
int a=2, b=5;
Max(a,b); // calling template function
float f1=3.4,f2=0.4;
Max(f1,f2);
char c1=A,c2=B;
Max(c1,c2);
char *ch1=Rohit, *ch2=Mohit;
Max(ch1,ch2);
}
Output:
5 is bigger
3.4 is bigger
B is bigger
Mohit is bigger
3. Describe about File Handling in details.
Streams and Files
A stream is a general name given to a flow of data.
In C++, a stream is represented by an object of a particular stream class.
Different streams are used to represent different kinds of data flow. In particular, streams are used for
file I/O.
Input stream
An input stream is a flow of characters into the program.
cin is a predefined input stream (defined in <iostream>).
o Can come from keyboard
o Can come from file
Output stream
An output stream is a flow of characters out of the program.
cout is a predefined output stream (defined in <iostream>).
o Can go to screen
o Can go to file

I/O Stream Class


Files streams
A file is collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.
Stream. It refers to a sequence of bytes
A stream that supplies data to the program is called Input Stream.
A stream that receives data to the program is called output Stream.
Classes for file stream creation
1. Ifstream 2.ofstream
Details of file streams
ifstream provides input operations.Open() as a default input mode
Inherits functions such as Get(), getline(), read(), seekg(),tellg().
ofstream- provides output operations.Open() as a default output mode
Inherits functions such as write(), seekp(),tellp().
fstream support simultaneous input / output operations ,Open() as default input mode
Inherits all the properties of istream and ostream through iostream.
Ways to open a file
1. Using constructor 2.Using open() function
Using constructor
Create a file stream using appropriate class. ifstream for input mode, ofstream for output mode.
Eg:
ofstream outfile(result); - writes content to fileifstream infile(result); - retrieves content from file
Using open() function
Can be used to open multiple files that uses the same stream objects.
Syntax:
<file-stream-calss><stream-object>;
<stream-object>.open(<file-name>)
Eg:
ofstream outfile;
outfile.open(result);
getline() and write() functions
To read and display a line of text using line oriented input / output function getline() and write()
function is used.
Syntax:
cin.getline(line,size);
Detecting end-of-file
if (fin.eof() !=0)It returns a non-zero value when an enf-of-file condition is encountered.
File modes
1. ios:: app append to end-of-file
2. ios:: ate go to end-of-file on opening
3. ios:: binary binary file
4. ios:: in - open file for reading only
5. ios:: nocreate open fails if the file does not exist
6. ios:: noreplace open fails if the file already exist
7. ios:: out opens file for writing only
8. ios:: trunk delete the contents of the file if exists
Eg:
fout .open(data,ios::app || ios::nocerate);
Function manipulators
Moves pointer to desired location.
1. Seekg() moves put pointer to a specific input location
2. Seekp() - moves put pointer to a specific output location
3. Tellg() gives the current position of the get pointer
4. Tellp() - gives the current position of the put pointer
Eg:Infile.seekg(10);
Closing a file
The connection with the file is closed automatically when the stream object expires or the program
terminates.
Eg:Infile.close();
Program to write in a text file
#include<fstream.h> char str[300]="Time is a great teacher but
int main() unfortunately it kills all its pupils. Berlioz";
{ fout<<str;
ofstream fout; fout.close();
fout.open("out.txt"); return 0;
}
Program to read from text file and display it
#include<fstream.h> {
#include<conio.h> fin.get(ch);
int main() cout<<ch;
{ }
ifstream fin; fin.close();
fin.open("out.txt"); getch();
char ch; return 0;
while(!fin.eof()) }
4. Explain about Exception Handling.
Exception Handling
An exception is a problem that arises during the execution of a program.
A C++ exception is a response to an exceptional circumstance that arises while a program is running, such
as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by
one or more catch blocks.
catch:represents a block of code that is executed when a particular exception is thrown. The catch keyword
indicates the catching of an exception.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Logical Error
The errors may be logical errors or syntactic mistakes (syntax mistakes). The logical errors remain in the
program due to poor understanding of the program.
Syntax Error
The syntax mistakes are due to lack of understanding of the programming language. C++ provides
exception-handling procedure to reduce the errors that a programmer makes.
Syntax
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
Program:
include<iostream.h> {
#include<conio.h> d=c/(a-b);
void main() cout<<"Result is:"<<d;
{ }
int a,b,c; else
float d; {
clrscr(); throw(a-b);
cout<<"Enter the value of a:"; }
cin>>a; }
cout<<"Enter the value of b:"; catch(int i)
cin>>b; {
cout<<"Enter the value of c:"; cout<<"Answer is infinite because a-b
cin>>c; is:"<<i;
try }
{ getch();
if((a-b)!=0) }

Potrebbero piacerti anche