Download as pdf or txt
Download as pdf or txt
You are on page 1of 108

DATA STRUCTURES &

OBJECT ORIENTED
PROGRAMMING
ECT33
B.Tech./ ECE /III SEMESTER

Prof. ELUMALAI .P
AP/CSE - ACET

Achariya College of Engineering Technology


(Approved by AICTE and affiliated to Pondicherry University)
An ISO 9001:2008 Certified Institution
Achariyapuram, Villianur, Puducherry – 605 110.
www.acet.edu.in

(For internal circulation only)


Syllabus

UNIT-I
Introduction to Algorithm – Programming principles – Creating programs-
Analyzing programs. Arrays: One dimensional array, multidimensional array. Pointers -
Searching: Linear search, Binary Search. Sorting techniques: Internal sorting - Insertion
Sort, Selection Sort, Shell Sort, Bubble Sort, Quick Sort, Merge Sort and Radix Sort.
UNIT II
Stacks: Definition – operations - applications of stack. Queues: Definition - operations -
Priority queues - De queues – Applications of queue. LinkedList: Singly Linked List,
Doubly Linked List, Circular Linked List, linked stacks, Linked queues,Applications of
Linked List.
UNIT III
Trees: Binary tree, Terminology, Representation, Traversals, Applications Graph:
Terminology, Representation, Traversals – Applications - spanning trees, shortest path
and Transitive closure, Hash tables.
UNIT IV
Principles of Object Oriented Programming - Beginning With C++ - Tokens-
Expressions-control Structures – Functions in C++, classes and objects,
constructors and destructors ,operators overloading and type conversions .
UNIT V
Inheritance: Extending classes, Pointers, Virtual functions and polymorphism, File
Handling Templates , Templates – Exception Handling .

TEXTBOOKS
1. Ellis Horowitz and Sartaj Sahni, “Fundamentals of Data Structures”, Galgotia Book
Source, Pvt. Ltd., 2004
2. D. Samanta, “Classic Data Structures”, Second Edition, Prentice-Hall of India,
Pvt. Ltd.India 2012.
3. E. Balagurusamy, “ Object Oriented Programming with C++”, McGraw Hill
Education (India)Private Limited, 6 thEdition 2013
REFERENCE BOOKS
1. Robert Kruse, C.L. Tondo and Bruce Leung, “Data Structures and Program
Design in C”, Prentice-Hall of India, Pvt. Ltd., Second edition, 2007.
2. Seymour, “Data Structures”, the McGraw-Hill, 2007.
3. Jean – Paul Tremblay & Paul G.Sorenson, An Introduction to data structures
with applications, Tata McGraw Hill edition, II Edition,2002.
Contents

Chapter 1 Introduction to Data Structures and Algorithms 1


1.1 Introduction to Algorithm 1
1.2 Programming Principles 1
1.3 Creating Programs 3
1.4 Analyzing Program 3
1.4.1 Performance Analysis 3
1.4.2 Asymptotic analysis 5
1.5 Searching Techniques 6
1.5.1 Linear Search 6
1.5.2 Binary Search 8
1.6 Sorting 8
1.6.1 Bubble sort 9
1.6.2 Selection Sorting 9
1.6.3 Insertion sorting 9
1.6.4 Quick Sorting 10
1.6.5 Merge Sorting 11
1.6.6 Radix Sorting 12
1.6.7 Shell Sorting 13
1.6.8 Heap Sorting 14
1.7 Introduction to Data structure 15
1.7.1 Types of Data Structure 15
1.8 Arrays 15
1.8.1 One Dimensional Array 15
1.8.2 Two Dimensional Array 17

Chapter 2 Linear Data Structure 18

2.1 Linked List 18


2.2 Types of Linked List 18
2.2.1 Single Linked List 18
2.2.2 Doubly Linked List 19
2.2.3 Circular Linked List 20
2.3 Applications of Linked List 20
2.3.1 Sparse matrices 20
2.3.2 Polynomial representation 21
2.3.3 Dynamic storage management 22
2.4 Stack ADT 23
2.4.1 Array implementation of stack 23
2.4.2 Operations 23
2.4.3 Linked list implementation of stack (or) Linked Stack 23

ii
2.5 Applications of stack 23
2.5.1 Infix to Postfix Conversion 23
2.5.2 Evaluation of Arithmetic Expression 25
2.5.3 Recursion 26
2.6 Queue ADT 26
2.6.1 Array implementation of queue 27
2.6.2 Operations 27
2.6.3 Circular queue 29
2.6.4 Representation of queue using linked list or Linked Queue 30
2.7 Priority Queues 30
2.8 De queues 31

Chapter 3 Trees and Graphs 34


3.1 Trees 34
3.1.1 Basic Terminology 34
3.2 Binary Trees 35
3.3 Binary Tree Representation 35
3.3.1 Linear Representation Of A Binary Tree(Array representation) 35
3.3.2 Linked List Representation 36
3.4 Traversals of a binary tree 36
3.4.1 Pre order traversal 36
3.4.2 In order traversal 37
3.4.3 Post order traversal 37
3.5 Application of Binary Tree 38
3.6 Graph 40
3.6.1 Basic Terminology 40
3.7 Graph Representation 41
3.7.1 Set representation 42
3.7.2 Linked representation 42
3.7.3 Matrix Representation 42
3.8 Graph Traversals 43
3.8.1 Depth First Search(DFS) 43
3.8.2 Breadth First Search(BFS) 45
3.9 Applications of Graph 47
3.9.1 Minimum Spanning Trees 47
3.9.1.1 Kruskal’s algorithm 47
3.9.1.2 Prims’s Algorithm 47
3.9.2 Shortest Path Problem 50
3.9.2.1 All Pair Shortest Path 50
3.9.2.2 Single Source Shortest Path Problem 51
3.9.3 Transitive Closure 53
3.10 Hash Table 53

iii
Chapter 4 Object Oriented Programming 56

4.1 Procedure Oriented Programming 56


4.2 Object Oriented Programming 56
4.3 Basic concepts of OOPS 56
4.4 Introduction to C++ 60
4.4.1 Data Types 61
4.4.2 Tokens 62
4.4.3 Expression 62
4.4.4 Control Structures 63
4.5 Functions 65
4.5.1 Call by value (pass by value) 66
4.5.2 Call by reference (pass by reference) 66
4.5.3 Inline Functions 67
4.5.4 Function overloading 68
4.5.5 Friend Functions 68
4.6 Classes 69
4.7 Objects 71
4.8 Constructors 72
4.8.1 Default Constructor 72
4.8.2 Parameterized constructors 73
4.8.3 Copy constructor 74
4.8.4 Dynamic Constructor 75
4.9 Destructors 76
4.10 Operator Overloading 77
4.10.1 Overloading of Binary operator 78
4.10.2 Overloading of Unary operators 79
4.11 Type Conversions 81
4.11.1 Basic to class type 81
4.11.2 Class type to basic type 82
4.11.3 One class to another class type 82

Chapter 5 Inheritance and Exception Handling 84

5.1 Inheritance 84
5.1.1 Types of Inheritance 84
5.1.1.1 Single Inheritance (only one base class) 85
5.1.1.2 Multiple inheritance (several base class) 86
5.1.1.3 Hierarchical Inheritance (One base class, many sub class) 87
5.1.1.4 Multilevel Inheritance (derived from a derived class) 88
5.1.1.5 Hybrid Inheritance (combination of two inheritance) 89
5.2 Extending Classes 90
5.2.1 Virtual base classes 90
5.3 Polymorphism 91
5.4 Virtual functions 93
iv
5.4.1 Pure Virtual Functions 94
5.5 Streams and File I/O 95
5.5.1 Streams and Files 95
5.5.2 Files streams 95
5.6 Templates 98
5.6.1 Function Templates 98
5.6.2 Class templates 99
5.7 Exception Handling 100
5.7.1 Multiple catch statements 102

v
Chapter 1 Introduction to Data Structures and Algorithms

1.1 Introduction to Algorithm


An Algorithm is a finite set of instructions that, if followed, accomplishes a particular
task. In addition, all algorithms should satisfy the following criteria.
• InputZero or more quantities are externally supplied.
• OutputAt least one quantity is produced.
• DefinitenessEach instruction is clear and unambiguous.
• FinitenessIf we trace out the instructions of an algorithm, then for all cases, the
algorithm terminates after a finite number of steps.
• EffectivenessEvery instruction must very basic so that it can be carried out, in
principle, by a
person using only pencil & paper.
Algorithm Specification
Algorithm can be described in three ways.
• Natural language like English: When this way is choose care should be taken,
we should ensure that each& every statement is definite.
• Graphic representation called flowchart:This method will work well when the
algorithm is small& simple.
• Pseudo-code Method:In this method, we should typically describe algorithms as
program, which resembles language like Pascal &algol.
1.2 Programming Principles
1. Comments begin with // and continue until the end of line.
2. Blocks are indicated with matching braces {and}.
3. An identifier begins with a letter. The data types of variables are not explicitly
declared.
4. Compound data types can be formed with records. Here is an example,
Node. Record
{
data type – 1 data-1;
.
.
data type – n data – n;
node * link;
}
Here link is a pointer to the record type node. Individual data items of a
record can be accessed with  and period.
5. Assignment of values to variables is done using the assignment statement.
<Variable>:= <expression>;
6. There are two Boolean values TRUE and FALSE.
 Logical Operators AND, OR, NOT
Relational Operators <, <=,>,>=, =,!=
7. The following looping statements are employed.
For, while and repeat-until

1
While Loop:
while< condition >
{
<statement-1>
.
<statement-n>
}
For Loop:
For variable: = value-1 to value-2 step do
{
<statement-1>
.
<statement-n>
}
repeat-until:
repeat
<statement-1>
.
.
<statement-n>
until<condition>
8. A conditional statement has the following forms.
 If <condition> then <statement>
 If <condition> then <statement-1>
Else <statement-1>
Case statement:
Case
{
:<condition-1>:<statement-1>
.
.
:<condition-n>:<statement-n>
:else:<statement-n+1>
}
9. Input and output are done using the instructions read & write.
10. There is only one type of procedure:
Algorithm, the heading takes the form,
Algorithm Name (Parameter lists)
 As an example, the following algorithm fields & returns the maximum of „n‟
given numbers:
1. algorithm Max(A,n)
2. // A is an array of size n
3. {
4. Result := A[1];
5. for I:= 2 to n do
6. if A[I] > Result then
7. Result :=A[I];
8. return Result;
9. }
2
1.3 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.

1.4 Analyzing Programs


1.4.1 Performance Analysis
 Space Complexity
 Time Complexity
1.Space Complexity:

3
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.
1. 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.
2.The second method to determine the step count of an algorithm is to build a table in
which we list the total number of steps contributes by each statement.

