Ec t33 Dsop Full
Ec t33 Dsop Full
Ec t33 Dsop Full
OBJECT ORIENTED
PROGRAMMING
ECT33
B.Tech./ ECE /III SEMESTER
Prof. ELUMALAI .P
AP/CSE - ACET
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
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
iii
Chapter 4 Object Oriented Programming 56
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
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.
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
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.
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:
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
10
When both i and j have stopped
A[i] ≥ pivot
A[j] ≤ pivot ⇒ A[i] and A[j] should now be swapped
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 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.
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
A1 800 A2 712 A3 0
18
Insertion
Insertion require obtaining a new cell from the system by using a malloc call and
then execute two pointer change
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.
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.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 .
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
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:
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.
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.
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
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
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.
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.
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.
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
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.
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
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
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
3)Pop the stack for the next vertex to be visited, v7 is popped and its adjacent pushed
on to the stack
4)Pop the stack for the next vertex to be visited, here v6 is popped and its adjacent
pushed on to the stack
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
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
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
50
Step 2: Change the infinity Value
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
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
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
55
Chapter 4
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
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
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.
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
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++
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.
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.
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
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:
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:
87
Eg :
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.
89
5.2 Extending Classes
5.2.1 Virtual Base Classes:
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
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.
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