4
First determine the number of steps per execution (s/e) of the statement and the total
number of times (ie., frequency) each statement is executed. By combining these two
quantities, the total contribution of all statements, the step count for the entire algorithm
is obtained.
Table 1.1:Algorithm for Time Complexity
Statement S/e Frequency Total
1. Algorithm Sum(a,n) 0 - 0
2.{ 0 - 0
3. S=0.0; 1 1 1
4. for I=1 to n do 1 n+1 n+1
5. s=s+a[I]; 1 n n
6. return s; 1 1 1
7. } 0 - 0
Total 2n+3
Best Case
This analysis constrains on the input, other than size. Resulting in the fasters possible
run time
Worst case
This analysis constrains on the input, other than size. Resulting in the fasters possible
run time
Average case
This type of analysis results in average running time over every type of input.
1.4.2Asymptotic analysis
Expressing the complexity in term of its relationship to know function.
This type analysis is called asymptotic analysis.
Asymptotic notation
 Big „oh‟(O)
 Omega(Ω)
 Theta(Θ)
1.Big ‘oh’(O):upper limit of an algorithm running time
The function f(n)=O(g(n)) iff there exist positive constants c and no such that
f(n)≤c*g(n) for all n, n ≥ no.
2.Omega(Ω):lower limit of an algorithm running time
The function f(n)=Ω(g(n)) iff there exist positive constants c and no such that
f(n) ≥ c*g(n) for all n, n ≥ no.
3.Theta(Θ):lower limit and upper limit of an algorithm running time
The function f(n)=ө(g(n)) iff there exist positive constants c1,c2 and no such that
c1 g(n) ≤ f(n) ≤ c2 g(n) for all n, n ≥ no.
1.5 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.

5
 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

Figure 1.1 linear search


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.

6
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.
7
Fig 1.2 (c) Binary Search
Is 17 = = A[2] ? Yes
Return (2).

1.6 Sorting
It is a specific arrangement of the given numbers, alphabets orstring either in
ascending or descending order. There are two types of sorting as given below.
 Internal Sorting
 External Sorting
1.6.1 Bubble sort
 Bubble sorting is otherwise called sinking sorts
 The idea of bubble sorting is to move the highest element to nth position.
 The principle of bubble sorting is scan or read the array (n-1) times.
 For each scan, do the following steps.
Scan-1:
o Take the first no and compare with the second no. if it is small, don‟t
interchange, otherwise interchange the elements.
o Take the second no and compare with the third no. if it is small, don‟t
interchange, otherwise interchange the elements.
o This process is continued till (n-1)th element is compared with nth
element.
o At end of the scan-1, the highest element is placed on the nth position.
Repeat this process until all the element in array get sorted
Algorithm:
BUBBLE(A,N)
1. FOR I=0,1,2,3………..N-1
2. FOR J=0,1,2,3………..N-I-1
3. IFA(J)>A(J+1)
INTERCHANGE A(J),A(J+1)
END OF IF
4. INC J BY 1
5. END OF STEP 2 FOR LOOP
6. END OF STEP 1 FOR LOOP
7. PRINT THE SORTED ARRAY
Eg.Consider the numbers 7 2 8 5 4
Scan 1: scan 2: scan 3: scan 4:

Figure 1.3 Bubble Sort


8
1.6.2 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;
}
}

Figure 1.4 Selection Sort


1.6.3 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.

9
 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

Figure 1.5 Insertion Sorting


1.6.4 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[left…right]
 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)

Fig 1.6 (a) Quick Sort


When i< j
 Move i right, skipping over elements smaller than the pivot
 Move j left, skipping over elements greater than the pivot

10
When both i and j have stopped
 A[i] ≥ pivot
 A[j] ≤ pivot ⇒ A[i] and A[j] should now be swapped

Fig 1.6 (b) Quick Sort


 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

Fig 1.6 (c) Quick Sort


When i and j have crossed
 swap A[i] and pivot
Result:A[k] ≤ pivot, for k<I A[k] ≥ pivot, for k>i

Fig 1.6 (d) Quick Sort


1.6.5 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.

11
Algorithm:
merge(k,first,second,third)
1. [initialize]
i←first
j←second
l←0
2. [compare elements and find smallest]
repeat while i<second and j≤third
if k[i]≤k[j] then
l←l+1
temp [l] ←k[i]
i←i+1
else
l←l+1
temp[l] ←k[j]
j←j+1
3. [copy remaining elements]
ifi≥second
repeat while j≤third
l←l+1
temp [l] ←k[j]
j←j+1
else
repeat while i<second
l←l+1
temp[l] ←k[i]
i←i+1
4. [copy temp into k]
fori=1,2,3..l
k[first-1+i] ←temp[i]
5. [finished]
return
1.6.6 Radix Sorting
Algorithm for bucket sorting:
 It can be performed using bucket using bucket 0 to 9
 In first pass, all the elements are sorted according to lest significant bit
 In second pass, the numbers are arranged according to the next least
significant bit so on this process is repeated until it reaches the most
significant bits of all numbers.
 Number of passes in Radix sort depends upon number of digits in given
number
Example
64 ,8 ,216 ,512 ,27 ,729 ,0 ,1 ,343 ,125
pass 1: Bucket Sorts By Least Significant Digit
0 1 512 343 64 125 216 27 8 729
0 1 2 3 4 5 6 7 8 9
Fig 1.7 (a) Radix Sort
Pass 2: Bucket sort by next least significant digit
12
008 729
001 216 27
000 512 125 343 064
0 1 2 3 4 5 6 7 8 9
Fig 1.7 (b) Radix Sort
Pass 3: Bucket sort by most significant digit
064
027
008
001 125
000 216 343 512 729
0 1 2 3 4 5 6 7 8 9
Fig 1.7 (c) Radix Sort
o/p: 0,1,8.27.64.125.216.343.512.729
1.6.7 Shell Sorting
 Shell Sortis also called diminishing increment sort.
 In this method, sub-array, contain kthelementofthe original array, are sorted.
 Let A be a linear array of n numbers A [1], A [2], A [3], ...... A [n].

13
1.6.6 Heap Sorting
A heap is a complete binary tree with the property that the value at each node is
at least as large as the value at its children.
Example:
a[1] a[2] a[3] a[4] a[5] a[6] a[7]
40 80 35 90 45 50 70
Step1:Take the first element of an array.a[1]=40.

40

Step 2: Take the second element of anarray.a[2]=80.


Insert a[2] to the left side of the first element.

Step 3:Take the 3rd element .a[3]=35.Add this element to the right side of the root
node.

80

40 35

Step 4:Take the 4th element .a[4]=90.Add this element to the left side of the node 40.

Step 5:Take the 5th element .a[5]=45.Add this element to the right side of the node 80.

Step 6:Take the 6th element .a[6]=50.Add this element to the left side of the node 35.

Step 7:Take the 7th element .a[7]=70.Add this element to the right side of the node 50.

Figure 1.8 Heap Sort


14
1.7 Introduction to Datastructure
• Data Structure is a way of organizing a data that considers not only the items
stored, but also their relationship to each other in a logical manner.
• Advance knowledge about the relationship between data items allows designing of
efficient algorithms for the manipulation of data in the following ways.
o How to store a collection of data in memory,
o What operations we can perform on that data,
o The algorithms for those operations, and
o How time and space efficient those algorithms are
Abstract Data Type (Adt)
Object along with operations can be viewed as Abstract data type example: for set
ADT, we have operations as union, Intersection, size and component. A data structure
is more concrete. Typically, it is a technique or strategy for implementing an ADT
1.7.1 Types of Data Structure

Figure 1.9 Types of Data Structures

Linear Data Structures


Items are arranged in Sequential order
Ex.Arrays, Linked list, Stacks, Queues.
Non Linear data Structures
Data Items are not in Sequential order
Ex. Tree, Graph
1.8 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];
15
 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];
Height[0] refers to the first element of array
Values[0]

Values[1]
Fig 1.10 One Dimensional Array
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
16
1.8.2 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.

17
Chapter 2 Linear Data Structure

2.1 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 cell‟s 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


Fig 2.1Linked list with actual pointer value

2.2 Types of Linked List


2.2.1 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;
}

18
Insertion
Insertion require obtaining a new cell from the system by using a malloc call and
then execute two pointer change

Fig 2.2 Insertion in single linked list


Routine to insert an Element to the List
void Insert (ElementType X, List L, Position P)
/* Insert after the 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.

Fig 2.3 Deletion in single linked list


Routine to Delete an Element from the List
void Delete(int x, List L)
{
/* Delete the first occurence of x from the List */
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.
19
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 can not traverse it from last
4. It is not easy to sort the elements stored in the linear linked list
2.2.2 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

Fig 2.4Doubly 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

Fig 2.5 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.

Fig 2.6Deletion 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.
20
2.2.3 Circular Linked List
The last node points to the first one.

Fig2.7 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.
3. 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.
2.3 Applications of Linked List
 Sparse matrices
 Polynomial representation
 Dynamic storage management
2.3.1 Sparse Matrices
 A sparse matrix is a two dimensional array having the value of majority element
as null.
 In large number of application ,sparse matrices are involved. Storing of null
element is nothing but wastage of memory.so we device a technique such that
only non-null element will be stored.
 Linked list are the best solution to store them
Algorithm For Insert
Read m, n
Header =getnode(node)
If(header=null)then
Print”non availability of storage space:quit”
Exit
Else
Header.i=m
Header.j=n
Header.rowlink=header
Header.collink=header
Header.data=null

21
Fig 2.8a)Linked List Representation of a sparse matrix
2.3.2 Polynomial Representation
A polynomial ,p(x) is an expression.
The variable x of the form
axn+ b xn-1+….jx+k
wherea,b,c….k are real numbers.
N is a non-negative number.
The polynomial expression consist of two part
1.co-efficient
2.exponent
Eg: 10x1000+5x14+1
(1000,14) exponent
(10,5,1) co-efficient)
COEF EXP LINK
Fig 2.9Node Structure
Linked list representation of two polynomial
P1(x)=10x1000+5x14+1
P2(x)=3x1990-2x1492+11x+5
Type declaration of polynomial ADT
typedefstruct
{
intcoeff array[max degree +1];
inthighpower;
}*polynomial;
Polynomial addition
In order to add polynomials, say P and Q to get a resultant polynomial R, we
have to compare their terms starting at the first nodes and moving towards the end one-
by-one.two pointers Pptr and Qptr are used to move along the terms of P and Q.
There may be three cases during the comparison between terms in two polynomials.
(i) Case 1:Exponent of two terms are equal .In this case coefficients in two
nodes are to be added and a new terms will be created with the values
22
Rptr.COEFF=Pptr.COEFF + Qptr.COEFF
And
Rptr.EXP=Pptr.EXP
(ii) Case 2: Pptr.EXP>Qptr.EXP, i.e the exponent of the current term in P is
greater than the exponent of the current term in Q.then ,a duplicate of the
current term in P is created and to be inserted in the polynomial R
(iii) Case 3: Pptr.EXP<Qptr.EXP ,i.e the case when exponent of the current term
in P is less than the exponent of the current term in Q .In this case, a
duplicate of the current term of Q is created and to be inserted in the
polynomial R. The algorithm for polynomial addition is described below;
Procedure to add two polynomial
Void addpolynomial(const polynomial poly1,const polynomial poly2, polynomial
polysum)
{
inti;
zeropolynomial(polysum);
polysum->highpower=max(poly1->highpower, poly2->highpower);
for(i=polysum->highpower;i>=0;i--)
polysum->coeffarray[i]=poly1->coeffarray[i]+poly2->coeffarray[i];
}
Example
P1=3x2+5x+10
P2=5x2+2x+5
Polysum->highpower=2
for(i=2;i>=0;i--)
Polysum->coeffarray[i]=3+5=8
.o/p:8x2+7x+15
2.3.3 Dynamic storage management
The basic task of any program is to manipulate data .These data should be
stored in memory during their manipulation. There are two memory management
schemes for the storage allocation of data:
1.Static storage management2. Dynamic storage management
In the case of the static storage management scheme, the net amount of memory
required for various data for a program is allocated before the start of the execution of
the program. once memory is allocated, it can neither be extended nor be returned to
the memory bank for the use of other programs at the same time.
On the other hand , the dynamic storage management scheme allows the user
to allocate and deallocate as per the requirement during the execution of programs.
The data structure for implementing such a scheme is a linked list.
The principle in dynamic memory management scheme are
1. Allocation schemes: In this a request for a memory block will be serviced. there
are two strategies:
(a) Fixed block allocation
(b) Variable block allocation. There are four strategies under this:
First –fit and its variant ,Next – fit,Best – fit,Worst –fit.
2.Deallocation schemes: Here, we discuss how to return a memory block to the
memory bank whenever it is no longer required. Two strategies are known for the de
allocation schemes:
(i) Random Dealloction(ii)OrderedDeallocation

23
There is an one more principle called garbage collection to maintain a memory bank so
that it can be utilized efficiently.

2.4 Stack ADT


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.
Operations Of Stack
 i)push(insert) -- > insert an element to the stack
 ii)pop(delete)---> delete one element from the stack
Principle of stack is known as LIFO(last in first out)
Example

Figure 2.10 stack ADT Example


Implementation Of Stack
Two type of implementation
 Array implementation ---uses an array
 Linked list implementation--- uses a pointers
2.4.1 Array implementation of stack
If we use an array implementation, the implementation is trivial. Associated with
each stack is the top of stack, tos, which is -1 for an empty stack (this is how an empty
stack is initialized).
To push some element x onto the stack, we increment tosand then set STACK[tos] = x,
where STACK is the array representing the actual stack.
To pop, we set the return value to STACK[tos] and then decrement tos. Of
course, since there are potentially several stacks, the STACK array and tosare part of
one structure representing a stack.
2.4.2operations
Insertion: - Push Deletion- Pop
If top>= size then Routine to delete an element in stack
Print”stack is full” If top<1 then
Print”stack is empty”
Else
Else
Top=top+1 Item=a[top]
A[top]=item Top=top-1
Endif Endif
Stop Stop
After Insertion (top= top+1) - going to insert an element 5After deletion (top= top-1)

24
Fig 2.11 After Insertion On a StackFigure 2.12 After Deletion Ona Stack
2.4.3 linked list implementation of stack(or) Linked Stack
We perform a push by inserting at the front of the list. We perform a pop by deleting the
element at the front of the list. A top operation merely examines the element at the front
of the list, returning its value. popon an empty stack or a push on a full stack will
overflow the array bounds and cause a crash.

Fig 2.13Linked Stack


Routine:
Push: Pop:
New=getnode(node) Iftop=null
New->data =item Print”stack is empty”
Exit
New->link=top
Else
Top=new Ptr=top->link
Stack_head->link=top Item=top->data
Stop Stack_head->link=ptr
Top=ptr
Endif
Stop

2.5 Applications of stack


1.Infix To Postfix Conversion
2.Postfix Expression Evaluation
3.Dynamic Memory Management
2.5.1 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.
25
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:

Fig 2.14(a)
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

Fig 2.14(b)
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 '+'.

Figure 2.14(c)

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

Fig 2.14(d)
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.

Fig 2.14(e)
26
The next symbol read is a '+'. We pop and output '*' and then we push '+'. Then we
read and output

Fig 2.14(f)
Now we read a ')', so the stack is emptied back to the '('. We output a '+'.

Fig 2.14(g)
We read a '*' next; it is pushed onto the stack. Then g is read and output.

Fig 2.14( h)
The input is now empty, so we pop and output symbols from the stack until it is empty.

Fig 2.14(i)
2.5.2 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 .

Fig 2.15 Postfix Expression Evaluation


Algorithm forEvaluating a postfix expression
operand_stack = empty stack
while (not end of input)
symbol = next input symbol
if (symbol is operand)
push(operand_stack, symbol)
27
else
operand2 = pop(operand_stack)
operand1 = pop(operand_stack)
result = apply symbol to operand1 and operand2
push(operand_stack, result)
return pop(operand_stack)
2.5.3 Recursion
Recursion is the name given to the technique of defining a set or a process in
terms of itself.
The factorial function, whose domain is the natural numbers, can be recursively
defined as
1, if N = 0
FACTORIAL(N) = N * FACTORIAL(N-1), otherwise
Here FACTORIAL(N) is defined in terms of FACTORIAL(N-1), which in turn is defined
in terms of FACTORIAL(N-2), etc., until finally FACTORIAL(0) is reached, whose value
is given as “one”.
A procedure that contains a procedure call to itself, or a procedure call to a
second procedure which eventually causes the first procedure to be called, is known as
a recursive procedure.
Algorithm:-
Variables used:
A  Stack to store an activation record associated with each
recursive call.
RET_ADDR  To store the return address.
TOP  refers to the top element of the stack.
TEMP_REC Temporary record to stimulate the proper transfer of
control.
PARM,ADDRESS  Variables of the temporary record.
Algorithm FACTORIAL.
1. [Save N and return address]
Call PUSH(A,TOP,TEMP_REC)
2. [Is the base criterion found?]
If N = 0
Then FACTORIAL  1
Go to step 4
Else PARAM  N-1
ADDRESS  step 3
Go to step 1
3. [Calculate N]
FACTORIAL  N * FACTORIAL (the factorial of N)
4. [Restore previous N and return address]
TEMP_REC POP(A,TOP)
(i.e., PARAM  N,ADDRESS RET_ADDR, pop stack)

2.6 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.

28
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.
2.6.1 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

Fig 2.16Array 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
2.6.2 Operations
Enqueue :
To enqueueanelement , we increment queue size and queue rear, then set
QUEUE[rear] = element.
Ex: Insert/enqueue 8

Fig2.17After Insertion On aQueue

29
Routine for Enqueue in Queue Routine for Dequeue
If (rear = N) then If(front=0)then
Print”queue is full” Print”queue 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:

Fig 2.18 After Deletion On a Queue


Operation Of Queue – Example

30
Fig 2.19Operation Of Queue
Disadvantage:
There is one potential problem with this representation.with this representation,a
queue may not be full,still a request for insertion operation may lead to the problem.for
an example on request (3) in figure 8 rooms are available but insertion is not possible
as insertion pointer reaches the end of the queue.thissimplies wastage of storage.
The simple solution is that whenever front or reargets to the end of the array, it is
wrapped around to the beginning. This is known as a circular array implementation or
circular queue.
2.6.3 Circular queue
Circular array queue is same as ordinary array queue.say, A[1…..N],but logically
it implies that A[1] comes after A[N] or after A[N] ,A[1} appears.

Fig 2.20Circular Queue

31
Fig 2.21 Trace Of Insertion And Deletion Operations On a Circular Queue
2.6.4 Representation of queue using linked list or Linked Queue
We perform a enqueuby inserting at the end of the list. We perform a dequeue
by deleting the element at the front of the list.

Fig 2.22 Linked Queue

2.7 Priority Queues


Priority queues are a generalization of stacks and queues. Rather than inserting
and deleting elements in a fixed order, each element is assigned a priority represented
by an integer. We always remove an element with the highest priority, which is given by
the minimal integer priority assigned.
Priority queues often have a fixed size.

Fig 2.23 Priority Queue


Implementation of priority queue using array
With this representation,an array can be maintained to hold the item and its
priority value.The element will be inserted at the REAR end as usual. The deletion will
then be performed either of following ways
(a) Starting from the FRONT pointer , traverse the array for an element of the
highest priority. Delete this element from the queue. If this is not the front most
element shift all its trailing element after the deleted element one stroke each to
fill up the vacant position fig

Fig 2.24 Deletion Operation in an Array Representation of a Priority Queue


32
(b) Add the elements at the REAR end as earlier.using a stable sorting algorithm,
*sort the elements of the queue so that highest priority elements is at the FRONT
end. when a deletion is required, delete it from the FRONT end only

Fig 2.25InsetionOperation in an Array Representation of a Priority Queue


Linked List Implementation Of Priority Queue:
This representation assumes the node structure as shown in the figure 2.35.
LLINK and RLINK are two usual link fields,DATA is to store the actual content and
PRIORITY is to store the priority value of the item.
LLINK DATA PRIORITY RLINK

Fig 2.26Node Structure

2.8 De queues
Another variation of the queue is known as deque (pronounced as „deck‟).unlike
queue ,in dequeue ,both insertion and deletion operation can be made at either end of
the structure. Actually , term deque is originated from Double Ended Queue.such
structure Is shown in figure

Fig 2.27 De-queues


It isclear from the deque structure that it is a general representation of both stack
and queue,or in other words, a deque can be used as a stack as well as a queue.
There are various ways of representing a deque in a computer.one simpler way
to represent is using a double linked list.Another popular representation is using a
circulerarray( as used in circular queue)
Following four operation are possible on a deque
1.PUSHDQ(ITEM): To insert ITEM at the FRONT end of deque
2.POPDQ():To remove the FRONT item from deque
3.INJECT(ITEM):to insert ITEM at the REAR end of deque
4.EJECT():To remove the REAR ITEM from deque
These operations are described for a deque based on a circular array of length
LENGTH.
Algorithm :PUSHDQ(ITEM)
if(front=1)then if(ahead=rear)then
ahead=LENGTH print”deque is full”
else exit
if(front=length)or(front=0)then else
ahead=1 front=ahead
else dq[front]=item
ahead=front-1 stop
endif

33
Chapter 3 Non-Linear Data Structure

3.1 Trees
3.1.1 Basic Terminology
Treeis a non-linear data structure defined as a finite set of one or more nodes such
that
 There is one specially designated node called ROOT and
 The remaining nodes are partitioned into a collection of sub-trees of the root
each of which is also a tree.
Example

Fig 3.1 Tree With Their Levels


Nodestands for item of information. The nodes of a tree have a parent-child
relationship. The root does not have a parent ; but each one of the other nodes has a
parent node associated to it .
A node may or may not have children is called a leaf node or terminal nodes.A line
from a parent to a child node is called a branch .If a tree has n nodes, one of which is
the root there would be n-1 branches.
 The number of sub-trees of a node is called its degree. The degree of A is
2, F is 1 and J is zero. The leaf node is having degree zero and other
nodes are referred as non-terminals.
 The degree of a treeis the maximum degree of the nodes in the tree.
 Nodes with the same parent are called siblings. Here D & E are all
siblings. H & I are also siblings.
 Thelevel of a nodeis defined by initially letting the root be at level zero. If
a node is al level l, there its children are at level l+1.
 The height or depthof a tree is defined to be the maximum level of any
node in the tree.
 A set of trees is called forest; if we remove the root of a tree we get a
forest. In the above fig, if we remove A, we get a forest with three trees.

34
If A is the root of a binary tree and B is the root of its left or right sub-tree, then A
is said to be the parent of B and B is said to be the left or right child of A.
Node n1 is an ancestor of node n2, if n1 is either the parent of n2 or the parent
of some ancestor of n2.

3.2 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.
3.3 Binary Tree Representation
3.3.1 Linear Representation of A Binary Tree(Array representation)
The linear representation method of implementing a binary tree uses a one-
dimensional array of size ((2^d+1)-1) where d is the depth of the tree.
Once the size of the array has been determined the following method is used to
represent the tree.The root node is at location 1.
1. For any node with index I, 1<i ≤ n
(a) PARENT(i) = [i/2]For the node when i=1 ,there is no parent.
(b) LCHILD(i) = 2*I If 2*i>n,then I has no child.
(c) RCHILD(i) = 2*i+1If 2*i+1>n,then I has no right child.

Fig 3.3 Array Representation of A Binary Tree


A binary tree of height h can have at most 2h-1 nodes. So, the size of the array to fit
such a binary tree is 2h-1
Advantages
1. Given a child node , its parent node can be determined immediately. If a child
node is at location N in the array, then its parent is at location N/2.

35
2. It can be implemented easily in languages in which only static memory allocation
is directly available.
Disadvantages
1. Insertion or deletion of a node causes considerable data movement up and
down the array, using an excessive amount of processing time.
2. Wastage of memory due to partially filled trees.

3.3.2 Linked List Representation:


Linked lists most commonly represent binary trees. Each node can be
considered as having 3 elementary fields : a data field, left pointer, pointing to left sub-
tree and right pointer pointing to the right sub-tree.

Fig 3.4 Structure Of Node In Linked List Representation


The following figure is an example of linked storage representation of a binary
tree.

Fig 3.5Binary tree Fig 3.6Linked representation of a binary


tree
Although for most purposes the linked representation of a binary tree is efficient,
it does have certain disadvantages. Namely,
1. Wasted memory space is well pointers.
2. Given a node, it is difficult to determined to parent.
3. Its implementation algorithm is more difficult in languages that do not offer
dynamic storage techniques.

3.4 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

36
3.4.1 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

Fig 3.7 Binary Tree


Solution: A B D E C
Routine:
Ptr=root
If(ptr≠NULL)then
Visit(ptr)
Preorder(ptr->LC)
Preorder(ptr->RC)
Endif
stop
3.4.2 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

Fig 3.8 Binary Tree


Solution: D B E A C
Routine:
Ptr=root
If(ptr≠NULL)then
Inorder(ptr->LC)
Visit(ptr)
Inorder(ptr->RC)
Endif
stop
37
3.4.3 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

Figure 3.9 Binary Tree


Solution D E B C A
Routine:
Ptr=root
If(ptr≠NULL)then
Postorder(ptr->LC)
Postorder(ptr->RC)
Visit(ptr)
Endif
Stop

3.5 Application of binary tree


Binary Expression Trees
 Binary trees are a good way to express arithmetic expressions.
 The leaves are operands and the other nodes are operators.
 The left and right subtrees of an operator node represent subexpressions that
must
be evaluated before applying the operator at the root of the subtree.

Fig 3.10Binary Expression Trees


Example
The input is: a b + c d e + * *
Since the first two symbols are operands, one-node trees are created and pointers are
pushed to them onto a stack. For convenience the stack will grow from left to right.

38
Fig 3.10 (a)
The next symbol is a '+'. It pops the two pointers to the trees, a new tree is formed, and
a pointer to it is pushed onto to the stack.

Fig 3.10 (b)


Next, c, d, and e are read. A one-node tree is created for each and a pointer to the
corresponding tree is pushed onto the stack.

Fig 3.10 (c)


Continuing, a '+' is read, and it merges the last two trees.

Fig 3.10 (d)


Now, a '*' is read. The last two tree pointers are popped and a new tree is formed with a
'*' as the root.

Fig 3.10 (e)


Finally, the last symbol is read. The two trees are merged and a pointer to the final tree
remains on the stack.
39
Fig 3.10 (f)
3.6 Graph
A graphs g consists of a set V of vertices (nodes) and a set E of edges (arcs). We
write G=(V,E). V is a finite and non-empty set of vertices. E is a set of pair of
vertices; these pairs are called as edges . A graph can be pictorially represented
as follows,

Fig 3.11 Graph


We have numbered the graph as 1,2,3,4. Therefore, V(G)=(1,2,3,4) and E(G) =
{(1,2),(1,3),(1,4),(2,3),(2,4)}.
3.6.1 Basic Terminology
Undirected Graph
All edges are undirected (i.e) edge does not indicate direction is said to be
undirected Graph. We can “travel” in either direction
G = (V, E) where E is a set of unordered pairs

Fig 3.12 Undirected graph


Directed Graph
An directed graph is that in which , each edge is an ordered pair of
vertices, (i.e.) each edge is represented by a directed pair. It is also referred to as
digraph.

Fig 3.13 Directed Graph Fig 3.14 Strongly Connected Graph


40
Strongly Connected Graph
A digraph is said to be strongly connected if there is a directed path from any
vertex to any other vertex.
Weakly Connected Graph
If there does not exist a directed path from one vertex to another vertex
then it is said to be a weakly connected graph.
Weighted Graph
A Graph is termed weighted graph if all the edges in it are labeled with some
weights.

Fig 3.15 Weakly Connected GraphFigure 3.16 Weighted Graph


Complete Gaph
A Graph (digraph) G is said to be complete if each vertex vi, is adjacent to every
other vertex vj in G.(i.e) there are edges from any vertex to all other vertices.

Fig 3.17 Complete Gaph Fig 3.18 Cycle


Adjacent Vertices
A vertex vi is adjacent to another vertex say vj, if there is an edge from vi to vj.
Path
A path in a graph is a sequence of adjacent vertices. The length of a path is one
lessthan the number of vertices in the path. • A simple path is a path with no repeated
vertices
Cycle
 A cycle is a path in which the first and the last vertices are the same.
 A directed graph with no cycles is a directed acyclic graph (DAG).
If there is an edge whose strating and end vertices are same , that is ,(vi,vi)is
aedge,then it is called as self loop.
3.7 Graph Representation
The graphs can be represented by the follow three methods
 1.Set representation
 2.Linked representation
 3.Matrix representation

41
Fig 3.19 Graph
3.7.1 Set representation
This is one of the straightforward methods of representing a graph.with this method,
two sets are maintained:
(i)V, the set of vertices
(ii)E, the set of edges
But if the graph is weighted, the set E is the ordered collection of three tuples,that is,
E=W*V*V,where W is the set of weights.
Graph G1
V(G1)={ V1,V2,V3,V4,V5,V6,V7}
E(G1)={(V1,V2),(V1,V3),(V2,V4),(V2,V5),(V3,V4),(V3,V6),(v4,v7),(v5,v7),(v6,v7)}
3.7.2 Linked representation
Linked representation is another space-saving way of graph representation. In this
representation, two types of node are assumed as shown in figure
NODE_LABEL ADJ_LIST WEIGHT NODE_LABEL ADJ_LIST

Node Structures for non-weighted graph Node structure for weighted


graph
Fig 3.20 Node Structures In Linked Representation
Now, let us see, how the graphs in figure 3.19 can be represented with the linked
representation

Fig 3.21Linked representation of Graph


3.7.3 Matrix Representation
Matrix representation is the most useful way of representing any graph. This
representation uses a square matrix of order n*n, n being the of vertices in the graph.
Entries in the matrix can be decided as follows;

42
aij = 1, if there is an edge from vi t0 vj
= 0, otherwise
This matrix is known as adjacency matrix because an entry stores the information
whether two vertices are adajacent or not.
Now, let us see, how the graphs in figure 3.19 can be represented with the Matrix
Representation

Fig 3.22 Matrix Representation of Graph

3.8 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)
3.8.1 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.

Fig 3.23 Graph


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

43
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
44
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
3.8.2 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
45
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

46
3.9Applications of Graph
3.9.1Minimum 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.kruskal‟s algorithm2.prim‟s algorithm
3.9.1.1 kruskal’s algorithm
To obtain a minimum spanning tree of a graph, a novel approach was devised by J.B
KRUSKAL known as kruskal‟s 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

3.9.2.2Prims’s Algorithm
According to prim‟s algorithm ,a minimum spanning tree grows in successive
stages.The prim‟s algorithm find a new vertex to add it to the tree by choosing the edge

47
<vi,vj>,the smallest among all edges, where vi I the tree and vjis yet to be included in
the tree.
The prim‟s 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

48
The minimum spanning tree obtained is

Fig 3.24 Minimum Spanning Tree


49
3.9.2 Shortest Path Problem
This problem of a graph is about finding a path between two vertices in
such a way that this path will satisfy somecriteria of optimization.forexample,for a non-
weighted graph,the number of edges will be minimum and for a weighted graph,the
sum of weights on all edges in the path will be minimum.
3.9.2.1 All Pair Shortest Path
In the all-pair shortest problem we must find the shortest paths between all pairs
of vertices, vi, vj.A few important algorithms are warshall‟salgorithm,folyd‟s Algorithm
Floyd’s algorithm :
warshall‟s algorithm shows the presence or absence of any path between a pair
of vertices.it does not take into account the weights of edges.
If weights are to be taken in account and if we are interested in the length of the
shortest path between any pair of vertices,then another classical solution is known
asFloyd‟s algorithm .
It use two function namely, Min(x,y) and combine(p1,p2).min(x,y) returns the minimum
value between x and y,and combine(p1,p2) returns the concationation of two path p1
and p2 resulting in single path.
Step 1: Let G=<N,A> be a directed graph ‟N‟ is a set of nodes and „A‟ is the set of
edges.
Step 2: Each edge has an associated non-negative length.
Step 3: We want to calculate the length of the shortest path between each pair of
nodes.
Step 4: Suppose the nodes of G are numbered from 1 to n, so N={1,2,...N},and
suppose G matrix L gives the length of each edge, with L(i,j)=0 for
i=1,2...n,L(i,j)>=for all i& j, and L(i,j)=infinity, if the edge (i,j) does not exist.
Step 5: The principle of optimality applies: if k is the node on the shortest path
from i to j then the part of the path from i to k and the part from k to j must also be
optimal, that is shorter.
Step 6: First, create a cost adjacency matrix for the given graph.
Step 7: Copy the above matrix-to-matrix D, which will give the direct distance
between nodes.
Step 8: We have to perform N iteration after iteration k.the matrix D will give you
the distance between nodes with only (1,2...,k)as intermediate nodes.
Step 9: At the iteration k, we have to check for each pair of nodes (i,j) whether or
not there exists a path from i to j passing through node k.
Example:

Fig 3.25floyd’s algorithm and work


Step 1: Cost Adjacency Matrix
D0=L=

50
Step 2: Change the infinity Value

Step 3: Find the shortest path for(2,1)

Step 4: Find the shortest path for(1,3) and (2,3)

 D4 will give the shortest distance between any pair of nodes.If you want the
exact path then we have to refer the matrix p.The matrix will be,

 Since [1,3]=4,the shortest path from 1 to3 passes through 4.Looking now at
p[1,4]&p[4,3] we discover that between 1 & 4, we have to go to node 2 but that
from 4 to 3 we proceed directly.Finally we see the trips from 1 to 2, & from 2 to 4,
are also direct.The shortest path from 1 to 3 is 1,2,4,3.
3.9.2.2 Single Source Shortest Path Problem
In this problem ,there is a distinct vertex, called source vertex and it requires to
find the shortest path from this source vertex to all other vertices.It is an example of
Single source shortest problem ,which generally solve problem in stages by selecting
what appears to be best thing at each stage.
Dw=dv+cvw

let us choose vertex „A‟ as a source vertex


Step 1 Step 2
A T 0
B F 7
C F 2
51
D T 1
A T 0 E F -
B F -
C F 2
D F 1
E F -
Step 3 Step 4 Step
5

A T 0 A T 0 A T 0
B F 7 B T 7 B T 7
C T 2 C T 2 C T 2
D T 1 D T 1 D T 1
E F 8 E F 8 E T 8
3.9.3Transitive Closure
A problem related to the all pairs shortest path problem is that of determining for
every pair of vertices i,j in G the existence of a path from i to j. Two cases are of
interest, one when all path lengths (i.e., the number of edges on the path) are required
to be positive and the other when path lengths are to be nonnegative. If A is the
adjacency matrix of G, then the matrix A+ having the property A+(i,j) = 1 if there is a
path of length > 0 from i to j and 0 otherwise is called the transitive closure matrix of G.
The matrix A* with the property A*(i,j) = 1 if there is a path of length0 from i to j and 0
otherwise is the reflexive transitive closure matrix of G.

(d)A*
Fig 3.26 showsA+ and A*for a digraph.

52
3.10 Hash Table
HashingHashing is a technique used for performing insertion, deletion and finds in a
constant average time.
Hash table The hash table data structure is an array of some fixed size, containing the
keys. The table size is generally denoted by the variable TableSize. Each key is
mapped into some numbers in the range o to TableSize-1 and placed in the appropriate
cell.
In the above example, John hashes to 3 ,Phil hashes to 4, Dave hashes to 6 and
Mary hashes to 7. The main problem in hashing as to choose the hash function
Hash Function
Hash function is a function which,when applied to the key, produce an integer
which can be used as an address in a hash table
There are two important properties to choose a Hash function.
 The function should be very easy and quick to compute.
 The function should give two different indices for two different key values.
There are so many methods to calculate the hash value
(i) Mid-Square Method:
A key is multiplied by itself and the address is obtained by choosing an
appropriate number of bits or digits from the middle of the square. The selection of
bits or digits based on the table size and also they should fit into one computer word
of memory.
E.g.: consider a key, 56789 and when it is squared we get 3224990521. If the three
digit address needed, then position 5to7 may chosen, given address 900.
(ii) Division Method:
In this method, integer X is to divide by M and d then to use the remainder modulo
M.
The hash function is
H(x) =x mod M
Great care should be taken while choosing value for M and preferable it should be
even number. By making M a large prime number the keys are spread out evenly.
(iii) Folding Method:
A key is partitioned into a number of parts, each of which has the same length as
the required address. The parts are then added together, ignoring the finial carry, to
form an address. For e.g. ., if keys 356942781 is to be transformed into a three-digit
address.
Two types:
1. Fold- shifting: 356,942 and 787 are added to yield 079.
2. Fold-boundary method; 653, 942, and 187 are added together, yielding 782.
(iv) Digit Analysis Method:
A hashing function referred to as digit analysis forms addresses by selecting and
shifting digits or bits of the original key. For eg., a key 7546123 is transformed to the
address 2164 by selecting digits in positions 3to6 and revising their order. Digit
positions having the most uniform distributions are selected. This hashing
transformation technique has been used in conjunction with static key sets.
Overflow handling (or) collision-resolution technique:
If hash function produce same address value for different key then
53
The general objective of a collision-resolution technique is to attempt to place
colliding records elsewhere in the table. This requires the investigation of a series of
table positions until an empty one is found to accommodate a colliding record.
Some important technique to handle collision are
(i)separate chaining(An array of linked list implementation).
(ii)open addressing(Array-based implementation)
1.Linear probing 2. Quadratic Probing 3.Double Hashing
(i) Separate chaining
It is used to keep the list of all elements that hash to same value. This list have
header similar to linked list implementation.
For Example
Hash function=Xmod10
And input keys 43,54,26,12,62,33,66

Fig 3.27 Separate Chaining


Disadvantage:
Separate chaining hashing has the disadvantage of requiring pointers. this tends
to slow the algorithm down a bit because of time required to allocate new cells
Open Addressing:
In open addressing ,if a collision occurs, alternate cells are tried until an empty
cell is found.
Some of the technique used are
1. Linear probing 2.Quadratic Probing
(i)Linear probing:
Here, the function f is defined as f (i)=i.
It indicates that whenever we encounter collision, the next available cell is searched
sequentially and data elements are placed accordingly.
For Example ,Hash function=Xmod10And input keys 43,54,12,42
Step 1: input key 43, 43%10=3, insert 43 in the address 3
0 1 2 3 4 5 6
43
Step 2:input key 54, 54%10=4,insert 54 in the address 4
0 1 2 3 4 5 6

54
43 54
Step 3:input key 12, 12%10=2
0 1 2 3 4 5 6
12 43 54

Step 4:input key 42, 42%10=2, 42 collides with 12,so it is put in next available position
0 1 2 3 4 5 6
12 43 54 42
(ii)Quadratic Probing
In this case, when the collision occurs at hash address h, then this method searches
the table at location i2 position. The hash function will now be defined as F(i)=i2
For Example
Hash function=Xmod10
And input keys 43,54,12,42
Step 1:input key 43, 43%10=3,insert 43 in the address 3
0 1 2 3 4 5 6
43
Step 2:input key 54, 54%10=4,insert 54 in the address 4
0 1 2 3 4 5 6
43 54

Step 3:input key 12, 12%10=2


0 1 2 3 4 5 6
12 43 54
Step 4:input key 42, 42%10=2, 42 collides with 12,so it search for empty cell one away
(12=1),but another collision occurs .so it search for next option (22=4)

55
Chapter 4

4.1 Procedure Oriented Programming


Structure of Procedure oriented language
 Programming languages (high-level language) such as COBOL, FORTRAN
and C are commonly known as Procedure oriented language (POP).
 In POP, each function is written to perform particular task. Ex: reading,
calculating and printing.
Some characteristics of procedure-oriented language.
 Emphasis is on doing things (algorithms).
 Larger programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Follows top-down approach in program design.

Fig 4.1 Procedure oriented language Fig 4.2: Object Oriented Paradigm
4.2 Object Oriented Programming
Object-oriented programming took the best ideas of structured programming and
combined them with several new concepts. A program can be organized in one of two
ways: around its code (what is happening) or around its data (who is being affected).
Using only structured programming techniques, programs are typically organized
around code. This approach can be thought of as “code acting on data.” Object-
oriented programs work the other way around. They are organized around data, with
the key principle being “data controlling access to code.”
Languages that support OOPS concepts
C++, Small talk, Object Pascal, Java
Four applications of OOPS
 Real-time systems.
 Simulation and modeling.
 Object-oriented databases.
 AI(Artificial Intelligence) and expert systems.
Features of OOPS.
 Emphasis is on data rather than on procedure.
 Programs are divided into objects.
 Data is hidden and cannot be accessed by external functions.
56
 Follows bottom-up approach in program design
 Data structures are designed such that they characterize the objects
 Objects may be communicate with each other through functions
4.3 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

57
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

Fig 4.4 Inheritance

58
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 compiler‟s 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


-OOP consists of a set of objects that communicate with each other.
-Objects communicate with one another by sending and receiving information.
Process of programming (OOP):
Steps:
1. Creating classes that define objects and their behaviours.
2. Creating objects from class definitions.
3. Establishing communication among objects.
Data members and member functions
Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight, and cost and uses functions to operate on these
attributes.
The attributes are sometimes called as data members because they hold
information. The functions that operate on these data are called as methods or member
functions.
Example: inta,b; // a,b are data members
void getdata ( ) ; // member function
Abstract Classes
-Serves only as a base class.
- We can derive classes fromabstract class.
-A base class contains pure virtual function.

59
-Pure Virtual function is a function whose body is equated to 0 ( has no code).
-Abstract classes are reusable and the programmer can extend them.
-Abstract classes with virtual function can be used as an aid to debugging.
Table 4.1 Difference between Procedure Oriented and Object Oriented
Programming

Procedure Oriented Programming Object Oriented Programming


 Top-down approach  Bottom up approach
 Large programs are divided into
 Programs are divided into Objects
functions
 No reuse  Reusability
 Software complexity cannot be  Software complexity easily can be
managed managed
 OOP can be easily upgraded from
 Up gradation is very difficult
small to large systems
 Emphasis is on doing  Emphasis is on data rather than
things(algorithms) procedure
 New data and functions can be
 Scalability is not available
easily added whenever necessary
 E.g. C, COBOL, FORTRAN, etc.,  E.g. C++, JAVA, etc.,
 Data driven  Message passing

4.4Introduction to C++
 OOP means Object Oriented Programming. This is a technique used to create
programs around the real world entities.
 In OOPs programming model, programs are developed around objects and data
rather than actions and logics.
 In OOPs, every real life object has properties and behavior. C++, Java, Smalltalk
are said to be object oriented programming language.
Object oriented programming as a paradigm is popularly an increasingly
significant role in the analysis, design and implementation of software systems.
C++:
An extension to the C language developed primarily by B.Stroustrup at AT&T
Bell Laboratories: it supports object-oriented programming among other enhancements.
The history of C++ begins with C. The reason for this is easy to understand: C++
is built upon the foundation of C. Thus, C++ is a superset of C. C++ expanded and
enhanced the C language to support object-oriented programming (which is described
later in this module). C++ also added several other improvements to the C language,
including an extended set of library routines. However, much of the spirit and flavor of
C++ is directly inherited from C.
C++ was invented by Bjarne Stroustrup in 1979, at Bell Laboratories in Murray
Hill, New Jersey. He initially called the new language “C with Classes.” However, in
1983 the name was changed to C++. Stroustrup built C++ on the foundation of C,
including all of C‟s features, attributes, and benefits.

60
Table 4.2 Difference between C and C++

C C++

1. C++ is non Procedural i.e Object oriented


1. C is Procedural Language.
Language.

2. The concept of virtual Functions are used in


2. No virtual Functions are present in C
C++.

3. The concept of polymorphism is used in C++.


3. In C, Polymorphism is not possible. Polymorphism is the most Important Feature of
OOPS.

4. Operator overloading is not possible in 4. Operator overloading is one of the greatest


C. Feature of C++.

5. Top down approach is used in 5. Bottom up approach adopted in Program


Program Design. Design.

6. Multiple Declarations of global 6. Multiple Declarations of global variables are


variables are allowed. not allowed.

7. In C 7. In C++
 scanf() Function used for Input.  Cin>> Function used for Input.
 printf() Function used for output.  Cout<< Function used for output.

8. C requires all the variables to be 8. C++ allows the declaration of variable


defined at the starting of a scope. anywhere in the scope i.e at time of its First use.

9. No inheritance is possible in C. 9. Inheritance is possible in C++

10. It supports built-in and primitive data 10.It support both built-in and user define data
types. types.

11. In C, Exception Handling is not 11. In C++, Exception Handling is done with Try
present. and Catch block.

4.4.1 Data Types


Defines a set of values and a set of operations that can be applied on those
values. Below is a list of the most commonly used Data Types in C++ programming
language:
shortint :This data type is used to represent short integer.

61
int:This data type is used to represent integer.
longint:This data type is used to represent long integer.
float:This data type is used to represent floating point number.
double:This data type is used to represent double precision floating point
number.
long double:This data type is used to represent double precision floating point
number.
char:This data type is used to represent a single character.
bool: This data type is used to represent boolean value. It can take one of two
values: True or False.
Data types can be classified as

Fig 4.6 Data Types


4.4.2 Tokens
A token is the smallest element of a C++ program that is meaningful to the
compiler. The C++ parser recognizes these kinds of tokens: identifiers, keywords,
literals, operators, punctuators, and other separators. A stream of these tokens makes
up a translation unit. Tokens are usually separated by "white space." White space can
be one or more
 Blanks
 Horizontal or vertical tabs
 New lines
 Formfeeds
 Comments
4.4.3 Expression
An expression is a combination of variables constants and operators written
according to the syntax of C language. In C++ every expression evaluates to a value
i.e., every expression results in some value of a certain type that can be assigned to a
variable.
Type of operators used in an expression determines the type of expression.
Arithmetic Expressions
 Arithmetic evaluation was one of the motivations for the development of the first
programming languages
 Arithmetic expressions consist of operators, operands, parentheses, and
function calls.

62
Operators
• A unary operator has one operand
• A binary operator has two operands
• A ternary operator has three operands
Operator Precedence Rules
• The operator precedence rules for expression evaluation define the order in
which “adjacent” operators of different precedence levels are evaluated
• Typical precedence levels
Parentheses,unary operators, ** (if the language supports it), *, /, +, -
Relational and Boolean Expressions
• Relational Expressions
– Use relational operators and operands of various types
– Evaluate to some Boolean representation
– Operator symbols used vary somewhat among languages (!=, /=, .NE.,
<>, #)
4.4.4 Control Structures
A program is usually not limited to a linear sequence of instructions. During its
process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides
control structures that serve to specify what has to be done by our program, when and
under which circumstances.
It is of three types:
– Sequence structure
• Programs executed sequentially by default
– Selection structures
• if, if/else, switch
– Repetition structures
while, do/while, for
Just like C, C++ supports all the control structures of C. The control structures if,
and switch is selection structures. The control structures do...while, while, and for are
called loop structure.
I. Selection structures
If:
The if keyword is used to execute a statement or block only if a condition is
fulfilled. Its form is:
if (condition)
{
Statements
}
If this condition is true, statement is executed. If it is false, statement is ignored
(not executed) and the program continues right after this conditional structure.
If else:
If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.
if(condition)
{
63
Statement;
}
else
{
Statement;
}
Switch-case
The switch-case is another conditional structure that may or may not execute
certain statements.
switch(expression)
{
case constant1:
statements;
...
break;
case constant2:
statements;
...
break;
.
default:
statements;
}
Switch evaluates expression and checks if it is equivalent to constant1; if it is, it
executesstatements until it finds the break statement. When it finds
this break statement, the program jumps to the end of the entire switch statement.
If expression was not equal to constant1, it is then checked against constant2. If
it is equal to this, it executes statements until a break is found, when it jumps to the end
of the switch.
Finally, if the value of expression did not match any of the previously specified
constants the program executes the statements included after the default: label, if it
exists.
II. Repetition structures
Loops repeat a statement a certain number of times, or while a condition is
fulfilled. They are introduced by the keywords while, do, and for.
The while loop
The format of while loop is:
while (expression)
{
//statements
}
The while-loop simply repeats statement while expression is true. If, after any
execution of statement, expressions no longer true, the loop ends, and the program
continues right after the loop.
The do-while loop
A very similar loop is the do-while loop, whose syntax is:
Do
{

64
// statements
}while (condition);
Its functionality is exactly the same as the while loop, except that condition in the
do-while loop is evaluated after the execution of statement instead of before, granting at
least one execution of statement even if condition is never fulfilled.
The for loop
The format of for loop is:
for (initialization; condition; increase)
{
// statement;
}
It works in the following way:
1. Initialization is executed. Generally it is an initial value setting for a counter variable.
This is executed only once.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
3. Statement is executed. As usual, it can be either a single statement or a block
enclosed in braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back
to step 2.
4.5 Functions
 A function is a group of statements that together perform a task.
 When any program is very long or same code is repeating many times then we
try to cut the program in different parts (or blocks) so that whole program
became more understandable, easier to debug (error checking) and size of code
will be lesser.
 A function can be called repeatedly based on the application and thus the size of
the program can be reduced.
Defining a Function:
The general form of a C++ function definition is as follows:
return_typefunction_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the
value the function returns.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument.
Function Body: The function body contains a collection of statements that define what
the function does.
Passing Arguments
The main objective of passing argument to function is message passing. The
message passing is also known as communication between two functions i.e., between

65
caller and callee functions. There are three methods by which we can pass values to
the function.
These methods are.
a. Call by value (pass by value),
b. Call by reference (pass by reference).
4.5.1 Call by value (pass by value)
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means
that code within a function cannot alter the arguments used to call the function.
Consider the function swap() definition as follows.
Program to demonstrate call by value
#include <iostream.h> int b = 200;
// function declaration cout<< "\n Before swap, value of a :"
void swap(int x, int y) << a;
{ cout<<\n "Before swap, value of b :"
int temp; << b;
temp = x; /* save the value of x */ swap(a, b);
x = y; /* put y into x */ cout<< "\n After swap, value of a :" <<
y = temp; /* put x into y */ a;
return; cout<< "\n After swap, value of b :" <<
} b;
int main () return 0;
{ }
int a = 100;// local variable
declaration:
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
4.5.2 Call by reference (pass by reference)
The call by reference method of passing arguments to a function copies the
reference of an argument into the formal parameter. Inside the function, the reference is
used to access the actual argument used in the call. This means that changes made to
the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions
just like any other value. So accordingly you need to declare the function parameters as
reference types as in the following function swap (), which exchanges the values of the
two integer variables pointed to by its arguments.
Program to demonstrate call by reference
#include <iostream.h>
void swap(int&x, int&y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
66
y = temp; /* put x into y */
return;
}

int main ()
{
int a = 100;// local variable declaration:
int b = 200;
cout<< "\n Before swap, value of a :" << a;
cout<< \n "Before swap, value of b :" << b;
swap(a, b);
cout<< "\n After swap, value of a :" << a;
cout<< "\n After swap, value of b :" << b;
return 0;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
4.5.3 Inline Functions
Inline functions are a lot like a placeholder. Once you define an inline function,
using the 'inline' keyword, whenever you call that function the compiler will replace
the function call with the actual code from the function.
One of the prime factors behind using function is that code duplication in
program is avoided and memory space is saved. When a function is defined and
invoked, one set of instruction is created in the memory of the system. At each call, the
control passes to the subroutine at a specified address in the memory.
General format:
inline return_type function_name(argument List)
{
//Statements
}
Program for inline function to return max of two numbers:
#include <iostream.h>
inlineint Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main( )
{
cout<< "Max (20,10): " << Max(20,10) <<endl;
cout<< "Max (0,200): " << Max(0,200) <<endl;
cout<< "Max (100,1010): " << Max(100,1010) <<endl;
return 0;
}

67
Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
4.5.4 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> cout<<”add one integer and one float
#include<conio.h> no:”;
classfunctover cout<<”a+b”<<a+b;
{ }
public: void add(float a,int b)
void add(inta,int b) {
{ cout<<”add two float no:”;
cout<<”add two integer no:”; cout<<”a+b”<<a+b;
cout<<”a+b:”<<a+b; }};
} void main()
void add(inta,intb,int c) {
{ functover fn1;
cout<<”add three integer no:”; fn1.add(20,30);
cout<<”a+b+c”<<a+b+c; fn2.add(20,30,40);
} fn1.add(20,20.4);
void add(inta,float b) 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 object‟s 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 class‟s private members.
o The function declaration must be prefixed by the keyword friend whereas the
function definition must not.
68
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.
Some of the special characteristics are:
 The scope of the friend function is not limited to the class in which it has been
declared as a friend.
 A friend function cannot be called using the object of that class; it is not in the scope
of the class.
 It can be called like a normal function without the use of any object.
 It cannot access the class members directly.
 Using object and the dot operator, it can access both the private and public data
members.
 It can be either declared in the private part or the public part of a class without
affecting its meaning.
General Format:
friend return type function_ name(arguments list)
{
//statement
}
Example program:
#include <iostream.h> float mean (sample S)
class sample {
{ return float (S.a + S.b)/2.0;
inta,b; }
public: void main()
voidsetdata() {
{ sample a;
a=10; a.setdata();
b=20; cout<<mean(a);
} }
friend float mean(sample S);
};

4.6 Classes
Collection of object is called class. And entire set of data and code of an object
is class. The class is user defined data types user defined data type means to create
the object in class name the class name is user defined data type. Once class is
defined, it can be used to create any number of objects.
 Encapsulation of data members and functions that manipulate the data.
 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.
 Class is a collection of objects with similar data type.
 For example mango, apple and orange are members of the class fruit.

69
 A class is an expanded concept of a data structure ie., it can hold both data and
functions.
General Format of Class
classclass_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Outside member function definition:
return_type class_name::fuction_name(arg list)
{
//Statements
}
Example program:
class student void main()
{ {
private: student s1;
intregno; s1.getdata();
char name[15]; s1.putdata();
public: }
void getdata()
{
cin >>regno;
cin>>name;
}
voidputdata()
{
cout<<regno<<name;
}
};
Access Specifiers
An access specifier is one of the following three keywords: private, public or
protected. It gives the access rights to the data members of the class.
 Private members can be accessible only from within other members of the
same class or from their friends.
 Protected members can be accessible from members of their same class and
from their friends, but also from members of their derived classes.
 Public members are accessible from anywhere where the object is visible.
Default access specifier is the private(even if we don‟t declare it in the class)
// classes example
#include <iostream.h> void getdata();
class add voidputdata();
{ };
private: void add::getdata()
int a,b,c; {
public: cout<<”Enter A and B\n”;
70
cin>>a>>b; void main()
} {
void add::putdata() add a1;
{ a1.getdata();
c=a+b; a1.putdata();
} }

4.7 Objects
In c++, the class variables are known as objects. i.e Object is an instance of a
class. Once a class has been declared, we can create variables of that type using the
class name.
For Example:
sample x; // creates a variable x of type sample.
Here, x is called an object of type sample.We may also declare and create more
than one object in one statement
samplex,y,z; // x,y,z are objects of type sample.
Objects can also be created when a class is defined by placing their names
immediately after the closing braces
class sample
{
int regno,mark1,mark2; // variable declaration
float res; // private by default
public:
voidgetdata(inta,intb,intc,float d); // function declaration
voidshowdata();
}x,y,z: // x,y,z are objects of type sample.
Array of objects can be created in the following manner.
sample x[5]; // x is the object for the class sample with 5 instances.
Example:
The following program illustrates the use of creating array of objects.
#include<iostream.h>
#include<string.h>
class student
{
private:
introllno;
string name;
string address;
public:
voidsetdetails (int roll, string studentname, string studadd)
{
rollno=roll;
name=studentname;
address=studadd;
71
}
voidprintdetails()
{
cout<<rollno;
cout<<name;
cout<<address;
}
};
void main()
{
studentarrayofstudent[2];
arrayofstudent[0].setdetails(1,”anand”,”tindivanam”);
arrayofstudent[1].setdetails(2,”viswa”,”chennai”);
}

4.8 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.
4.8.1 Default Constructor
Constructor with default arguments:
Like default arguments to functions, the constructors can also have the default
arguments.
For example
#include<iostream.h>
72
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> {
class test a=x;
{ b=y;
private: c=z;
inta,b,c; }
public: voiddisp()
{
test() cout<<a<<b<<c;
{ }
a=5; };
b=10;
c=15; void main()
} {
test(int x, int y, int z) test t1,t2;

73
test t3(4,8,12); }
t1.disp();
t2.disp();
t3.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>
class sample a=x.a;
{ b=x.b;
private: c=x.c;
inta,b,c; }
public: void display()
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
4.8.4 Dynamic Constructor
Allocation of memory to objects at the time of their construction is known as
dynamic construction of objects.
The memory is allocated with the help of the newoperator.

74
Example:
#include<iostream.h>
#include<string.h>
classstr
{
private:
char *name; //input string;
int length; //length of the string;
public:
str() //constructor 1
{
length=0;
name=new char(length+1);
}
str(char *s) //constructor 2
{
length=strlen(s);
name=new char(length+1); // one additional space for null character
}
void display()
{
cout<<name;
}
void join(str&s1,str &s2)
{
length =s1.length+s2.length;
name=new char(length+1);
strcpy(name,s1.name);
strcat(name,s2.name);
}
};
void main()
{
str n1(“C++”),n2(“Programming”),n3(“Language”),n4,n5;
n1.display();
n2.display();
n3.display();
n4.join(n1,n2);
n5.join(n4,n3);
n4.display();
n5.display();
}
Output
C++
Programming
Language
C++ Programming
C++ Programming Language

75
4.9 Destructors
 A destructor is a function that automatically executes when an object is
destroyed.
 It is used to destroy the objects that have been created by a constructor.
 It is used to release space on the heap.
 The compiler calls the destructor automatically whenever there is an exit
operation from a function, block or program.
Characteristics
 The destructor is a member function whose name is the same as the class name
but is preceded by a tilde (~) symbol.
 No argument should be passed.
 Return type should not be given.
 It cannot be declared static, const or volatile.
 It should have public access in the class definition.
 It may also be declared either inside the class or outside the class using scope
resolution operator.
Syntax:
classclass_name
{
private:
//data
public:
class_name(); // constructor declaration
~class_name();//destructor declaration
};
class_name::class_name() // constructor definition
{
//statements;
}
class_name::~classname() // destructor definition
{
statements;
}
For example:
#include<iostream.h>
int c=0;
class sample
{
public:
sample()
{
c++;
cout<<”No.of object created”<<c;
}
~sample();//destructor declaration
};
sample:~sample()//destructor definition
{
76
cout<<”No.of object destroyed”<<c;
c--;
}
void main()
{
cout<<”Enter main”;
sample s1,s2,s3,s4;
{
cout<<”Enter Block1”<<endl;
sample s5;
}
{
cout<<”Enter Block2”<<endl;
}
}
Output
Enter main
No.of object created 1
No.of object created 2
No.of object created 3
No.of object created 4
Enter Block1
No.of object created 5
No.of object destroyed 5
Enter Block2
No.of object destroyed 4
No.of object destroyed 3
No.of object destroyed 2
No.of object destroyed 1
4.10 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.
The general form of an operator function is defined outside the class.
return_typeclassname::operator operator_to_be_overloaded (list of parameters)
{
function body; //Task defined
77
}
returntype is the type of value returned by the specified operation.
The process of overloading involves the following steps
 First create a class that defines the data type that is to be used in the
overloading operation.
 Declare the operator function in the public part of the class. It may be either a
member function or a friend function.
 Define the operator function to implement the required operations.
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.
4.10.1 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>
#include<conio.h>
78
classcomplex
{
private:
intreal,img;
public:
complex()
{
real=0;
img=0;
}
complex(intx,int y)
{
real=x;
img=y;
}
void display()
{
cout<<real<<”I”<<img<<”\n”;
}
complex operator+(complex &c1)
{
complex temp;
temp.real=real+c1.real;
temp.img=img+c1.img;
return temp;
}
};
void main()
{
complex c1(10,20),c2(15,25),c3;
c3=c1+c2;
c1.display();
c2.display();
c3.display();
getch();
}

Output:
10 20
15 25
25 45
4.10.2 Overloading of Unary operators (Overloading increment and decrement
operators)
The operators that operate on only one operand are called unary operators. E.g
++,-- Unary operators overloaded by member functions take no formal arguments
whereas when they are overloaded by friend functions they take a single argument.
For example:
/* The program to illustrate the use of unary operator overloading */
#include <iostream.h>
class sample
79
{
private:
int v;
public:
sample()
{
v=0;
}
void operator ++();
void operator –();
void operator++(int dummy);
void operator--();
voiddisp()
{
cout<<v<<endl;
}
};
void sample::operator ++(int dummy)
{
v++;
}
void sample::operator ++()
{
++v;
}
void sample::operator -()
{
v=-v;
}
void sample::operator --()
{
v--;
}};
void main()
{
sample s1;
s1.disp()
s1++;
s1.disp();
++s1;
s1.disp();
s1--;
s1.disp();
--s1;
s1.disp();
s1.disp();
++s1;
-si;
s1.disp();
}

80
Output
0
1
2
1
0
-1
4.11 Type Conversions
 The user defined data types are designed by us to suit our requirements, the
compiler does not support automatic type conversions for such data types.
 The automatic type conversion has to be designed by the user. ,It is a
process of converting one data type into another data type.The three types of
data conversion are
i. Conversion from basic type to class type.
ii. Conversion from class type to basic type.
iii. Conversion from one class type to another class type.
A casting operator is a function that satisfies the following conditions
 It must be a class member
 It must not specify a return type.
 It must not have any arguments.
The general form of overloaded casting operator is
operatortype_name()
{
…………//function statements
}
It is also known as conversion function.
4.11.1 Basic to class type
The conversion from basic type to class type is easy to accomplish. It may be
recalled that the use of constructors was illustrated in a number of examples to initialize
objects. For example, a constructor was used to build a vector object from an int type
array. Similarly, we used another constructor to build a string type object from a char*
type conversion from the argument‟s type to the constructor‟s class type.
Example:
#include<iostream.h> voiddisp()
classeee {
{ cout<<”a:”<<a;
int a; }
public: };
eee() void main()
{ {
a=0; eee e1(10);
} e1.disp();
eee(int x) }
{
a=x;
}

81
Output:
A:10
4.11.2 Class type to basic type
Constructors are used for type conversion from a basic to class type . But class
type conversion is not supported. C++ allows us to define an overload casting operator
that could be used to convert a class type data to a basic type. This function converts a
class type data to type name.
For examples, the operator double( ) converts a class object to type double, the
operator int() converts a class type object to type int and so on .
Program
#include<iostream.h>
class sample
{
int x;
public:
sample(int a)
{
x=a;
}
operator(int c)
{
return x;
}
};
void main()
{
sample s1(10);
int a=s1;
cout<<a;
}
4.11.3 One class to another class type:
Objx // (destination class) = obj y; //(source class)
Consider a single argument construction function which serves as an institution
for converting the arguments type to the class of which it is a member. This implies that
the argument belongs to the source class and is passed to the destination class for
conversion. This makes necessary that the conversion constructor be placed in the
destination class.
Conversion constructors
We can convert from one type of object into another type of object using either
constructors or conversion operator functions. The following program explains how to
convert from one object to another object of different classes using constructor function.
Example Program
#include<iostream.h>
#include<conio.h>
class one
{
int x;
public:
one(int a)
82
{
x=a;
}
int get()
{
return x;
}
};
class two
{
int y;
public:
two(one o1)
{
y=o1.get();
}
void print()
{
cout<<y;
}
};
void main()
{
one o1(10);
two t1;
t1=o1;
t1.print();
}
Conversion operator function
The following program explains how to convert from one object to another object
of different classes using conversion operator function.
Example:
#include<iostream.h> two(int b)
#include<conio.h> {
class one y=b;
{ }
int x; operator one()
public: {
one(int a) return one(y);
{ }
x=a; };
} void main()
void print() {
{ one o1;
cout<<x; two t1(10);
} o1=t1;
}; o1.print();
class two }
{
int y;
public:
83
Chapter 5

5.1 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.
 Visibility mode specifies whether the features of the base class are privately
derived or publically derived.
There are 3 visibility modes.
 Private
 Public
 Protected
Definition
 The process of creating new classes from existing classes.
 A class that inherited is referred to as a base class. The class that does the
inheriting is called derived class
Features or Advantages of Inheritance
 Reusability:
Inheritance helps the code to be reused in many situations. The base class is
defined and once it is compiled, it need not be reworked. Using the concept of
inheritance, the programmer can create as many derived classes from the base
class as needed while adding specific features to each derived class as
needed.
 Saves Time and Effort:
The above concept of reusability achieved by inheritance saves the
programmer time and effort, because the main code written can be reused in
various situations as needed.
 Increases Program Structure which results in greater reliability.
 Polymorphism
5.1.1 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
}

84
5.1.1.1 Single inheritance(only one base class) :
If a single class is derived from a single base class is called single inheritance.

Eg:

Fig 5.1 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> class student:public person
#include<conio.h> {
class person private:
{ int roll;
private: char *dept;
char *name; public:
cahr sex; void gets();
int age; {
public: person::get();
void get() cout<<”roll no:”;
{ cin>>roll;
coout<<”name:”; cout<<”dept:”;
cin>>name; cin>>branch;
cout<<”sex”; }
cin>>sex; void displs()
cout<<”age:”; {
cin>>age; person::despl();
} cout<<”roll no:”<<roll;
void displ() cout<<”dept:”<<dept;
{ }};
cout<<”name;”<<name; void main()
cout<<”sex:”<<sex; {
cout<<”age:”<<age; student s1;
} s1.gets();
}; s1.displs();
}
Output
Name : Mohan
Sex : M
Age : 26
Roll no : 1202
Dept : cse

85
5.1.1.2 Multiple Inheritance(several base class):
If a class is derived from more than one base class, it is called multiple
inheritance.
Eg:

Fig 5.2 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
{
………....
…………
};
Example
#include<iostream.h>
#include<conio.h>
class internal
{
private:
int imark1,imark2;
public:
void get()
{
coout<<”imark1:”;
cin>>imark1;
cout<<”imark2:”;
cin>>imark2;
}
void displ()
{
cout<<”imark1:”<<imark1;
cout<<”imark2:”<<imark2;
}
};
class external
{
private:
86
int emark1,emark2;
public:
void get()
{
coout<<”emark1:”;
cin>>emark1;
cout<<”emark2:”;
cin>>emark2;
}
void displ()
{
cout<<”emark1:”<<emark1;
cout<<”emark2:”<<emark2;
}
};
class total:public internal,public external
{
private:
int tmark1,tmark2;
public:
void gett()
{
internal::get();
external::get();
}
void totalm()
{
tmark1=internal::imark1+external::emark1;
tmark2=internal::imark2+external::emark2;
}
void displt()
{
internal::displ();
external::displ();
cout<<”tmark1:”<<tmark1;
cout<<”tmark2:”<<tmark2;
}
};
void main()
{
total t;
t.gett();
t.totalt();
t.displt();
}

5.1.1.3 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.

87
Eg :

Fig 5.3 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
{
…………..
………….
};
5.1.1.4 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:
88
Fig 5.4 Multilevel Inheritance
General format
class A
{
………….
………….
};
class B:public A
{
…………..
………….
};
class C:public B
{
………....
…………
};
5.1.1.5 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.

Fig 5.5 Hybrid Inheritance


The class result will have both the multilevel and multiple inheritances.

89
5.2 Extending Classes
5.2.1 Virtual Base Classes:

Fig 5.6 Multipath inheritance


 The child has two direct base classes „parent1‟ and „parent2‟ which themselves
have a common base class grandparent.
 The child inherits the traits of „grandparent‟ via two separate paths.
 It can also inherit directly as shown by the broken line. The „grandparent‟ is
sometimes referred to as indirect base class.
 All the public and protected members of the „grandparent‟ are inherited into
„child‟ twice, first via „parent1‟ and again via „parent2‟.
 This means „child‟ would have duplicate sets of the members inherited from
grandparent.
 This introduces ambiguity and should be avoided.
 The duplication of inherited members due to these multiple paths can be
avoided by making the common base class(ancestor class) as virtual base
class while declaring the direct or intermediate base classes as shown below.
class a
{
…………
…………
};
class b1 : virtual public a //parent1
{
……….
……….
};
class b2 : virtual public a //parent 2
{
……….
………
};
class c : public b1, public b2 //child
{
……… //only one copy of „a‟ will be inherited
………
};

90
Example program:
#include<iostream.h> float score;
class student public:
{ void get_score(float s)
protected: {
int roll_number; score=s;
public: }
void get_number (int a) void put_score(void)
{ {
roll_number=a; cout<<”sports wt:”<<score<<”\n\n”;
} }
void put_number (void) };
{ class result : public test,public sports
cout<<”roll no:”<<roll_number<<”\n”; {
} float total;
}; public:
class test : virtual public student void display(void);
{ };
protected: void result : : display(void)
float part1,part2; {
public: total = part1+part2+score;
void get_marks(float x,float y) put_number();
{ put_marks();
part1=x; part2=y; put_score();
} cout<<”total score:”<<total<<”\n”;
void put_marks(void) }
{ int main()
cout<<”marks obtained:”<<”\n”; {
<<”part1=”<<part1<<”\n” result student_1;
<<”part2=”<<part2<<”\n”; student_1.get_numbr(1234);
} student_1.get_marks(27.5,33.0);
}; student_1.get_score(6.0);
class sports : virtual public student student_1.display();
{ return 0;
protected: }

Output:
Roll No: 1234
Marksobtained:
Part1=27.5
Part2=33
Sport wt=6
Total score: 66.5
5.3 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.There are two types of polymorphism. They are
1. Compile time polymorphism
2. Run time polymorphism
91
Fig 5.7 Polymorphism
The compile time polymorphism is achieved by function overloading and
operator overloading.
The run time polymorphism is achieved by virtual functions. Resolving function
call at run time is known as run time or late or dynamic binding. Run time polymorphism
allows selecting the suitable function at run time.
Pointer object
Pointer object is a variable containing an address of an object. It is similar to
pointer variable. We have to use & operator to get the address of an object. The
address of an object is assigned to pointer object. Consider the following code.
Class demo
{
------
};
Void main()
{
demo *d1;
Demo d2;
D1=&d2;
}
 The pointer object is used to achieve a run time polymorphism.
 It is a polymorphic object which means, using this same object it is possible to
access member functions of different classes.
This pointer
The name ‘this’ is a keyword. The pointer „this‟ allows you to access the current
object only. You can use the pointer „this‟ within a method to access an object member.
It is also used to return the address of the current object.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
private:
int x;
public:
A(int a)
{
92
this->x=a;
}
A disp()
{
return *this;
}
};
void main()
{
A(10);
A a1,a2;
a2=a1.disp();
}
5.4 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()
{
93
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

Fig 5.8 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.
Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract
classes are used to provide an Interface for its sub classes. Classes inheriting an
Abstract Class must provide definition to the pure virtual function, otherwise they will
also become abstract class.
Characteristics of Abstract Class
1. Abstract class cannot be instantiated, but pointers and refrences of Abstract
class type can be created.
2. Abstract class can have normal functions and variables along with a pure virtual
function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can
use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or
else they will become Abstract too.
5.4.1 Pure Virtual Functions
A do-nothing function can be defined as pure virtual function.
That is, a function without body (statements).
94
Eg:
class SomeClass
{
public:
virtual void pure_virtual() = 0; // a pure virtual function
// note that there is no function body
};

5.5 Streams and File I/O


5.5.1 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

Fig 5.19 I/O Stream Class


5.5.2 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

95
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);
File pointer and their manipulators

96
Two types
1. Input or get pointer 2. Output or put pointer
Actions
Read only mode – the pointer is set at the beginning of the file
write only mode - the pointer is set at the beginning of the file ,the old contents will be
erased.
Append mode - the pointer is set at the end of the file
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);
Input and output file operations
Put() and get() – an handle single character at a time.
Write() and read() – to read and write blocks of binary data.
Eg:Infile.read((char*) &v, sizeof(v));
Error handling in file operations
1. eof()returns non-zero-value if end-of-file is encountered otherwise zero.
2. fail()returns true when input or output operation fails
3. bad()returns true for invalid operation or for any unrecoverable errors
4. good()returns true if no error occurs
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>
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz";
fout<<str;
fout.close();
return 0;
}
Program to read from text file and display it
#include<fstream.h>
#include<conio.h>
int main()
{

97
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}

5.6 Templates
 Templates are a feature of the C++ programming language that allows functions
and classes to operate with generic types.
 This allows a function or class to work on many different data types without
being rewritten for each one.
 The template allows the reusability feature (without inheritance) stronger and
provides higher flexibility to the language.
 It allows the construction of family of functions and classes to perform the same
operation on different data types in a single framework. There are two types of
templates.
They are
 Function templates  Class templates
5.6.1 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.
Use of Typename
The keyword typename indicates that the expression following the keyword is
the name of a type. It can also be used within the body of the template function or class
template. If we write a typename identifier; then that identifier is treated as a generic
type in that function.
Note: The keyword typename may not work in some old compilers. Instead the keyword
class can be used in its space.
98
The syntax of function template is similar to a normal function except that it uses
variables whose data types are not known until a call to it is made. The syntax for
calling a function template is similar to a normal function and the parameters can be of
any type.
Function Template with Multiple Arguments
 It is possible to have templates with more than one argument. Other arguments
can be generic or normal.
 In the following program we defined a Max function to find maximum between
two values passed to it. The Max function is declared as a generic function i.e.,
template function to work with multiple data types.
/* 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
5.6.2 Class templates
We also have the possibility to write class templates, so that a class can have
members that use template parameters as types.
Syntax
template<typename T,……>
class class_name
{
//class body
}

99
For example:
#include<iostream.h>
template<class T>
class temp
{
T a,b;
public:
temp(T x,T y)
{
A=x;
B=y;
}
void put()
{
cout<<a;
cout<<b;
}
};
void main()
{
temp e1(10,20);
e1.put();
temp e2(10.2,12.2);
e2.put();
}
Output
10 20
10.2 12.2
The class that we have just defined serves to store two elements of any valid
type.

5.7 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
100
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
}

 throw (exception)
 throw exception
 throw
Program:
include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;
try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}
101
catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}
getch();
}
5.7.1 Multiple catch statements
We have one catch block because we threw only one exception. If we have more
than one exception in our code, we will have to write multiple catch blocks in such
scenarios.
Example Program:
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}

catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;
}

catch(char x)
{
cout<<"Catch a character and that character is:"<<x;
}
}

void main()
{
clrscr();
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}

102

You might also like