You are on page 1of 176

Downloaded From : www.EasyEngineering.

net

ww
w.E
asy
En
gin
eer
ing
.ne
t

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials without Legal Permission of the Publishers.

**Disclimers : EasyEngineering not the original publisher of this Book/Material


on net. This e-book/Material has been collected from other sources of net.
Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net

ANNA UNIVERSITY
SYLLABUS COPY (REGULATION 2013)
EC6301 OBJECTPROGRAMMING AND DATA STRUCTURES L T P C
3 0 0 3

UNIT I DATA ABSTRACTION & OVERLOADING 9


Overview of C++ – Structures – Class Scope and Accessing Class Members – Reference
Variables – Initialization – Constructors – Destructors – Member Functions and Classes – Friend
Function – Dynamic Memory Allocation – Static Class Members – Container Classes and
Integrators – Proxy Classes – Overloading: Function overloading and Operator Overloading.

UNIT II INHERITANCE & POLYMORPHISM 9


Base Classes and Derived Classes – Protected Members – Casting Class pointers and Member
Functions – Overriding – Public, Protected and Private Inheritance – Constructors and Destructors

ww
in derived Classes – Implicit Derived – Class Object To Base – Class Object Conversion –
Composition Vs. Inheritance – Virtual functions – This Pointer – Abstract Base Classes and
Concrete Classes – Virtual Destructors – Dynamic Binding.

UNIT III w.E LINEAR DATA STRUCTURES


Abstract Data Types (ADTs) – List ADT – array-based implementation – Linked list
10

asy
implementation –– singly linked lists –Polynomial Manipulation – Stack ADT – Queue ADT –
Evaluating arithmetic expressions.

UNIT IV En
NON-LINEAR DATA STRUCTURES 9

gi
Trees – Binary Trees – Binary tree representation and traversals – Application of trees: Set
representation and Union-Find operations – Graph and its representations – Graph Traversals –

nee
Representation of Graphs – Breadth-first search – Depth-first search – Connected components.

UNIT V SORTING and SEARCHING


rin 8
Sorting algorithms: Insertion sort – Quick sort – Merge sort – Searching: Linear search –Binary
Search
g.n
TOTAL: 45 PERIODS
TEXT BOOK(S):
e
1. Deitel and Deitel, “C++, How To Program”, Fifth Edition, Pearson Education, 2005.
2. Mark Allen Weiss,“Data Structures and Algorithm Analysis in C++”, Third Edition, Addison-
Wesley, 2007.
t
REFERENCES:
1. Bhushan Trivedi, “Programming with ANSI C++, A Step-By-Step approach”, Oxford University
Press, 2010.
2. Goodrich, Michael T., Roberto Tamassia, David Mount, “Data Structures and Algorithms in
C++”, 7th Edition, Wiley. 2004.
3. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, “Introduction to
Algorithms”, Second Edition, Mc Graw Hill, 2002.
4. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson Education, 2007.
5. Ellis Horowitz, Sartaj Sahni and Dinesh Mehta, “Fundamentals of Data Structures in C++”,
Galgotia Publications, 2007.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

TABLE OF CONTENTS
Sl.No Topic Page No.
a Aim and Objective of the Subject 5
b Detailed Lesson Plan 6
UNIT I DATA ABSTRACTION & OVERLOADING
I PART A 9
II PART B 14
1 Parameterized Constructor and Copy Constructor 14
2a Function overloading 17
2b Binary overloading 19
3 Friend Function 24
4 Operator overloading 25
5 Constructor and Destructor 28

wwIII
6
7
PART C
Object oriented Programming Concepts
Call By Value Call By Reference
30
30
34

w.E UNIT II INHERITANCE & POLYMORPHISM


I
II asy
PART A
PART B
36
42
1a
1b En
Base and Derived Class
Access Modifiers
42
44
2
3
4
gi
Class Object to Base and Base to Class Object
Virtual Functions
This Pointer nee
47
49
51
5 Inheritance 54
III PART C
rin
63
6
7
Example Program
Implementation of Constructor
63
67 g.n
I
II
1a
UNIT III LINEAR DATA STRUCTURES
PART A
PART B
Singly Linked List
68
71
71
e t
1b List ADT 74
2 Applications of Stack 76
3 Stack 82
4 Queue 87
5 Addition of Two Polynomials 93
III PART C 99
6 Sum of odd Numbers Using Singly Linked List 99
7 Polynomial Manipulation 102
UNIT IV NON- LINEAR DATA STRUCTURES
I PART A 107
II PART B 111
1 Binary Tree Traversal 111
3

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

2 Breadth First Traversal And Depth First Traversal 115


3 Implementation of Tree Traversals 122
4a Expression Tree Construction 125
4b Set Representation 129
5 Union- Find Operations 131
III PART C 135
6 Minimum Spanning Tree 135
7 Connected Components 138
UNIT V SORTING and SEARCHING
I PART A 141
II PART B 145
1 Quick Sort 145
2 Insertion Sort 150

ww3
4
5
Linear Search
Binary Search
Merge Sort
152
154
157

w.E
III
6
PART C
Example programs
160
160
7
asy
Program in sorting.
Industrial/Practical Connectivity of the subject
161
164

En
University Question Bank 166

gi nee
rin
g.n
e t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

AIM AND OBJECTIVE OF THE SUBJECT


• To introduce the basics and advanced concepts of C++ programming language
• Be familiar with writing programs using techniques in C++ programming.
• To introduce the concepts of ADTs
• To Master the implementation of linked data structures such as linked lists,
stacks and queues.
• Be familiar with several algorithms including quicksort, mergesort and radix
sort.
• To introduce the concepts of Trees and Graphs

ww
• To Master analyzing problems and writing program solutions to problems using
the above techniques

w.E
asy
En
gi nee
rin
g.n
e t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DETAILED LESSON PLAN


TEXT BOOKS:
1. Deitel and Deitel, “C++, How To Program”, Fifth Edition, Pearson Education, 2005.
2. Mark Allen Weiss,“Data Structures and Algorithm Analysis in C++”, Third Edition,
Addison-Wesley, 2007.

REFERENCES:
1. Bhushan Trivedi, “Programming with ANSI C++, A Step-By-Step approach”, Oxford University
Press, 2010.
2. Goodrich, Michael T., Roberto Tamassia, David Mount, “Data Structures and Algorithms in
C++”, 7th Edition, Wiley. 2004.
3. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, “Introduction to

ww Algorithms”, Second Edition, Mc Graw Hill, 2002.


4. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson Education, 2007.
5. Ellis Horowitz, Sartaj Sahni and Dinesh Mehta, “Fundamentals of Data Structures in C++”,

w.E
Galgotia Publications, 2007.

asy
Hours Cumu
Sl. Books
Unit Topic / Portions to be Covered Required lative
No Referred
/ Planned Hrs
UNIT I
En DATA ABSTRACTION & OVERLOADING

gi
Overview of C++- Concepts of OOPS,
1 1 1 1 TB1,RB1,RB4
Applications
2 1 Structures , Definition, Usage
nee 1 2 TB1,RB1,RB4

3 1 Class scope and Accessing Class Members


Reference Variables, Declaration,
1
rin 3 TB1,RB1,RB4

4 1
Initialization
Constructors-Default, Parameterized,
1 4
g.n TB1,RB1,RB4

6
1

1
Copy, Destructors
Class, Member functions, Nesting of
member functions, Pointers to objects
1

1
5

6
eTB1,RB1,RB4

t
TB1,RB1,RB4

Friend Function, Dynamic Memory


7 1 1 7 TB1,RB1,RB4
Allocation- new and delete operator
Static Class members, Container Classes
8 1 and Integrators- Objects as members of 1 8 TB1,RB1,RB4
class
Proxy classes, overloading Functions
9 1 Implementation, Interface and class 1 9 TB1,RB1,RB4
member function definition
Operator overloading, Unary and Binary TB1,RB1,RB4,
10 1 1 10
operators RB5

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT II INHERITANCE & POLYMORPHISM


Inheritance – Base classes , Derived Classes, TB1,RB1,RB4,
11 2 1 11
Types RB5
12 2 Protected members, Casting Class pointers 1 12 TB1,RB1,RB4
Overriding- Public, protected and private
13 2 1 13 TB1,RB1,RB4
members usage in inheritance
Constructors and Destructors in derived
14 2 1 14 TB1,RB1,RB4
classes, Implicit derived.
15 2 Class object to base- Class Object conversion 1 15 TB1,RB1,RB4

Composition Vs Inheritance TB1,RB1,RB4,


16 2 1 16
RB5

ww
17 2
Virtual functions, This pointer with an example,
Pure virtual function
1 17 TB1,RB1,RB4

18
19
2
2 w.E
Abstract base classes and concrete classes

Virtual destructors, Dynamic Binding


1
1
18
19
TB1,RB1,RB4

TB1,RB1,RB4

20 3 asy
UNIT III LINEAR DATA STRUCTURES
Abstract Data Types (ADTs) 1 20 TB2

21 3 En
Array implementation of List – Insert, Delete
1 21
TB2

22 3
gi
, Search and Display functions
Linked List implementation– Insert, Delete ,
Search and Display functions nee 1 22
TB2

23
lisLinked Singly linked lists - Insert, Delete , Search
3
and Display functions
1
rin 23
TB2,RB2,RB3

24 3 Polynomial Manipulation 2 25
g.n TB2

25

26
3

3
Stack ADT-array,push,pop operations
Queue ADT-array
implementation
and pointer
1

1
26

27
e TB2,RB2,RB3
TB2,RB2,RB3
t
27 3 Applications of Queue-Radix sort 1 28 TB2

28 3 Evaluating arithmetic expressions 1 29 TB2

UNIT IV NON-LINEAR DATASTRUCTURES


29 4 Trees – Binary Trees 1 30 TB2,RB2,RB3
30 4 Binary tree representation and traversals 2 32 TB2,RB2,RB3
31 Application of trees: Set representation and TB2,RB2,RB3
4 1 33
Union- Find operations
32 4 Graph and its representations 1 34 TB2,RB2,RB3
33 4 Graph Traversals, Representation of Graphs 1 35 TB2,RB2,RB3

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

34 4 Breadth-First search, Depth-First search 2 37 TB2,RB2,RB3


35 4 Connected components 1 38 TB2,RB2,RB3

UNIT V SORTING AND SEARCHING


36 5 Sorting methods – Insertion sort 1 41 TB2
Quick sort – Recursive and Divide and
37 5 1 42 TB2,RB5
Conquer
Quick sort problems- Choice of pivot
38 5 1 43 TB2,RB5
element
39 5 Mergesort – Divide and Conquer technique 1 44 TB2
40 5 Mergesort problems 1 45 TB2

ww
41
42
5
5
Searching- Definition, and its types
Linear search- Sequential method
1
1
46
47
TB2
TB2
43 5
w.E
Binary search - Divide and Conquer 1 48 TB2

asy
En
gi nee
rin
g.n
e t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT I

DATA ABSTRACTION & OVERLOADING

Overview of C++ – Structures – Class Scope and Accessing Class Members –


Reference Variables – Initialization – Constructors – Destructors – Member
Functions and Classes – Friend Function – Dynamic Memory Allocation – Static
Class Members – Container Classes and Integrators – Proxy Classes –
Overloading: Function overloading and Operator Overloading.

PART-A

ww
1. What is a destructor? Nov/Dec 2015

Destructor
w.E
It is used to destroy the objects that have been created by constructor. Destructor name

asy
is same as class name preceded by tilde symbol (~)
Eg:
En
~ integer()
{ gi nee
}

rin
A destructor never takes any arguments nor it does it return any value. The compiler
upon exit from the program will invoke it.
g.n
2. Define friend function. e
Apr/May 2015,Nov/Dec 2015
t
A friend function that is a "friend" of a given class is allowed access to private and
protected data in that class that it would not normally be able to as if the data was public .
Normally, a function that is defined outside of a class cannot access such information.

3. What is reference variable? Apr/May 2015

References are often confused with pointers but three major differences between
references and pointers are:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

• You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
• Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
• A reference must be initialized when it is created. Pointers can be initialized at any
time.
For example, suppose we have the following example:
int i = 17;
We can declare reference variables for i as follows.

ww int& r = i;

function.
w.E
4. Write a C++ code to swap values of two variable using reference variables in
Nov/Dec 2014

asy
#include <iostream.h>
En
// function declaration
void swap(int &x, int &y);
int main (void)
gi nee
{
rin
int a = 100; // local variable declaration:
g.n
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
e t
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}

10

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

5. What are 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.
Eg:
Class A
{

ww int a,b; // a,b are data members


void getdata ( ) ; // member function
};
w.E
asy
6. How can reference variables be initialized?

En
for the original variable.
syntax for defining a variable is
gi
Reference variables provide a kind of link to the original variable and becomes alias

nee
<data type>& ref variable = original variable;
rin
e.g int &a =b;
g.n
7. What is polymorphism? What are its types? e t
Polymorphism is an important concept of OOPs. Polymorphism means one name,
multiple forms. It is the ability of a function or operator to take more than one form at
different instances.
Operator overloading – The process of making an operator to exhibit different behaviors
at different instances.
Function overloading – Using a single function name to perform different types of tasks.
The same function name can be used to handle different number and different types of
arguments.

11

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

8. List out the operators that cannot be overloaded.

• Class member access operator (.)


• Scope resolution operator (::)
• Size operator ( sizeof )
• Conditional operator (?:)

9. Define the two memory management operators.

ww New -used to dynamically allocate memory for built in data type or user define
data types.

w.E
Example:

asy
int *p=new int[15];
delete-to de-allocate the memory allocated
example: delete []p;
En
gi
10. State the properties of static data members.
nee
• They are special data members which is a property of the class. rin
• These members are shared by the objects of the class and are accessed as
g.n
classname:: data member
e t
11. What are container classes?

They are collection classes which are designed to hold collections of objects. They
provide services such as insertion, deletion, searching, sorting, testing an item to determine
whether it is a member of the collection. Arrays, Stacks, Queues, Trees and Linked lists are
examples.

12

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

12. What are iterators?

An iterator is an object that returns the next item of a collection. It is associated with
container classes. Iterators hold state information sensitive to the particular containers on
which they operate.

13. Write a C++ code to display “pen object instantiated” and “pen object
destroyed”when class for pen constructor and destructor are called. Nov/dec 2014

ww class pen
{

w.E
int m,n;
public:
pen( ); . asy
~pen()
En
{

}
gi
cout<<”pen object destroyed”;
nee
};
rin
pen::pen( )
g.n
{
void display()
{
e t
cout<<”pen object instantiated”;
}
}
void main()
{
Pen p;
}

13

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

14. Define proxy class.

Proxy class in C++ is used to implement the Proxy Pattern in which an object is an
interface or a mediator for some other object. A typical use of a proxy class in C++ is
implementing the [ ] operator since the [ ] operator may be used to get data or to set data
within an object

15. What is Dynamic Memory Allocation?

ww Dynamic memory is allocated using operator new. new is followed by a data type
specifier and, if a sequence of more than one element is required, the number of these

w.E
within brackets []. It returns a pointer to the beginning of the new block of memory
allocated.
Its syntax is: asy
En
pointer = new type

gi
pointer = new type [number_of_elements]

nee
PART-B rin
g.n
PARAMETERISED CONSTRUCTOR AND COPY CONSTRUCTOR
e t
1. Narrate on parameterised constructor and copy constructor with an example for
each of them. Nov/Dec 2015

Constructor
It is a special member function whose task is to initialize the objects of its class. It is
special because its name is the name as the class name. It is invoked when an object is
created.
Eg:
class sample
14

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
int m,n;
public:
sample()
{
m=0;
n=0;
}
};

ww
The rules to be followed
• It should be in public section

w.E
• It should have the same name as that of the class name
• It has no return type
• It cannot be virtual asy
• It cannot be inherited
En
Parameterized Constructor
gi nee
A constructor with arguments is called as parameterized constructor. It is invoked
when an object is created with matching arguments.
Eg: rin
class sample
g.n
{
int a,b; e t
public:
sample()
{
a=0;
b=0;
}
sample(int d,int e)
{
a=d;

15

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

b=e;
}
void display()
{
cout<<a<<b;
}
};
void main()
{

ww sample obj(10,5);
obj.display();
}
Output:
w.E
10 5 asy
Copy Constructor
En
Eg:
class sample
gi
It is used to declare and initialize objects from another object.

nee
{
rin
int a,b;
g.n
public:
sample()
{
e t
a=0;
b=0;
}
sample(int d,int e)
{
a=d;
b=e;
}

16

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

sample(sample &obj)
{
a=obj.a;
b=obj.b;
}
void display()
{
cout<<a<<b;

ww };
}

w.E
void main()
{

asy
sample obj(10,5);
sample obj1(obj)
En
}
Output:
obj1.display();
gi nee
10 5
rin
g.n
FUNCTION OVERLOADING
e t
2. (i)What do you mean by function overloading and explain it with an example?
Nov/Dec 2015
Function overloading

It is a compile time polymorphism where more than one function have the same name but
differ either in the number of arguments or the type of arguments.
Eg:
void area(float r)
{

17

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

float a;
a=3.14*r*r;
cout<<"\nArea of the circle is:"<<a;
}
void area(int l,int b)
{
int area;
area=l*b;
cout<<"\nArea of rectangle is:"<<area;

ww
}
void main()
{
w.E
int a,b;
float c; asy
En
cout<<"\nEnter length and breadth:";
cin>>a>>b;
area(a,b); gi
cout<<"\nEnter the radius:" nee
cin>>c;
rin
area(c);
g.n
}
Output:
Enter length and breadth:
e t
10
20
Area of Rectangle is 200
Enter the radius: 10
Area of Circle is 314.0000

18

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

BINARY OVERLOADING

2. (ii) Elaborate on binary overloading with an example. Nov/Dec 2015


Operator Overloading
Giving an operator new meaning is called as operator overloading. The syntax
is
returntype classname::operator op(args)
{
//sts

ww }
where op is the operator to be overloaded.

w.E
Unary Operator Overloading
Unary operator have only one variables associated with it. Eg: !, ++, --, +, -
Eg: asy
class sample
En
{
int x,y,z; gi nee
public:
void getdata(int a,int b,int c) rin
{
g.n
x=a;
y=b; e t
z=c;
}
void display()
{
cout<<"X="<<x<<"Y="<<y<<"Z="<<z;
}
void operator -();
};
void sample::operator()

19

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
x=-x;
y=-y;
z=-z;
}
void main()
{
sample obj;
obj.getdata(10,20,-30);

ww -obj;
obj.display();
//Overloaded Operator is called

}
Output:
w.E
X=-10 Y=-20 asy
Z=30

En
Binary Operator Overloading
It can be done in two ways
gi
• Without using friend function
nee
• Using Friend Function
Without Using Friend Function rin
g.n
#include<iostream.h>
#include<conio.h> e t
class complex
{
float x,y;
public:
complex()
{
}
complex (float real,float img)
{

20

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

x=real;
y=img;
}
void display()
{
cout<<x<<”+i”<<y;
}
complex operator +(complex);
};

ww complex complex::operator+(complex c)

w.E
{
complex temp;

asy
temp.x=x+c.x;

En
temp.y=y+c.y;

} gi
return temp;

nee
void main()
rin
{
g.n
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;
c1.display();
e t
cout<<”\nC2\n”;
c2.display();
c3=c1+c2;
cout<<”\nC3\n”;
c3.display();
getch();
}

21

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Output:
C1
5.0+i6.0
C2
4.4+i3.3
C3
9.4+i9.9

Using Friend Function

ww
#include<iostream.h>
#include<conio.h>

w.E
class complex
{
float x,y; asy
public:
En
complex()
{
}
gi nee
complex(float real,float img)
rin
{
g.n
}
x=real;
y=img; e t
void display()
{
cout<<x<<”+i”<<y;
}
friend complex operator +(complex,complex);
};
complex operator+(complex c1,complex c2)
{

22

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

complex temp;
temp.x=c1.x+c2.x;
temp.y=c1.y+c2.y;
return temp;
}
void main()
{
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;

ww c1.display();
cout<<”\nC2\n”;

w.E
c2.display();
c3=c1+c2;

asy
cout<<”\nC3\n”;
c3.display();
En
}
getch();
gi nee
Output:
rin
C1
g.n
5.0+i6.0
C2
4.4+i3.3
e t
C3
9.4+i9.9

23

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

FRIEND FUNCTION

3. Write a member function and friend function to subtract two complex numbers in
C++. Nov/Dec 2015

#include<iostream.h>
#include<conio.h>
class complex
{

ww float x,y;
public:

w.E
complex()
{
} asy
En
complex(float real,float img)
{
x=real; gi nee
y=img;
} rin
void display()
g.n
{
cout<<x<<”+i”<<y; e t
}
friend complex operator -(complex, complex);
};
complex operator-(complex c1,complex c2)
{
complex temp;
temp.x=c1.x+c2.x;
temp.y=c1.y+c2.y;
return temp;

24

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
void main()
{
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;
c1.display();
cout<<”\nC2\n”;
c2.display();
c3=c1-c2;

ww cout<<”\nC3\n”;
c3.display();

}
w.E
getch();

asy
Output:
En
C1
5.0+i6.0
C2
gi nee
4.4+i3.3
rin
C3
g.n
0.6+i2.7

OPERATOR OVERLOADING
e t
4. Write a member function to perform matrix addition,simple addition and string
concatenation by overloading + operator. Nov/Dec 2015

#include<iostream.h>
#include<math.h>
#include<conio.h>
#include<string.h>

25

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

#define SIZE 3
class Addition
{
public:
char name[10];
int num;
int a[SIZE][SIZE];
Addition()
{

ww Strcpy(name,””);
Num=0;
}
w.E
Addition (char n[10],int val,int x[SIZE][SIZE]);

asy
Addition operator + (Addition obj);
};
En
{
strcpy(name,n);
gi
Addition::Addition (char n[10],int val,int x[SIZE][SIZ])

nee
num=val;
rin
for(int i=0;i<SIZE;i++)
g.n
for(int j=0;j<SIZE;J++)
a[i][j]=x[i][j];
}
e t
Addition Addition::operator +(Addition obj)
{
Addition temp;
strcat(name,obj.name);strcpy(temp.name,name);
temp.num=num+obj.num;
for(int i=0;i<SIZE;i++)
for(int j=0;j<SIZE;j++)
temp.a[i][j]=a[i][j]+obj.a[i][j];

26

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return temp;
}
void main()
{
int mat1[SIZE][SIZE]={{1,2,3},{4,5,6},{7,8,9}};
int mat1[SIZE][SIZE]={{1,1,1},{2,2,2},{3,3,3}};
Addition obj1(“Hello”,10,mat1);
Addition obj2(“Friend”,20,mat2);
Addition obj3;

ww obj3=obj1+obj2;
cout<<”\n concatenated string is”<<obj3.name;

w.E
cout<<”addition of two numbers is”<<obj3.num;
cout<<”addition of two numbers is”;

asy
for(int =0;i<SIZE;i++)

En
for(int j=0;j<SIZE;j++)

}
cout<<””<<obj3.a[i][j];
cout<<”\n”; gi nee
rin
OUTPUT
g.n
concatenated string is: HelloFriend
addition of two numbers is 30
addition of two matrices is 2 3 4 6 7 8 10 11 12
e t

27

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

CONSTRUCTOR AND DESTRUCTOR

5. What is the purpose constructor and destructor? Explain with suitable example the
different types of constructors in C++. Apr/May 2015

It is a special member function whose task is to initialize the objects of its class. It is
special because its name is the name as the class name. It is invoked when an object is
created.
Eg:

ww
class sample
{

w.E
int m,n;
public:
sample() asy
{
En
m=0;
n=0; gi nee
}
}; rin
The rules to be followed
g.n
• It should be in public section
• It should have the same name as that of the class name
e t
• It has no return type
• It cannot be virtual
• It cannot be inherited
Default Constructor
A constructor with no arguments is called as default constructor. It is mainly used to
initialize the variables to a default value. It is called when an object is created with no
arguments.
Eg:
class sample
28

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
int a,b;
public:
sample()
{
a=5;
b=10;
}
void display()

ww {
cout<<a<<b;

};
w.E }

void main() asy


{
En
}
sample obj;
obj.display(); gi nee
Output:
rin
5 10
g.n
Destructor
e t
A destructor is used to destroy the objects that have been created by a constructor. It is also
a member function whose name is the same as the class name but is preceded by a tilde(~)
operator.
Eg: ~sample()
It is invoked when an object is destroyed. It cannot be overloaded. It has no return
type and no arguments
Eg:
class sample

29

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
int id;
public:
sample()
{
id=5;
}
~sample()
{

ww }
cout<<id;

};
w.E
void main()
{ asy
sample obj;
En
}

Output:
gi nee
5
rin
g.n
PART – C
e t
OBJECT ORIENTED PROGRAMMING CONCEPTS
6. Describe the major components of object oriented programming with illustrations.
Apr/May 2015
C++ Programming Features
• Classes
• Objects
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
30

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

• Dynamic Binding
• Message Passing
• Persistance and Delegation
• Genericity
Classes
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 class. Once a class has been
created any number of objects can be created belonging to that class. Thus a class is a
collection of objects of similar type.

ww Eg: fruit mango;


Where fruit is the class name and mango is the object name
Objects
w.E
asy
Objects are the basic run time entities in an object oriented system. They may
represent a person, a place or any item. A program object should be selected such that they

En
match closely with the real world objects. Objects communicate with each other by passing
message.
gi nee
Each object contains data and code to manipulate the data.

rin
Object : Student
g.n
STUDENT
DATA
Name
TOTAL
e t
DOB
Marks AVG

..........
FUNCTIONS DISPLAY
TOTAL
AVG
DISPLAY

31

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. It is the most striking feature of a class. The data is not accessible to the
outside world and those functions which are wrapped in the class only can access it. This
separation of the data from direct access is called data hiding.
Abstraction refers to the act of representing the essential features without including
the background details such as size, weight and cost. The variables are called as data
members and the function is called as methods or member function.

ww
Inheritance

w.E
It is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. It provides the idea of

asy
reusability which means that we can add additional features to an existing class without

En
modifying it. The newly created class is called as derived class and the old class is called as
base class.
FLYING
BIRD
gi BIRD

nee NON-FLYING

rin
BIRD

EAGLE CROW PENGUIN g.nKIWI

Polymorphism e
It is derived from a Greek word which means the ability to take more than one form.
t
It is classified into two types. They are
• Compile Time Polymorphism
❖ Operator Overloading
❖ Function Overloading
• Runtime Polymorphism
An operation may exhibit different behaviours in different instances. The behaviour
depends on the type of data used in the operation. That is, the process of making an operator
to exhibit different behaviours in different instances. It is called as operator overloading.

32

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

'+' when used with integers addition happens


'+' when used with strings concatenation happens
A single function name can be used to handle different number and different types of
arguments. It is called as function overloading.
Shape

Draw()

Draw() Draw()
Triangle

ww Circle Rectangle

Draw()

w.E
Dynamic Binding

asy
Binding refers to the linking of a procedure call to the code to be executed in

En
response to the function call. Dynamic Binding means that the code to be used for a

and polymorphism.
Message Passing
gi
function call is not known until the time of the call at run time. It is related to inheritance

nee
rin
An object oriented programming consists of a set of objects that communicate with
each other. The steps for communicating are
g.n



Create class with data and code
Create objects for that class
Establish communication
e t
employee . salary(name)

Object Information
Message
Persistance
This is the process in which the object(data) outlives the program execution time and
exist between the execution of the program. In C++, this can be achieved by explicitly using
the file streams.

33

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Delegation
Delegation is a way of making object composition as powerful as inheritance. In
delegation two objects are involved in handling a request receiving object delegates
operations to its delegate. This is analogous to child class sending requests to the parent
class.
Genericity
This is the technique for defining the generic software components(having more than
one interpretation depending on the data type of the parameter) where the declaration of
data items does not have the data type and the unknown data type is called as generic data

ww
type.

w.E CALL BY VALUE CALL BY REFERENCE

asy
7. Explain Call by value and Reference

Call by Value En
gi
Here the copy of the actual arguments is passed to the formal arguments.

nee
Hence any change in formal arguments is not affected in actual argument.

Eg:
rin
void swap(int a,int b)
{
g.n
int t=a;
a=b;
b=t;
cout<<"\nAfter swapping in Swap Function a and b are:"<<a<<b;
e t
}
void main()
{
int a,b;
cout<<"Enter 2 numbers:";
cin>>a>>b;
cout<<"Value of a and b before swapping:"<<a<<b;
swap(a,b);
cout<<"\nAfter swapping in Main Function a and b are:"<<a<<b;
}
O/p:
Enter two numbers: 10

34

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

20
Value of a and b before swapping: 10 20
After swapping in Swap Function a and b are: 20 10
After swapping in Main Function a and b are: 10 20

Call by Reference

Here the reference of the actual arguments is passed to the formal arguments.
Hence any change in formal arguments is affected in the actual argument.
Eg:
void swap(int *a,int *b)
{
int t=*a;
*a=*b;

ww *b=t;

w.E
cout<<"\nAfter swapping in Swap Function a and b are:"<<*a<<*b;
}
void main()
{
asy
int a,b;
En
gi
cout<<"Enter 2 numbers:";
cin>>a>>b;

nee
cout<<"Value of a and b before swapping:"<<a<<b;
swap(&a,&b);

} rin
cout<<"\nAfter swapping in Main Function a and b are:"<<a<<b;

O/p:
g.n
e
Enter two numbers: 10
20
Value of a and b before swapping: 10 20
After swapping in Swap Function a and b are: 20 10
t
After swapping in Main Function a and b are: 20 10

35

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT-II
INHERITANCE & POLYMORPHISM
Base Classes and Derived Classes – Protected Members – Casting Class pointers
and Member Functions – Overriding – Public, Protected and Private Inheritance –
Constructors and Destructors in derived Classes – Implicit Derived – Class Object
To Base – Class Object Conversion – Composition Vs. Inheritance – Virtual
functions – This Pointer – Abstract Base Classes and Concrete Classes – Virtual
Destructors – Dynamic Binding

PART-A
1. Define polymorphism.

ww • It means the ability to take more than one form.

w.E
• For ex, consider the operation of addition.
• If the operands are strings, then the operation would produce a third string by concatenation.

asy
•If the operands are numbers, it will generate a sum.

En
2. Define dynamic binding.
gi nee
• It refers to the linking of a procedure call to the code to be executed in response to the call.

rin
• Dynamic binging means that the code associated with a given procedure call is not
known until the time of the call at run time.
g.n
• It is associated with polymorphism and inheritance.
e t
3. Explain about Type Casting Operator.
This is used for conversion of variables or expression explicitly.
Syntax:
(type – name) expression or Type –name ( expression)
Ex: avg= sum/ float(i);
Alternatively, we can use typedef to create an identifier of the required type and use it in the
functional notation
typedef int * int_pt;
p= int_pt(q);

36

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. What is meant by this pointer? Nov/Dec 2014

• C++ uses the unique keyword called this to represent an object that invokes a member function.
• this is a pointer that points to the object for which this function was called.
• This unique pointer is automatically passed to a member function when it is called.
The pointer this acts as an implicit argument to all the member functions.
• One important application of the this pointer this is to return the object it points to.

5. What is meant by pure virtual function?

ww A virtual function that is declared in a base class but not defined there.The responsibility

w.E
for defining the function falls on the derived classes, each of which generally provides different
definitions.

asy
It is illegal to create instances of a class that declares a pure virtual function. So such a

En
class is necessarily an abstract base class.

6. Define abstract class. gi nee


rin
Abstract class is one that is not used to create objects. An abstract class is

g.n
designed only to act as a base class. It is a design concept in program development
and provides a base upon which other classes may be built.

7. What is Overriding?April/May 2015


e t
Many object-oriented programming languages permit a class or object to
replace the implementation of an aspect—typically a behavior—that it has inherited. This
process is usually called overriding.

37

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

8. Explain basic to class type conversion with an example.


Conversion from basic data type to class type can be done in destination
class.Using constructors does it. Constructor takes a single argument whose type is to
be converted.
Eg: Converting int type to class type
class time
{
int hrs,mins;
public:

ww ………….
Time ( int t) //constructor
{
w.E
hours= t/60 ; //t in minutes

asy
mins =t % 60;
}
En
};
gi nee
Constructor will be called automatically while creating objects so that this conversion
is done automatically.

rin
9. Explain class to basic type conversion with an example.
g.n
be done. It is done in the source class itself.
Eg:
e
Using Type Casting operator, conversion from class to basic type conversion can

t
vector : : operator double( )
{
double sum=0;
for(int I=0;I<size;I++)
sum=sum+v[ i ] *u[ i ] ;
return sqrt ( sum ) ;
}
This function converts a vector to the corresponding scalar magnitude.

38

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

10. Explain one class to another class conversion with an example.

Conversion from one class type to another is the combination of class to basic and
basic to class type conversion. Here constructor is used in destination class and casting
operator function is used in source class.
Eg:objX=objY
objX is the object of class X and objY is an object of class Y. The class Y type data is
converted into class X type data and the converted value is assigned to the obj X. Here
class Y is the source class and class X is the destination class.

ww .
11. Why there is need for operator overloading?April/May 2015

w.E
Operator overloading provides a flexile option for the creation of new

asy
definitions for the most of the C++ operator. C++ has the ability to provide the

En
operators with a special meaning for a datatype

gi nee
12. Write a C++ code to display as area of square or rectangle using function
overriding.Nov/dec 2014
#include<iostream.h>
rin
Class rectangle
g.n
{
private:
Double len,breadth:
e t
public:
void setlengthbreadth(double l,double b);
void computeArea();
void Rectangle::setlengthbreadth(double l,double b)
{
len=l;
breadth=b;
}

39

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

void Rectangle::computeArea()
{
double area;
Area=len*breadth;
cout<<”\n Area of Recangle =”<<area;
}
class square:public Rectangle
{
private:

ww public:
Double len;

w.E void setlength(double l);


void computeArea();

asy void square::setlength(double l)

En {

gi }
len=l;

void square::computeArea() nee


{
rin
double area;
g.n
}
Are=len*len;
cout<<”\narea of Square=”<<area; e t
int main()
{
Rectangle obj1;
Square obj2;
obj1.setlengthBreadth(10,20);
obj1.computeArea();
obj2.setlength(10);
obj2.ComputeArea();// function overriding

40

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return 0;
}
Output
Area of the Rectangle =200
Area of square=100
13. Write a sample to code to show the usage of this pointer in C++.
Nov/ Dec 2014
#include<iostream.h>
/* local variable is same as a member's name */

ww class Test
{

w.E
private:
int x;
public: asy
void setX (int x)
En
{
gi nee
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
rin
}
g.n
};
void print() { cout << "x = " << x << endl; }

int main(void)
e t
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

41

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

14. Differentiate private and protected members of a class.Nov/Dec 2015

Private - only available to be accessed within the class that defines them.
protected - accessible in the class that defines them and in other classes which inherit
from that class.
15. What is dynamic binding?Nov/Dec 2015
Dynamic binding also called dynamic dispatch is the process of linking procedure
call to a specific sequence of code (method) at run-time. It means that the code to be
executed for a specific procedure call is not known until run-time. Dynamic binding is also

ww
known as late binding or run-time binding.

w.E PART – B

asy BASED AND DERIVED CLASS


1. a Explain based and derived class with examples. Nov/ Dec 2015

En
Base & Derived Classes:
gi nee
A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation list
rin
to specify the base class(es). A class derivation list names one or more base classes and has
the form:
g.n
class derived-class: access-specifier base-class
e
Where access-specifier is one of public, protected, or private, and base-class is the t
name of a previously defined class. If the access-specifier is not used, then it is private by
default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream.h>
// Base class
class Shape
{
public:
void setWidth(int w)

42

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;

ww
};
int height;

w.E
// Derived class
class Rectangle: public Shape
{ asy
public:
En
{ gi
int getArea()

return (width * height); nee


}
rin
};
g.n
int main(void)
{
Rectangle Rect;
e t
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total area: 35

43

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ACCESS MODIFIERS

1.b. Explain about C++ class access modifiers in detail.

Data hiding is one of the important features of Object Oriented Programming which

allows preventing the functions of a program to access directly the internal representation of

a class type. The access restriction to the class members is specified by the labeled public,

private, and protected sections within the class body. The keywords public, private, and

ww
protected are called access specifiers.

w.E
A class can have multiple public, protected, or private labeled sections. Each section

remains in effect until either another section label or the closing right brace of the class

asy
body is seen. The default access for members and classes is private.

class Base En
{ gi nee
public:
rin
// public members go here
g.n
protected:

// protected members go here


e t
private:

// private members go here

};

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords

introduced, namely,

44

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

• Public

• private

• protected

These access specifiers are used to set boundaries for availability of members of

class be it data members or member functions.Access specifiers in the program, are

followed by a colon. You can use either one, two or all 3 specifiers in the same class to set

different boundaries for different class members. They change the boundary for all the

ww
declarations that follow them.

Public:
w.E
Public, means all the class members declared under public will be available to everyone.
asy
The data members and member functions declared public can be accessed by other classes

En
too. Hence there are chances that they might change them. So the key members must not be

declared public. gi nee


class PublicAccess
rin
{
g.n
public: // public access specifier

int x; // Data Member Declaration


e t
void display(); // Member Function decaration

45

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Private:

Private keyword, means that no one can access the class members declared private outside

that class. If someone tries to access the private member, they will get a compile time error.

By default class variables and member functions are private.

class PrivateAccess

ww private: // private access specifier

w.E int x; // Data Member Declaration

void display(); // Member Function decaration

} asy
Protected: En
gi nee
Protected, is the last access specifier, and it is similar to private, it makes class member

rin
inaccessible outside the class. But they can be accessed by any subclass of that class. (If

class A is inherited by class B, then class B is subclass of class A.


g.n
class ProtectedAccess
{
protected: // protected access specifier
e t
int x; // Data Member Declaration
void display(); // Member Function decaration
}

46

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

CLASS OBJECT TO BASE AND BASE TO CLASS OBJECT

2. Explain about class object to base and base to class object conversion using
C++ with suitable example. Nov/Dec14

• The class pointer can be cast by the base or by the derived class
• If the base class pointer is cast by the derived class then it is called upcasting
• If the derived class pointer is cast by the base class then it is called d owncasting
• The member function can then be accessed using these pointers

wwUpcasting:

w.E
#include<iostream.h>
class mother
{
asy
public:
En
{ gi
void cooks()

cout<<”mother coks food”; nee


}
rin
};
g.n
class child:public mother
{
public:
e t
void studies()
{
cout<<”child studies”;
}
};
int main()
{
child child;mother *pmother=&child;

47

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

pmother->cooks
return 0;
}
Downcasting:

A downcast is the cast frm a base class to a class derived from that base class.The
upcast is a cast form derived class t the baese class.The upcast is safe and implicit but the
downcast needs to be dne carefully .In the following program we are performing
downcasting and then invoking the methods of corresponding classes

ww . #include<iostream.h>
class mother

w.E
{
public:

asy void cooks()’

En{

};
}gi cout<<”mother coks food”;

nee
class child1:public mother
rin
{
g.n
public:
void studies()
{
e t
cout<<”child1 studies”;
}
};
class child2:public mother
{
public:
void studies()
{

48

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

cout<<”child2 studies”;
}
};
int main()
{
mother *mother=new child1;
child1 *pchild1=(child1*)(pmother);
child2 *pchild1=(child2*)(pmother);
cout<<”using object of mother class”;

ww pmother->cooks();
cout<<”using object of child1 class”;

w.E pchild1->studies();
cout<<”using object of child2 class”;

asy
pchild1->studies();
}
En
gi
VIRTUAL FUNCTIONS
nee
3. Explain about the virtual functions in detail.
rin
April/May 2015,Nov/Dec 2015

g.n
e
A virtual function is a member function that you expect to be redefined in derived
classes. When you refer to a derived class object using a pointer or a reference to the base
class, you can call a virtual function for that object and execute the derived class's version
t
of the function.
It is made possible using virtual function. A virtual function is a member function that
is declared within a base class and redefined by a derived class. The whole function body
can be replaced with a new set of implementation in the derived class. To make a function
virtual, the virtual keyword must be in front of the function declaration in the base class.
Eg:
#include<iostream.h>
#include<conio.h>

49

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

class shape
{
public:
virtual void draw()
{
cout<<"shape is drawn";
cout<<endl;
}
};

ww
class circle:public shape
{

w.E
public:
void draw()
{ asy
En
cout<<"circle is drawn";

};
} gi
cout<<endl;

nee
void main()
rin
{
g.n
clrscr();
shape s;
shape *ps;
e t
ps=&s;
cout<<"s.draw(): ";
s.draw();
cout<<"ps->draw(): ";
ps->draw();
circle c;
ps=&c;
cout<<"\n";

50

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

cout<<"After pointer ps is set to hold the address of object c";


cout<<"\n \n";
cout<<"c.draw(): ";
c.draw();
cout<<"ps->draw(): ";
ps->draw();
getch();
}

ww Output:
s.draw():shape is drawn

w.E
ps->draw():shape is drawn
After pointer ps is set to hold the address of object c

asy
c.draw():circle is drawn

En
ps->draw():circle is drawn
Explanation:
gi nee
Initially the pointer to object 'ps' is made to point the shape object. Hence when ps->draw()
is called shape draw function is executed. When the pointer to object ps is made to point

rin
circle object. When ps->draw() is called the circle draw function is called because the circle
function in shape is made virtual.
g.n
THIS POINTER e t
4. Explain about this pointer and types of binding.Nov/Dec 2015

This Pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.

51

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Let us try the following example to understand the concept of this pointer:
#include <iostream.h>
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;

ww length = l;
breadth = b;

w.E
}
height = h;

asy
double Volume()
{
En
} gi
return length * breadth * height;

int compare(Box box) nee


{
rin
return this->Volume() > box.Volume();
g.n
}
private:
double length; // Length of a box
e t
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))

52

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}

ww
When the above code is compiled and executed, it produces the following result:
Constructor called.

w.E
Constructor called.
Box2 is equal to or larger than Box1
StaticBinding asy
En
By default, matching of function call with the correct function definition happens

gi
at compile time. This is called static binding or early binding or compile-time binding.

nee
Static binding is achieved using function overloading and operator overloading.
Dynamic Binding

rin
C++ provides facility to specify that the compiler should match function calls

g.n
with the correct definition at the run time; this is called dynamic binding or late binding

e
or run-time binding. Dynamic binding is achieved using virtual functions. Base class
pointer points to derived class object. And a function is declared virtual in base class,
then the matching function is identified at run-time using virtual table entry.
t

53

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

INHERITANCE

5. What is inheritance? Discuss in detail about the various types of inheritances in


C++ with suitable examples. Apr/May 2015

It is a process by which the object of one class acquire the properties of objects of
another class. The new class is called as derived class whereas the already existing
one is called as base class.
The various types of inheritance are

ww ❖

Single Inheritance
Multilevel Inheritance


w.E
Multiple Inheritance
Hierarchical Inheritance
❖ asy
Hybrid Inheritance
The syntax is
En
{ gi
class derivedclassname : visibilitymode baseclassname

nee
//STS;
}; rin
Base Class Derived Class Visibility
g.n
Visibility
Private

Public
Public
Not Inherited

Public
Private
Not Inherited

Private
Protected
Not
Inherited
Protected
e t
Protected Protected Private Protected

Single Inheritance
It is an inheritance where a derived class has only one base class.
BASE CLASS
A

DERIVED CLASS

54

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Eg:
class A
{
public:
int a;
void puta()
{
cout<<a;

ww
};
}

w.E
class B:public A
{
public: asy
int b;
En
void putb()
{
cout<<b;
gi nee
}
rin
};
g.n
void main()
{
B obj;
e t
obj.a=10;
obj.b=15;
obj.puta();
obj.putb();
}
Output
10 15

55

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Explanation
Here the variable 'a' and puta() in class A are inherited to class B with public visibility
mode.

Multiple Inheritance

It is an inheritance where the derived class has more than one base class

A B

ww
Eg:
class A
w.E C

{ asy
public:
En
int a;
void puta()
{
gi nee
cout<<a;
rin
}
g.n
};
class B
{
e t
public:
int b;
void putb()
{
cout<<b;
}
};
class C:public A,public B

56

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
public:
int c;
void putc()
{
cout<<c;
}
};

ww
void main()
{

w.E
C obj;
obj.a=10;
obj.b=15; asy
obj.c=20;
En
obj.puta();
obj.putb();
obj.putc();
gi nee
}
rin
Output:
g.n
10 15 20
Explanation: e
Here the variables 'a' from class A and 'b' from class B are inherited to class C with
t
public visibility mode.

Multilevel Inheritance

The derived class is derived from intermediate base class which is already derived from
a base class. A

Intermediate Base Class B

57

C
Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net

Example program:
class A
{
public:
int a;
void puta()
{
cout<<a;

ww
};
}

w.E
class B : public A
{
public: asy
int b;
En
void putb()
{
cout<<b;
gi nee
}
rin
};
g.n
class C:public B
{
public:
e t
int c;
void putc()
{
cout<<c;
}
};
void main()
{

58

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

C obj;
obj.a=10;
obj.b=15;
obj.c=20;
obj.puta();
obj.putb();
obj.putc();
}
Output:

ww
10 15 20
Explanation:

w.E
The variables 'a' from class A is inherited to class B. Then variable 'a' and 'b' from class
B are inherited to class C with public visibility mode.
Hierarchical Inheritance asy
En
In this more than one derived class have the same base class

gi A

nee
Eg: B C
rin
class A
g.n
{
public:
int a;
e t
void puta()
{
cout<<a;
}
};
class B : public A
{
public:

59

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

int b;
void putb()
{
cout<<b;
}
};
class C:public A
{
public:

ww int c;
void putc()

w.E
{
cout<<c;
} asy
};
En
void main()
{
B obj;
gi nee
obj.a=5;
rin
obj.b=10;
g.n
obj.puta();
obj.putb();
C obj;
e t
obj.a=10;
obj.c=20;
obj.puta();
obj.putc();
}
Explanation:
The variables 'a' from class A is inherited to class B. Also variable 'a' from class A are
inherited to class C with public visibility mode.

60

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Hybrid Inheritance
It is a combination of two or more inheritance.

B C

ww
Eg:

w.E
class A
{
public: asy
int a;
En
void puta()
{ gi
cout<<a; nee
}
rin
};
g.n
class B : public A
{
public:
e t
int b;
void putb()
{
cout<<b;
}
};
class C:public A
{

61

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

public:
int c;
void putc()
{
cout<<c;
}
};
class D: public B, public C
{

ww public:
int d;

w.E
void putd()
{

asy
cout<<d;
}
En
};

void main()
gi nee
{
rin
D obj;
g.n
obj.a=5;
obj.b=10;
obj.c=20;
e t
obj.d=20;
obj.puta();
obj.putb();
obj.putc();
obj.putd();
}

62

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

PART - C
EXAMPLE PROGRAM

6. Write a C++ code to construct classes of a person with name and age as public
properties, account details as private properties and percentage of mark as protected
property. Construct a class with sports details of person. Construct a class to rank
person based on the equal weightage to academic and sports details. Use inheritance
concept. Nov/Dec 14

ww #include<iostream.h>
Class Person
{
w.E
private:
asy
int accno;
public:
En
int age; gi
char name[10];

nee
void PersonDetails()
{ rin
cout<<” Enter your name”;
g.n
cin>> name;
cout<<”\n Enter your age:”; e t
cin>>age;
cout<<”\n Enter Account Number:”;
cin>> accno;
}
void displayPersonDetails()
{
cout<<”\n Name:”<< name;
cout<< “\n Age:”<<age;
cout<<”\n Account Number:”<<accno;

63

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
};
class Academic:public Person
{
protected:
double marks;
public:
void AcademicMarks()
{

ww cout<<”\n Enter Academic marks”;


cin>>marks;

w.E
}
void displayAcademicMarks()
{ asy
En
Cout<<”\n Academic Marks:”;<<marks;

};
}

class Sports
gi nee
{
rin
protected:
g.n
double score;
public:
void SportsScore()
e t
{
cout<<”\n Enter Sports Score:”;
cin>>score;
}
void displaySportsScore()
{
cout<<”\n Sports Marks:”<<score;
}

64

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
class Rank:public Academic, public Sports
{
double totalMarks;
double m,s;
public:
void display()
{
m=marks/2;

ww s=score/2;
totalMarks=m+s;

w.E displayPersonalDetails();
displayAcademicMarks();

asy
displaySportsScore();

En
cout<<”\n Total Marks:”<<totalMarks;

};
}

void main()
gi nee
{
rin
Rank obj;
g.n
obj.PersonalDetails();
obj.AcademicMarks();
obj.SportsScore();
e t
obj.display();
}
Input:
Enter your name : AAA
Enter your age : 22
Enter Account Number : 1234
Enter Academic marks : 64
Enter Sports Score : 46

65

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Output:
Name : AAA
Age : 22
Account Number : 1234
Academic Marks : 64
Sports Marks : 46
Total Marks : 55

ww
w.E
asy
En
gi nee
rin
g.n
e t

66

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

IMPLEMENTATION OF CONSTRUCTORS

7. Write a program to illustrate how constructors are implemented when the classes
are inherited. Nov/Dec 2015
#include<iostream.h>
class Base
{
public:
Base()

ww {
Cout<<"Base Class Constructor Called ";

w.E
};
}

asy
En
class Derived : public Base
{
public: gi nee
Derived()
{ rin
g.n
cout<<"Derived Class Constructor Called ";

};
}
e t
void main()
{
Derived obj;
}

Output:
Base Class Constructor Called
Derived Class Constructor Called

67

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT – III
LINEAR DATA STRUCTURES

Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list
implementation –– singly linked lists –Polynomial Manipulation – Stack ADT – Queue
ADT – Evaluating arithmetic expressions.

PART A

1. Define ADT (Abstract Data Type). Apr/May 2015, Nov/Dec 2015

ww Abstract Data type is defined by the set of operations that may be performed on it

w.E
and by mathematical constraints on the effects of those operations.
Abstract Data type is an extension of modular design.

asy
• An abstract data type is a set of operations such as Union, Intersection, Complement,
Find etc.,
En
gi
• The basic idea of implementing ADT is that the operations are written once in

nee
program and can be called by any part of the program

2. What do you mean by queue ADT? rin Nov/Dec 2015

g.n
e
The queue abstract data type is defined by the following structure and operations. A
queue is structured, as an ordered collection of items which are added at one end, called the
t
“rear”, and removed from the other end, called the “front”. Queues maintain a FIFO
ordering property.

3. Write short notes on queue? Apr/May 2015

Queue is an ordered collection of elements in which insertions and deletions are


restricted to one end. The end from which elements are added and /or removed is referred to
as the rear end and the end from which deletions are made is referred to as front end.

68

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. Define Binary Heap. Nov/Dec 2012, Apr/May 2009

The implementation we will use is known as a binary heap. Its use is so common for
priority queue implementations that when the word heap is used without a qualifier
Structure Property A heap is a binary tree that is completely filled, with the possible
exception of the bottom level, which is filled from left to right. Such a tree is known as a
complete binary tree.
6. What are the operations of ADT?

ww Union, Intersection, size, complement and find are the various operations of ADT.

w.E
7. What are the two parts of ADT?

• Value definition asy


• Operator definition
En
gi
8. Define len(S),first(S),last(S),nilseq.
nee
len(S) is the length of the sequence S.
rin
first(S) returns the value of the first element of S
g.n
last(S) returns the value of the last element of S
nilseq :Sequence of length 0 is nilseq .ie., contains no element. e t
9. Define Structure and Union.

A Structure is a group of items in which each item is identified by its own identifier,
each of which is known as a member of the structure.
Union is collection of Structures , which permits a variable to be interpreted in
several different ways.

69

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

10. What is a Stack? Nov/Dec 2008

A Stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at one end, called the top of the stack. The other name of
stack is Last-in - First-out list.

11. What is a Queue?

A Queue is an ordered collection of items from which items may be deleted one end

ww
called the front of the queue and into which tems may be inserted at the other end called
rear of the queue.Queue is called as First–in-First- Out(FIFO).

w.E
12. What is a Priority Queue? Nov/Dec 2010

asy
En
Priority queue is a data structure in which the intrinsic ordering of the elements does

the two types of Priority queue.


13. What is a linked list?
gi
determine the results of its basic operations. Ascending and Descending priority queue are

nee
rin
g.n
Linked list is a kind of series of data structures, which are not necessarily adjacent in
memory. Each structure contain the element and a pointer to a record containing its
successor. e t
14. What is a doubly linked list? April/May 2014

In a simple linked list, there will be one pointer named as 'NEXT POINTER' to point
the next element, where as in a doubly linked list, there will be two pointers one to point the
next element and the other to point the previous element location.

70

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

16. Evaluate the value of expression ab+c*d using stack.


Nov/Dec2014

Input read Action Taken Stack contents


a Push value of “a” onto the stack A
b Push value of “b” onto the stack B
+ Pop “b” and “a” values .Perform a+b and (a+b)
push the result on to the stack
c Push value of “c” onto the stack (a+b) c

ww
*
d
Pop “c”
Push value of “d” onto the stack
(c*(a+b))
(c*(a+b)) d
-
w.E
Pop “d” (c*(a+b)) - d

asy
Pop the contents of the stack and print the
result

En
gi PART B

SINGLY LINKED LIST nee


rin
1. a) Write a note on singly linked list.
g.n
Nov/Dec 2015

e
Linked list consists of series of nodes. Each node contains the element and a pointer to
its successor node. The pointer of the last node points to NULL. t
Insertion and deletion operations are easily performed using linked list. A single node
is represented as follows

Actual representation of the singly linked list:

71

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Singly Linked list with actual pointers

Singly linked lists

ww A singly linked list is a linked list in which each node contains only one link
field pointing to the next node in the list.

w.E
#include <iostream.h>
// Node class class Node { int data;

asy
Node* next;
En
public:
Node() {}; gi
void SetData(int aData) { data = aData; }; nee
rin
void SetNext(Node* aNext) { next = aNext; }; int Data() { return data; };
Node* Next() { return next; };
g.n
};

Example: Insert the element ‘5’ in the beginning of the list temp.
e t
Before insertion

After Insertion :

72

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

void List::Append(int data)


{
// Create a new node
Node* newNode = new Node(); newNode-
>SetData(data); newNode->SetNext(NULL);
// Create a temp pointer Node *tmp = head;
if ( tmp != NULL ) {
// Nodes already present in the list
// Parse to end of list

ww while ( tmp->Next() != NULL ) { tmp = tmp-


>Next();

w.E
}
// Point the last node to the new node tmp-
>SetNext(newNode);asy
}
En
else {
gi
// First node in the list
head = newNode; nee
}
rin
}
g.n
DELETION AT FIRST

Before deletion
e t

After deletion

Delete a node from the list */


void List::Delete(int data)

73

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
// Create a temp pointer Node *tmp = head;

// No nodes

if ( tmp == NULL ) return;


// Last node of the list
if ( tmp->Next() == NULL ) { delete tmp;
head = NULL;

ww }
Else
{
//
w.E Parse thru the nodes Node *prev;
do { asy
En
if ( tmp->Data() == data ) break; prev = tmp;

//
tmp = tmp->Next();
} while ( tmp != NULL ); gi
Adjust the pointers nee
prev->SetNext(tmp->Next());
rin
// Delete the current node delete tmp;
g.n
}
} e t
LIST ADT

1.b) Explain List ADT Nov/Dec 2015

List ADT is a sequential storage structure.


General list of the form a1, a2, a3.…., an and the size of the list is 'n'.
Any element in the list at the position I is defined to be ai, ai+1 the successor
of ai and ai-1 is the predecessor of ai.

74

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Empty list of size 0.


Various operations performed on List
1. Insert (X, 5) - Insert the element X after the position 5.
2. Delete (X) - The element X is deleted
3. Find (X) - Returns the position of X.
4. Next (i) - Returns the position of its successor element i+1.
5. Previous (i) - Returns the position of its predecessor i-1.
6. Print list - Contents of the list is displayed.
7. Make empty - Makes the list empty

ww Implementation of List ADT


1. Array Implementation

1.
w.E
2. Linked List Implementation
Array Implementation of List

asy
Array is a collection of specific number of data stored in a consecutive memory
location.
En
List ADT: Array Insertion
gi
Suppose we insert x at position 0. insert(x, 0)
nee
• Must move every element in the array down one position. That takes N operations
(one for moving each element in the array).
rin
1, 4, 32, 6, 29, -3 x, 1, 4, 32, 6, 29, -3
g.n
So inserting one number is O(N) and inserting N numbers could take up to N2 time!.
e
We often have to do many inserts – three, twelve, or N.That‟s the worst case, depending on
where they are inserted.
t
List ADT: Array Deletion
Same problem as insertion.
• On average will have to move at least half the list up one position.
• If don’t move elements, then findKth won’t work.
• And if delete 0th position will have to move the whole list; N operations or
O(N).
• So deleting a single element will be O(N).
• And deleting N elements will take O(N2 ).

75

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

• And we usually have to delete more than once – five, twelve, N times.
2. Linked List Implementation
• A linked list is a series of connected NODES, where each node is a data structure.
• A linked list can grow or shrink in size as the program runs
The composition of a Linked List
• Each node in a linked list contains one or more members that represent data.
• In addition to the data, each node contains a pointer, which can point to another
node.
• A linked list is called "linked" because each node in the series has a pointer that

ww points to the next node in the list.

w.E
asy
En
gi
APPLICATIONS OF STACK

nee
2. Explain the applications of stack in detail.
rin Nov/Dec 2015
• Stack is used by compilers to check for balancing of parentheses, brackets and braces
• Stack is used to evaluate a postfix expression. g.n
• Stack is used to convert an infix expression into postfix/prefix form.
• In recursion, all intermediate arguments and return values are stored on the
e t
processor’s stack.
• During a function call the return address and arguments are pushed onto a stack and
on return they are popped off.
Different Types of Notations to Represent Arithmetic Expression
There are 3 different ways of representing the algebraic expression. They are
* INFIX NOTATION
* POSTFIX NOTATION
* PREFIX NOTATION

76

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

INFIX
In Infix notation, The arithmetic operator appears between the two operands to which
it is being applied. For example : - A / B + C
POSTFIX
The arithmetic operator appears directly after the two operands to which it applies.
Also called as reverse polish notation. ((A/B) + C). For example : - AB / C +
PREFIX
The arithmetic operator is placed before the two operands to which it applies. Also
called as polish notation. ((A/B) + C). For example : - +/ABC

ww
INFIX PREFIX (or) POLISH POSTFIX (or) REVERSE POLISH
1. (A + B) / (C - D) /+AB - CD AB + CD - /

w.E
2. A + B*(C - D)
3. X * A / B - D
+A*B - CD
- / * XABD
ABCD - * +
X A*B/D-
4. A * B/C + D asy
+/ * ABCD AB * C / D +

En
gi
1. Evaluating Arithmetic Expression

nee
To evaluate an arithmetic expressions, first convert the given infix expression to postfix
expression and then evaluate the postfix expression using stack.
Infix to Postfix Conversion
rin
g.n
Read the infix expression one character at a time until it encounters the delimiter. "#"
Step 1 : If the character is an operand, place it on to the output.
e
Step 2 : If the character is an operator, push it onto the stack. If the stack operator has a
higher or equal priority than input operator then pop that operator from the stack and place
t
it onto the output.
Step 3 : If the character is a left paraenthesis, push it onto the stack.
Step 4 : If the character is a right paraenthesis, pop all the operators from the stack till it
encounters left parenthesis, discard both the parenthesis in the output.
Evaluating Postfix Expression

Read the postfix expression one character at a time until it encounters the delimiter `#'.
Step 1 : - If the character is an operand, push its associated value onto the stack.

77

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Step 2 : - If the character is an operator, POP two values from the stack, apply the operator
to them and push the result onto the stack.

Infix Expression : A * B #

Read Character Stack Output

A A

ww
w.E * * A

asy
En
B
gi *

nee
AB

rin
# AB*
g.n
Example: Let us consider the symbols A,B, with values
e t
Symbol Value
A 4
B 5

EVALUATION OF A B *

78

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Read Character Stack

A 4

-
5
B
4

ww * 20 result=20

w.E
asy
En
1. Balancing the symbols

gi
Read one character at a time until it encounters the delimiter. "#"

nee
Step 1 : If the character is an opening symbol, push it on to the stack.
Step 2 : If the character is a closing symbol, and if the stack is empty, then report an
error as missing opening symbol.
rin
g.n
Step 3 : If the character is a closing symbol and if it has a corresponding opening

mismatched symbols. e
symbol in the stack, then pop it from the stack. Otherwise report an error as

t
Step 4 : At the end of file, if the stack is not empty, report an error as missing closing
symbol. Otherwise report as balanced symbols.
Let us consider the expression (a+b)#

Read Character Stack

( (

79

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

a (

+ (

b (

ww # Balanced symbol. Stack is empty.

w.E
3. Towers of Hanoi asy
En
The problem is moving a collection of N disks of decreasing size from one pillar to

gi
another pillar. The movement of the disk is restricted by the following rules.
Rule 1: Only one disk could be moved at a time.
nee
Rule 2: No larger disk could ever reside on a pillar on top of a smaller disk.

rin
Rule 3: A 3rd pillar could be used as an intermediate to store one or more disks, while they
werebeing moved from sourced to destination.
g.n
Recursive Solution
N - represents the number of disks.
Step 1. If N = 1, move the disk from A to C.
e t
Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C, Then
move the 1st disk from B to C.
Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as
intermediate.
Then the 3rd disk is moved from A to C. Then repeat the step (2) to move 2 disks
from B to C using A as intermediate.

80

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

In general, to move N disks. Apply the recursive technique to move N - 1 disks from
A to B using C as an intermediate. Then move the Nth disk from A to C. Then again apply
the recursive technique to move N - 1 disks from B to C using A as an intermediate.
RECURSIVE ROUTINE FOR TOWERS OF HANOI
void hanoi (int n, char s, char d, char i)
{
/* n no. of disks, s source, d destination i intermediate */
if (n = = 1)
{

ww print (s, d);


return;

w.Eelse
}

{ asy
En
hanoi (n - 1, s, i, d);

gi
print (s, d)
hanoi (n-1, i, d, s);
return; nee
}
rin
}
g.n
4.Function Calls
e
When a call is made to a new function all the variables local to the calling routine
need to be saved, otherwise the new function will overwrite the calling routine variables.
t
Similarly the current location address in the routine must be saved so that the new function
knows where to go after it is completed.
Main( ) Balance ( ) Push ( )

Call Balance ( ) Call Push ( )

Return Return

81

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

RECURSIVE FUNCTION TO FIND FACTORIAL: -


int fact (int n)
{
int s;
if (n = = 1)
return (1);
else
s = n * fact (n - 1);
return (s);

ww }
STACKS

w.E
3. Write a set of routines for implementing two stacks within a single array.

asy April/May 2015


Implementation of stack
Array Implementation En
empty stack.
gi
In this implementation each stack is associated with a Top pointer,which is -1 for an

nee
rin
• To push an element x on to the stack,Top pointer is incremented and then set
Stack[Top]=x
g.n
• To pop an element,the stack[Top] value is returned and the top pointer is
decremented,. e
• Pop on an empty stack or push on a full stack will exceed the array bounds.
t
Routine to push an element on to a stack
void push (int x, Stack S)
{
if (IsFull (S))
Error ("Full Stack");
}
else

82

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
Top = Top + 1;
S[Top] = x;
}
}
int IsFull (Stack S)
{
if (Top = = Arraysize)
return (1);

ww }

Stack
w.E can be implemented using arrays and

asy
En
gi nee
rin
g.n
pointers.
e t
Routine to pop an element from the stack
void pop(stack S)
{
if(IsEmpty(S));
Error(“Empty stack”);
else
{

83

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

X=S[Top];
Top=Top-1;
}
}
int IsEmpty(stack S)
{
if(Top==-1)
return(1);
}

ww
Routine to return top element of the stack
int TopElement(stack S)
{
w.E
if(!IsEmpty(s))

asy
return s[Top];
else
En
}
return 0; gi
Error(“Empty stack”);

nee
Linked List Implementation of Stack
rin
g.n
Push operation is performed by inserting an element at the front of the list.
Pop operation is performed by deleting at the front of the list.
Top operation returns the element at the front of the list.
Declaration for linked list Implementation
e t
struct Node;
typedef struct Node *stack;
int IsEmpty(stack S);
stack Createstack(void);
void MakeEmpty(stack S);
void push(int X,stack S);
int Top(stack S);
void Top(stack S);

84

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

struct Node
{
int Element;
struct Node *Next;
}
Routine to check whether the stack is Empty.
int IsEmpty(stack S)
{
if(S-> Next==NULL)

ww
}
return(1);

w.E
Routine to create an Empty stack
stack CreateStack()
{ asy
stack S;
En
if(s==NULL) gi
S=malloc(sizeof(struct Node));

Error(“Out of space”); nee


Make Empty(S);
rin
return S;
g.n
}
void MakeEmpty(stack S)
{
e t
if(S==NULL)
Error(“Create stack First”);
else
while(!IsEmpty(S))
pop(S);
}

Routine to push an element onto a stack

85

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

void push(int X,stack S)


{
Struct Node *Tempcell;
Tempcell=malloc(sizeof(struct Node))
if(Tempcell==NULL)
Error(“out of space”);
else
{
Tempcell->Element=X;

ww Tempcell->Next=S->Next;
S->Next=Tempcell;
}
}
w.E
asy
Routine to return Top Element in a stack
int Top(stack S)
En
{
if(!ISEmpty(S)) gi
return S-> Next -> Element; nee
else
rin
Error(“Empty stack”);
g.n
}
return 0;

Routine to pop an element from the stack


e t
void pop(stack S)
{
Struct Node *Tempcell
if (IsEmpty(S))
Error(“Empty stack”);
else
{
Tempcell=S-> Next;

86

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

S ->Next=S->Next-> Next;
Free(Tempcell);
}
}
QUEUE

4. Write a set of routines for implementing queue using linked lists.


April/May 2015
Queue is a Linear data structure which follows First In First Out (FIFO) principle, in

ww
which insertion is performed at rear end and deletion is performed at front end.

w.E
DEQUEUE(Q) QUEUE ENQUEUE(Q)
asy
OPERATIONS ON QUEUE
En
gi
The fundamental operations performed on queue are: Enqueue and Dequeue.

nee
Enqueue : The process of inserting an element in the queue.
Dequeue : The process of deleting an element from the queue.

rin
EXCEPTIONAL CONDITIONS
g.n
be overflow. e
Oveflow: Attempt to insert an element into the queue, when the queue is full is said to

t
Underflow: Attempt to delete an element from the queue, when the queue is empty is
said to be underflow.
IMPLEMENTATION OF QUEUE
Queue can be implemented in 2 ways.
1. Array Implementation
2. Linked List Implementation

87

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ARRAY IMPLEMENTATION
o In order to create a queue we require a one dimensional array Q(1:n) and two
variables front and rear. The conventions we shall adopt for these two
variables are that front is always 1 less than the actual front of the queue and
rear always points to the last element in the queue.
• Thus, front = rear if and only if there are no elements in the queue.
• The initial condition is front = rear = -1.
• The various queue operations to perform creation, deletion and display the elements
in a queue are as follows:

ww• insertQ(): inserts an element at the end of queue Q.

w.E
• deleteQ(): deletes the first element of Q.
• displayQ(): displays the elements in the queue.
asy
En
• In this implementation queue Q is associated with two pointers namely rear pointer
and front pointer.
gi nee
• To insert an element X onto the Queue Q, the rear pointer is incremented by 1 and
then set Queue [Rear] = X
rin
• To delete an element, the Queue [Front] is returned and the Front Pointer is
incremented by 1. g.n
ROUTINE TO ENQUEUE
e t
void Enqueue (int X)
{
if (rear = = max _ Arraysize-1)
print (" Queue overflow");
else
{
rear = rear + 1;
Queue [rear] = X;
if(front==-1)
88

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

front=0;
}
}

ROUTINE FOR DEQUEUE


void delete ( )
{
if (front < 0)
print (" Queue Underflow");

ww else
{

w.E X = Queue [front];


if (front = = rear)

asy {

En front = -1;

gi
else
}
rear = -1;

nee
front = front + 1 ;
rin
}
g.n
}
e
In Dequeue operation, if Front = Rear, then reset both the pointers to their initial values.
(i.e. F = -1, R = -1)
t
LINKED LIST IMPLEMENTATION OF QUEUE
We can represent a queue as a linked list. In a queue data is deleted from the front
end and inserted at the rear end. We can perform similar operations on the two ends of a list.
We use two pointers front and rear for our linked queue implementation.

89

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Front rear

100 400

30 400 40 X
10 200 20 300

ww 100 200 300 400



w.E
Enqueue operation is performed at the end of the list.
Dequeue operation is performed at the front of the list.

asy
En
DECLARATION FOR LINKED LIST IMPLEMENTATION OF QUEUE ADT
Struct Node;
gi
typedef Struct Node * Queue;
int IsEmpty (Queue Q); nee
Queue CreateQueue (void);
rin
void MakeEmpty (Queue Q);
g.n
void Enqueue (int X, Queue Q);
void Dequeue (Queue Q);
Struct Node
e t
{
int Element;
Struct Node *Next;
}* Front = NULL, *Rear = NULL;
ROUTINE TO CHECK WHETHER THE QUEUE IS EMPTY
int IsEmpty (Queue Q) // returns boolean value /
{ // if Q is empty
if (Q→Next = = NULL) // else returns 0

90

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return (1);
}
ROUTINE TO CHECK AN EMPTY QUEUE
Struct CreateQueue ( )
{
Queue Q;
Q = malloc (Sizeof (Struct Node));
if (Q = = NULL)
printf ("Out of Space");

ww MakeEmpty (Q);
return Q;
}
w.E
void MakeEmpty (Queue Q)
{ asy
if (Q = = NULL)
En
else gi
printf ("Create Queue First");

while (! IsEmpty (Q) nee


Dequeue (Q);
rin
}
g.n
ROUTINE TO ENQUEUE AN ELEMENT IN QUEUE
void Enqueue (int X)
{
e t
Struct node *newnode;
newnode = malloc (sizeof (Struct node));
if (Rear = = NULL)
{
newnode →data = X;
newnode →Next = NULL;
Front = newnode;
Rear = newnode;

91

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
else
{
newnode → data = X;
newnode → Next = NULL;
Rear →next = newnode;
Rear = newnode;
}
}

ww
ROUTINE TO DEQUEUE AN ELEMENT FROM THE QUEUE

w.E
void Dequeue ( )
{

asy
Struct node *temp;

En
if (Front = = NULL)

else
{
gi
printf("Queue is underflow");

nee
temp = Front;
rin
if (Front = = Rear)
g.n
{
Front = NULL;
Rear = NULL;
e t
}
else
Front = Front →Next;
printf("%d\n",temp→data);
free (temp);
}
}

92

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ADDITION OF TWO POLYNOMIALS

5. Write a C++ code to perform addition of two polynomials using link list form of
queue. Nov/Dec 2014

#include <iostream.h>
class poly
{
private :

ww struct polynode
{

w.E float coeff ;


int exp ;
asy polynode *link ;

En
} *p ;
public :
poly( ) ; gi nee
void poly_append ( float c, int e ) ;
void display_poly( ) ; rin
void poly_add( poly &l1, poly &l2 ) ;
g.n
};
~poly( ) ;
e t
poly :: poly( )
{
p = NULL ;
}
void poly :: poly_append ( float c, int e )
{
polynode *temp = p ;
if ( temp == NULL )
{

93

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

temp = new polynode ;


p = temp ;
}
else
{
while ( temp -> link != NULL )
temp = temp -> link ;
temp -> link = new polynode ;
temp = temp -> link ;

ww }
temp -> coeff = c ;

w.E temp -> exp = e ;


temp -> link = NULL ;
} asy
En
void poly :: display_poly( )
{
gi
polynode *temp = p ;
int f = 0 ; nee
cout << endl ;
rin
while ( temp != NULL )
g.n
{
if ( f != 0 )
{
e t
if ( temp -> coeff > 0 )
cout << " + " ;
else
cout << " " ;
}
if ( temp -> exp != 0 )
cout << temp -> coeff << "x^" << temp -> exp ;
else

94

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

cout << temp -> coeff ;


temp = temp -> link ;
f=1;
}
}
void poly :: poly_add ( poly &l1, poly &l2 )
{
polynode *z ;
if ( l1.p == NULL && l2.p == NULL )

ww return ;
polynode *temp1, *temp2 ;

w.E temp1 = l1.p ;


temp2 = l2.p ;

asy
while ( temp1 != NULL && temp2 != NULL )
{
En
gi
if ( p == NULL )
{
nee
p = new polynode ;
z=p;
rin
}
g.n
else
{
z -> link = new polynode ;
e t
z = z -> link ;
}
if ( temp1 -> exp < temp2 -> exp )
{
z -> coeff = temp2 -> coeff ;
z -> exp = temp2 -> exp ;
temp2 = temp2 -> link ;
}

95

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

else
{
if ( temp1 -> exp > temp2 -> exp )
{
z -> coeff = temp1 -> coeff ;
z -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
else

ww {
if ( temp1 -> exp == temp2 -> exp )

w.E {
z -> coeff = temp1 -> coeff + temp2 -> coeff ;

asy z -> exp = temp1 -> exp ;

En temp1 = temp1 -> link ;

}
gi }
temp2 = temp2 -> link ;

nee
}
rin
}
g.n
while ( temp1 != NULL )
{
if ( p == NULL )
e t
{
p = new polynode ;
z=p;
}
else
{
z -> link = new polynode ;
z = z -> link ;

96

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
z -> coeff = temp1 -> coeff ;
z -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
while ( temp2 != NULL )
{
if ( p == NULL )
{

ww p = new polynode ;
z=p;

w.Eelse
}

asy
{

En z -> link = new polynode ;

} gi z = z -> link ;

nee
z -> coeff = temp2 -> coeff ;
z -> exp = temp2 -> exp ;
rin
temp2 = temp2 -> link ;
g.n
}
}
z -> link = NULL ; e t
poly :: ~poly( )
{
polynode *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q;

97

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
}
void main( )
{
poly p1 ;
p1.poly_append ( 1.4, 5 ) ;
p1.poly_append ( 1.5, 4 ) ;
p1.poly_append ( 1.7, 2 ) ;
p1.poly_append ( 1.8, 1 ) ;

ww p1.poly_append ( 1.9, 0 ) ;
cout << "\nFirst polynomial:" ;

w.E
p1.display_poly( ) ;
poly p2 ;

asy
p2.poly_append ( 1.5, 6 ) ;

En
p2.poly_append ( 2.5, 5 ) ;

gi
p2.poly_append ( -3.5, 4 ) ;
p2.poly_append ( 4.5, 3 ) ;
p2.poly_append ( 6.5, 1 ) ; nee
cout << "\nSecond polynomial:" ;
rin
p2.display_poly( ) ;
g.n
poly p3 ;
p3.poly_add ( p1, p2 ) ;
cout << "\nResultant polynomial: " ;
e t
p3.display_poly( ) ;
}

98

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

PART - C
SUM OF ODD NUMBERS USING SINGLY LINKED LIST

6. Write a C++ program to sum up all odd numbers using singly linked list.
Nov/Dec 2014
#include<iostream.h>
#include<conio.h>
class sll
{

ww public:
struct node

w.E {

asy int data;


struct node *next;

En
}*temp,*first,*nnode;
sll()
{ gi nee
first=NULL;
} rin
void create(int);
g.n
void addodd();
void display(); e t
};
//function for creating a sll
void sll::create(int element)
{
nnode=newnode;
nnode->data=element;
nnode->next= NULL;
if(first== NULL)
{

99

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

first=nnode;
temp=nnode;
}
else
{
temp->next=nnode;
temp=nnode;
}
}

ww
void sll::addodd()
{

w.E
int sum=0,odd,res;
temp=first;

asy
while(temp!= NULL)
{
En
gi
res=(temp->data)%2;
if(res!=0)
{ nee
add=temp->data;
rin
sum+=odd;
g.n
}
}
temp=temp->next; e t
cout<<”displaying elements”<<display();
cout<<”result “<<sum;
}
//func tion that display the elements of the singly linked list
void sll::display()
{
temp=first;
while(temp!= NULL)

100

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
cout<<temp->data;
temp=temp->next
}
int main()
{
clrscr();
int ch,n,i,element1[10];
sll obj;

ww cout<<”addition of add n umbers in a singly linked list”;


while(1)

w.E {
cout<<”\n 1.create 2.addodd numbers 3.display 4.exit”;

asy cout<<”enter your choice”;

En
cin>>ch;
switch(ch)
{ gi
case 1: nee
rin
cout<<”enter the number of elements”;
cin>>n;
g.n
cout<<”enter the elements”;
for(i=0;i<n;i++)
{
e t
cin>>element1[i];
obj.create(element1[i]);
}
break;
case 2:
cout<<”\n adding odd numbers”;
obj.addodd();
break;

101

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

case 3:
cout<<”\n displaying elements in list”;
obj.display();
break;
case 4:
cout<<”\n program ends”;
exit(0);
}}}

ww POLYNOMIAL MANIPULATION

w.E
7. Write a C++ program to perform addition, subtraction and multiplication

asy
operations on polynomial using linked list.

En
Polynomials is represented as a list of pairs of coefficient and exponent. Each of these

gi
pairs will constitute a structure, so a polynomial will be represented as a list of structures. A

nee
linked list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 + 9x0 illustrates in
figure 3.10.1
rin
g.n
e t
Fig. 3.3.1 Linked list representation of polynomial
Declaration of Linked list implementation of Polynomial:

struct poly{
{
int coeff;
int power;
struct poly *next;

102

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

} *list1, *list2, *list3;

Creation of Polynomial:
poly create(poly *head, poly *newnode)
{
poly*ptr;
if(head==NULL)
{
head=newnode;
return(head);

ww }
else
{ w.E
ptr=head;
asy
En
while(ptr-> next!=NULL)
ptr=ptr->next;

}
ptr->next=newnode;
gi nee
return(head);
rin
}
g.n
Addition of Polynomials:
To add two polynomials we need to scan them once. If we find terms with the same
e t
exponent in the two polynomials, then we add the coefficients; otherwise, we copy the term
of larger exponent into the sum and go on. When we reach at the end of one of the
polynomial, then remaining part of the other is copied into the sum.
To add two polynomials follow the following steps:
• Read two polynomials.
• Add them.
• Display the resultant polynomial.
Addition of Polynomials:
void add()
{

103

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

poly *ptr1, *ptr2, *newnode;


ptr1=list1;
ptr2=list2;
while(ptr1!=NULL && ptr2!= NULL)
{
newnode=malloc(sizeof(struct poly));
if(ptr1->power==ptr2->power)
{
newnode->coeff = ptr1->coeff + ptr2->coeff;
newnode->power=ptr1->power;
newnode->next=NULL;

ww list3=create(list3,newnode);
ptr1=ptr->next;

}
w.E
ptr2=ptr2->next;

else asy
{
En
{ gi
if(ptr1->power > ptr2->power)

nee
newnode->coeff = ptr1->coeff
newnode->power=ptr1->power; rin
newnode->next=NULL;
g.n
list3=create(list3,newnode);
ptr1=ptr1->next; e t
}
else
{
newnode->coeff = ptr2->coeff
newnode->power=ptr2->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr2=ptr2->next;
}}}

104

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

FOR SUBTRACTION OF POLYNOMIALS , add this statement in the above program


newnode->coeff = ptr1->coeff - ptr2->coeff
MULTIPLICATION OF POLYNOMIALS:
Multiplication of two polynomials however requires manipulation of each node such that
the exponents are added up and the coefficients are multiplied. After each term of first
polynomial is operated upon with each term of the second polynomial, then the result has to
be added up by comparing the exponents and adding the coefficients for similar exponents
and including terms as such with dissimilar exponents in the result
void Mul()

ww {

w.E
poly *ptr1, *ptr2, *newnode;
ptr1=list1;
ptr2=list2;
asy
if(ptr1 == NULL && ptr2 == NULL)
return;
En
list3 = list2;
gi
if(ptr1 == NULL) // I polynomial does not exist

nee
elsif(ptr2 ==NULL) // II polynomial does not exist
list3 =list1; rin
else // Both polynomial exist g.n
{
if(ptr1!=NULL && ptr2!= NULL)
e t
{
while(ptr1!=NULL)
{ newnode=malloc(sizeof(struct poly));
while(ptr2!=NULL)
{
newnode->coeff = ptr1->coeff * ptr2 ->coeff;
newnode->power=ptr1->power + ptr2->power;
list3=create(list3,newnode);
ptr2=ptr2->next;
105

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

} ptr2=list2;
ptr1=ptr1->next; } }}}

ww
w.E
asy
En
gi nee
rin
g.n
e t

106

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT IV

NON-LINEAR DATA STRUCTURES

Trees – Binary Trees – Binary tree representation and traversals – Application of


trees: Set representation and Union-Find operations – Graph and its representations –
Graph Traversals – Representation of Graphs – Breadth-first search – Depth-first
search – Connected components.

ww PART A

w.E
1. What is tree? April/May 2015
A tree is a nonlinear data structure. It is mainly used to represent data containing a

asy
hierarchical relationship between elements. Example: records, family trees and tables of

En
contents. A tree is a finite set of one or more nodes such that there is a specially designated

gi
node called the Root, and zero or more non empty sub trees T1, T2....Tk, each of whose roots
are connected by a directed edge from Root R.
nee
2. How a graph is represented?
rin April/May 2015

g.n
A graph G = (V, E) consists of a set of vertices, V, and set of edges E. Each edge is

are referred to as Edges. The graph is represented as e


a pair (v, w) where v, w εV. Vertices are referred to as nodes and the arc between the nodes

107

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3. Find the maximum number of nodes in complete binary tree if d is the depth.
(Nov/Dec 2014)
The maximum number of nodes in a binary tree of depth d is 2d−1 ie)d >=1

4. Difference between full binary tree and complete binary tree.

A full binary tree is a tree in which all the leaves are on the same level and every
non-leaf node has exactly two children.
A complete binary tree is a tree in which every non-leaf node has exactly two

ww
children not necessarily to be on the same level.

w.E
5. Give the representation of network of cities (Chennai, Delhi, Kolkata and Mumbai)
as weighted graph. (Nov/Dec 2014)

asy
En
gi nee
rin
g.n
6. What is a binary tree?
e
Nov/Dec 2015
t
Binary search tree is a binary tree in which for every node X in the tree, the
values of all the keys in its left subtree are smaller than the key value in X, and the values of
all the keys in its right subtree are larger than the key value in X.
A binary tree is a tree in which no node can have more than two children.
Example

108

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

7. When a graph is said to be connected? Nov/Dec 2015


A complete graph is a graph in which there is an edge between every pair of vertices.
A complete graph with n vertices will have n (n - 1)/2 edges.

ww
w.E
asy
En
gi
The above graph contains 6 vertices and 15 edges.
nee
rin
8. What do you mean by level of the tree?
g.n
The root node is always considered at level zero, then its adjacent children are

e
supposed to be at level 1 and so on. Here, node A is at level 0, nodes B and C are at level 1
and nodes D and E are at level 2. t

9. Difference between strongly connected and weakly connected in a graph?

109

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

An undirected graph is connected, if there is a path from every vertex to every other
vertex. A directed graph with this property is called strongly connected.
When a directed graph is not strongly connected but the underlying graph is
connected, then the graph is said to be weakly connected.

10. Name the different ways of representing a graph.


a.Adjacencymatrix
b. Adjacency list

ww
11. Define biconnectivity.

w.E
A connected graph G is said to be biconnected, if it remains connected afterremoval of
any one vertex and the edges that are incident upon that vertex. A connectedgraph is

asy
biconnected, if it has no articulation points.

En
12. What do you mean by articulation point?

gi nee
If a graph is not biconnected, the vertices whose removal would disconnect the graph
are known as articulation points.

rin
13. What do you mean by tree edge?
g.n
e
If w is undiscovered at the time vw is explored, then vw is called a tree edge and v
becomes the parent of w. The root of the tree is A the first vertex visited. Each edge(v,w) in
t
the graph is present in the tree. When (v,w),find that w is unmarked or process(w,v), find
that v is unmarked it indicate with a tree edge.

14. What do you mean by back edge?

If w is the ancestor of v, then vw is called a back edge. When process (v,w), find that
w is aready marked and when processing(w,v), find that v is already marked. Then draw a
dashed line, it called as back edge to indicate that this edge is not really part of the tree.

110

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

15. How to perform union operation? Nov/Dec 2014

The union operation is a operation in which the elements from one set are combined
with a element of the another set.The repetition of element is avoided.

PART B

BINARY TREE TRAVERSAL

1. Discuss the different methods traversing a binary tree with algorithm.

ww April/May 2015
Tree traversal is a process of moving through a tree in a specified order to process

w.E
each of the nodes. Each of the nodes is processed only once (although it may be visited
more than once). Usually, the traversal process is used to print out the tree.

asy
There are three standard ways of traversing a binary tree T with root R.
➢ Preorder
En
➢ inorder
➢ postorder gi nee
Preorder: (also called Element-Left-Right Traversal)
1. Process the root R rin
2. Traverse the left sub tree of R in preorder
g.n
EXAMPLE
3. Traverse the right subtree of R in preorder
e t
Consider the binary tree T.
Observe that A is the root, that its left subtree consists of nodes B, D and E and that
its right sub tree consists of nodes C and F.
The preorder traversal of T processes A, traverses left subtree and traverses right
subtree. However, the pre order traversal of left subtree processes the root B and then D and
E, and the preorder traversal of right subtree processes the root C and then F. Hence
ABDECF is the preorder traversal of T.

111

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Routine
void preorder (Tree T)
{

ww if (T!= NULL) /* Base case, if t is null, do nothing */


{
w.E
printf(“%c”, T → Element); /* Print the value of the root */

asy
preorder (T → Left); /* Traverse the left sub tree in in-order */

}} En
preorder (T → Right); /* Traverse the right sub tree in in-order */

} gi
Inorder: (also called Left-Element-Right Traversal) nee
1. Traverse the left subtree of R in inorder.
rin
2. Process the root R
3. Traverse the right subtree of R in inorder. g.n
EXAMPLE
Consider the binary tree T.
e t
Observe that A is the root, that its left subtree consists of nodes B, D and E and that its right
sub tree consists of nodes C and F.
The inorder traversal of T traverses left subtree, processes A and traverses right
subtree. However, the in order traversal of left subtree processes D, B and then E, and the
inorder traversal of right subtree processes C and then F. Hence DBEACF is the inorder
traversal of T.

112

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ww
Routine
void inorder (Tree T)
{
w.E
if (T!= NULL) /* Base case, if p is null, do nothing */
{
asy
En
inorder (T→ Left); /* Traverse the left sub tree in in-order */

gi
printf(“%c”, T →Element);
inorder (T → Right);
}
/* Print the value of the root */

nee
/* Traverse the right sub tree in in-order */

}
rin
g.n
Postorder: (also called Left-Right-Node Traversal)

1. Traverse the left subtree of R in postorder.


e t
2. Traverse the right subtree of R in postorder.
3. Process the root R.

113

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EXAMPLE : Consider the binary tree T.

ww
w.E
Observe that A is the root, that its left subtree consists of nodes B, D and E and that
asy
its right sub tree consists of nodes C and F.The postorder traversal of T traverses left

En
subtree, traverses right subtree, and processes A. However, the postorder traversal of left

gi
subtree processes D, E and then B, and the postorder traversal of right subtree processes F

nee
and then C. Hence, DEBFCA is the postorder traversal of T.
Routine
void postorder (Tree T) rin
{
g.n
if (T!= NULL)
{
/* Base case, if p is null, do nothing */
e t
postorder (T → Left); /* Traverse the left sub tree in in-order */
postorder (T→ Right); /* Traverse the right sub tree in in-order */
printf(“%c”, T→ Element); /* Print the value of the root */

}
}

114

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Example:

ww
w.E
The preorder traversal of T is A B D E H C F G I K J.

asy
The Inorder traversal of T is D B H E A F C K I G J
The Postorder traversal is D H E B F K I J G C A.

En
gi
BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL

nee
2. Explain DFS and BFS with suitable example.
(or) rin
Nov/Dec 2014, Nov/Dec 2015

Illustrate the Depth First Search algorithm with a graph. g.n


April/May 2015
GRAPH TRAVERSAL
e
A graph traversal is a systematic way of visiting the nodes in a specific order. There t
are two types namely,
1) Breadth first traversal
2) Depth first traversal
Breadth first traversal
Breadth first search (BFS) of a graph G starts from an unvisited vertex u. then all the
unvisited vertices vi adjacent to u are visited and then all unvisited vertices wj adjacent to vi
are visited and so on. The traversal terminates when there are no more nodes tp visit. BFS
uses a queue data structure to keep track of the order of nodes whose adjacent nodes are to
be visited.
115

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Steps to be implemented in BFS


Step 1: choose any node in the graph, designate it as search node and mark it as visited.
Step 2: using the adjacency matrix of the graph, find all the unvisited adjacent node to the
search node and enqueue them into the queue Q.
Step 3: Then the node is dequeued from the queue. Mark that node as visited and designate
it as new search node.
Step 4: Repeat step 2 and 3 using the new search node.
Step 5: This process continues until the queue Q which keeps track of the adjacent nodes is
empty.
A B

ww
Example:

w.E
Casy D

En
Adjacency matrix: gi nee
A B C D
rin
A 0 1 1 0
g.n
B
C
1
1
0
1
1
0
1
1 e t
D 0 1 1 0
Implementation

1. Let ‘A’ be the source vertex. Mark it to as visited.


2. Find the adjacent unvisited vertices of ‘A’ and enqueue then into the queue. Here B and
C are adjacent nodes of A
B C

116

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3. Then vertex ‘B’ is dequeued and its adjacent vertices C and D are taken from the
adjacency matrix for enqueuing. Since vertex C is already in the queue, vertex D alone is
enqueued. Here B is dequeued, D is enqueued.
C D
4. Then vertex ‘C’ is dequeued and its adjacent vertices A,B and D are found. Since vertices
A and B are already visited and vertex D is also in the queue, no enqueue operation takes
place. Here C is dequeued.
D

ww
5. Then vertex ‘D’ is dequeued. This process terminates as all the vertices are visited and
the queue is empty.

w.E
Example: asy A

En B
C

D
gi nee
Figure: Breadth first Spanning tree rin
Routine for Breadth first search:
g.n
Void BFS(vertex u)
{ e t
Initialize queue Q;
Visited[u]=1;
Enqueue(u,Q);
While(!Isempty(Q))
{
U=Dequeue(Q);
Print u;
For all vertices v adjacent to u do
If(visited[v]==0) then

117

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
Enqueue(v,Q)
Visited[v]=1;}}}
Depth first search
Depth first works by selecting one vertex V of G as a start vertex ; V is marked
visited. Then each unvisited vertex adjacent to V is searched in turn using depth first search
recursively. This process continues until a dead end (i.e.) a vertex with no adjacent
unvisited vertices is encountered. At a dead end, the algorithm backs up one edge to the
vertex it came from and tries to continue visiting unvisited vertices from there.The

ww
algorithm eventually halts after backing up to the starting vertex, with the latter being a
dead end. By then, all the vertices in the same connected component as the starting vertex

w.E
have been visited. If unvisited vertices still remain, the depth first search must be restarted
at any one of them.

asy
Routine for depth first search:
Void DFS(Vertex V)
En
{
Visited[V]=True; gi
For each W adjacent to V nee
If(!visited[W]
rin
DFS(W);
g.n
}
To implement the Depth first Search performs the following Steps: e
Step 1: Choose any node in the graph. Designate it as the search node and mark it as
t
visited. Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search
node that has not been visited yet. Designate this as the new search node and mark it as
visited.
Step 3: Repeat step 2 using the new search node. If no nodes satisfying (2) can be found,
return to the previous search node and continue from there.
Step 4: When a return to the previous search node in (3) is impossible, the search from the
originally choosen search node is complete.

118

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Step 5: If the graph still contains unvisited nodes, choose any node that has not been visited
and repeat step (1) through (4).
Example:
A B

C D

ww
Adjacency matrix
A B C D

w.E A
B
0
1
1
0
1
0
1
1
C asy 1 0 0 1
D
En1 1 1 0

Implementation gi nee
1. Let `A' be the source vertex. Mark it to be visited.

rin
2. Find the immediate adjacent unvisited vertex `B' of `A' Mark it to be visited.
3. From `B' the next adjacent vertex is `d' Mark it has visited.
g.n
4. From `D' the next unvisited vertex is `C' Mark it to be visited.
A e t
B

Applications of Depth First Search


1. To check whether the undirected graph is connected or not.
2. To check whether the connected undirected graph is Bioconnected or not.
3. To check the Acyclicity of the directed graph.

119

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNDIRECTED GRAPHS
A undirected graph is `connected' if and only if a depth first search starting from any node
visits every node.
A
Example:

B D E

ww
Adjacency matrix
A B C D E
A
B
w.E 0
1
1
0
0
1
1
1
1
0
C 0 asy 1 0 1 1
D 1
En 1 1 0 0
E 1
gi
0 1

nee
0 0

Implementation

rin
We start at vertex `A'. Then Mark A as visited and call DFS (B) recursively, Dfs (B) Marks
B as visited and calls Dfs(c) recursively.
A g.n
e t
B

Dfs (c) marks C as visited and calls Dfs (D) recursively. No recursive calls are made
to Dfs (B) since B is already visited. A

120
C

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Dfs(D) marks D as visited. Dfs(D) sees A,B,C as marked so no recursive call is made there,
and Dfs(D) returns back to Dfs(C). A

ww D

w.E
asy
En
Dfs(C) calls Dfs(E), where E is unseen adjacent vertex to C.

gi nee
A

B rin
g.n
C e t
D
E

Since all the vertices starting from ‘A’ are visited, so the above graph is said to be visited.

121

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

IMPLEMENTATION OF TREE TRAVERSALS

3. Write C++ code for the implementation of different types of tree traversals. State
few tree applications. Nov/Dec 2014
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct btree
{

ww struct btree *left;


struct btree *right;

};
int no;
w.E
asy
void postorder(struct btree *trav);
void inorder(struct btree *trav);
En
void preorder(struct btree *trav);
gi
struct btree * create(struct btree *trav);
nee
void main()
{ rin
struct btree *root=NULL;
g.n
char c;
clrscr(); e t
while(1)
{
root=create(root);
cout<<"Do you want to continue : ";
cin>>c;
if(c=='n' ||c=='N')
break;
}
cout<<endl<<"Inoder is : ";inorder(root);

122

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

cout<<endl<<"Preorder is : ";preorder(root);
cout<<endl<<"Postorder is : ";postorder(root);
getch();
}
struct btree * create(struct btree *trav)
{
if(trav==NULL)
{
trav=new btree;

ww trav->right=NULL;
trav->left=NULL;

w.E
cout<<"Enter the no : ";
cin>>trav->no;
return(trav); asy
}
En
char choice;
gi
cout<<"Enter the left or right child : ";
cin>>choice; nee
if(choice == 'r' || choice == 'R')
rin
{
g.n
}
trav->right=create(trav->right);

if(choice=='l' || choice=='L')
e t
{
trav->left=create(trav->left);
}
return(trav);
}
void inorder(struct btree *trav)
{
if(trav==NULL)

123

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return ;
inorder(trav->left);
cout<<" "<<trav->no;
inorder(trav->right);
}
void preorder(struct btree *trav)
{
if(trav==NULL)
return;

ww cout<<" "<<trav->no;
preorder(trav->left);

}
w.E
preorder(trav->right);

asy
void postorder(struct btree *trav)
{
En
if(trav==NULL)
return;
postorder(trav->left);
gi nee
postorder(trav->right);
rin
cout<<" "<<trav->no;
g.n
}
Tree Applications:
• Binary search tree
e t
• AVL tree, Decision tree
• Splay trees etc.

124

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EXPRESSION TREE CONSTRUCTION

4.(i) How can you construct an expression tree? Describe your answer with an
example. Nov/Dec 2015

Expression Tree is a binary tree in which the leaf nodes are operands and the interior
nodes are operators. Like binary tree, expression tree can also be travesed by inorder,
preorder and postorder traversal.
Example

ww
Constructing an Expression Tree

w.E
This algorithm is used to construct the expression tree from the given infix
expression.
asy
1. Convert the infix expression to postfix expression.
2. Create an Empty stack.
En
4. If the symbol is an operand gi
3. Read one symbol at a time from the postfix expression.

nee
i) create a one – node tree
ii) Push the tree pointer on to the stack. rin
5. If the symbol is an operator
g.n
i)
ii)
pop two pointers from the stack namely T1 and T2
e
Form a new tree with root as the operator and T2 as a left child and T1 t
as a right child.
iii) A pointer to this new tree is then pushed onto the stack.
6. Repeat steps 3 to 5 until the end of input is reached
Example : -
Consider an example, suppose the input is (a + b ) * c * (d + e )
First we have to convert it into Postfix Expression. The Postfix Expression as a b + c d e + *
*
The first two symbols are operands, so we create one-node trees and push pointers to them
onto a stack.*

125

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Next `+’ symbol is read, so two pointers are popped, a new tree is formed and a pointer to
this is pushed on to the stack.

ww
w.E
asy
En
gi nee
rin
g.n
Next, c, d, and e are read, and for each a one-node tree is created and a pointer to the
corresponding tree is pushed onto the stack.

e t

126

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ww
w.E
asy
En
gi nee
rin
g.n
e t

127

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Now a ‘+’ is read, so two trees are merged.

ww
Next ‘*’ is read, so we pop two tree pointers and form a new tree with a ‘*’ as root.

w.E
asy
En
gi nee
rin
g.n
Finally, the last symbol ‘*’ is read, two trees are merged, and a pointer to the final tree is
left on the stack.
e t

128

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

SET REPRESENTATION

4 (ii) Discuss how sets are represented. (4) Nov/Dec 2015

A disjoint set data structure maintains a collection S={ S1 , S2 ,…, Sk } of


disjoint dynamic sets. Each set is identified by a representative, which usually is a member
in the set.
Operations on Sets

ww
Let x be an object. We wish to support the following operations.
• MAKE-SET( x) creates a new set whose only member is pointed by x; Note that x is
w.E
not in the other sets.

asy
UNION( x,y) unites two dynamic sets containing objects x and y, say Sx and Sy ,
into a new set that Sx ∪ Sy , assuming that Sx ∩ Sy =∅;

En
FIND-SET( x) returns a pointer to the representative of the set containing x.


gi
INSERT( a,S) inserts an object a to S, and returns S∪{a}.

nee
DELETE( a,S) deletes an object a from S, and returns S-{a}.

rin
SPLIT( a,S) partitions the objects of S into two sets S1 and S2 such that
S1 ={b | b≤a & b∈S}, and S2 =S- S1 .
• MINIMUM( S) returns the minimum object in S. g.n
The Disjoint Set Representation
e t
The Linked-list Representation

A set can be represented by a linked list. In this representation, each node has a
pointer to the next node and a pointer to the first node.

129

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Figure 2: Linked-list representation


Example: Disjoint set
Elements:1,2,3,4,5,6,7
Union(1,2)

ww
Represented as {1,2}

w.E
asy
En
Union(2,3)
gi nee
Represented as {1,2,3}
rin
g.n
e t
Union(4,5)
Represented as {4,5}

130

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Union(6,7)
Represented as {6,7}

Union(5,6)
Represented as {4,5,6,7}

ww
w.E
asy
Union(3,7)
En
Represented as {4,5,6,7,1,2,3}
gi nee
rin
g.n
UNION FIND OPERATIONS
e t
5. Explain union-find operations. (4) Nov/Dec 2015

A union-find data structure that keeps track of a set of elements partitioned into a
number of disjoint (non-overlapping) subsets. A Disjoint-set is an algorithm that performs
two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if
two elements are in the same subset.

131

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Union: Join two subsets into a single subset.


The application is to check whether a given graph contains a cycle or not.Union-Find
Algorithm can be used to check whether an undirected graph contains cycle or not.
Path compression: The effect of path compression is that every node on the path from x to
the root has its parent changed to the root.
Example 1: Slow UNION-FIND
int FIND( int x )
{
if( uf[x] == x ) return x; // x is the leader

ww
}
return FIND( uf[x] );

w.E
void UNION( int x, int y )
{

asy
uf[FIND( x )] = FIND( y );
}
En
gi
FIND() simply follows the uf[] links up until it reaches the leader and returns. UNION

nee
points x's leader to y's leader, effectively merging the two trees. From now on, calling
FIND(z) on any member of x's party will return the leader of y's party, as desired. The

rin
choice of leader for the new, merged party is unimportant; we could switch x and y and get
an equivalent result.
g.n
Example 2: FIND with path compression
int FIND( int x )
{
e t
if( uf[x] != uf[uf[x]] ) uf[x] = FIND( uf[x] );
return uf[x];
}
The first line checks whether the path from x to the leader has length at least 2. If it does,
then we
reset uf[x] to point to the leader (otherwise, it's already pointing to the leader). Finally, we
simply
return uf[x].

132

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Example:1 2 3 4 5 6 7 are the elements


Step1:

ww
Node with the highest rank be the parent.

Union(1,2)
w.E union(2,3) union(4,5)

asy
En
gi nee
rin
g.n
e t
union(6,7) union(5,6)

133

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Make path comperession( make 7 to point directly to 4)

ww
union(3,7)
w.E
asy
En
gi nee
rin
g.n
After path compression(2 and 3 directly connected with 4) e t

134

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

PART - C
MINIMUM SPANNING TREE
6. Discuss about Minimum spanning tree

Spanning Tree Definition: Consider a connected, undirected graph G=(V,E). A spanning


tree of G is a subgraph of G, say T =(V’,E’), with the following properties:
1. V’ = V ( that is the spanning tree contains all the vertices of the graph )
2. T is connected.
3. T is acyclic.

ww A minimum spanning tree of a weighted connected graph G is its spanning tree of


the smallest weight, where the weight of a tree is defined as the sum of the weights on all its

w.E
edges. Minimum Spanning tree
2

a asy b

5 En 3

c
gi 1
nee d
1

2
rin
2
g.n
a b
e t
1

c d Cost = 5

2 2
a b
1
Cost = 5

c d
2

135

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Example
Undirected Graph
Spanning Tree

ww
Prim's Algorithm
Prim's algorithm is used compute a minimum spanning tree. It uses a greedy

w.E
technique. This algorithm begins with a set U initialized to {1}. It this grows a spanning

asy
tree, one edge at a time. At each step, it finds a shortest edge (u,v) such that the cost of (u,
v) is the smallest among all edges, where u is in Minimum Spanning Tree and V is not in
Minimum Spanning Tree.
En
void Prims (Table T)
{ gi nee
vertex V, W;
/* Table initialization */ rin
for (i = 0; i < Numvertex ; i++)
g.n
{
T[i]. known = False; e t
T[i]. Dist = Infinity;
T[i]. path = 0;
}
for (; ;)
{
Let V be the start vertex with the smallest distance
T[V]. dist = 0;
T[V]. known = True;
for each W adjacent to V

136

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

If (! T[W] . Known)
{
T[W].Dist = Min(T[W]. Dist, CVW);
T[W].path = V;
}
}
}
Kruskal's algorithm

ww Kruskal's algorithm is a minimum-spanning-tree algorithm where the algorithm


finds an edge of the least possible weight that connects any two trees in the forest.It is a

w.E
greedy algorithm in graph theory as it finds a minimum spanning tree for a connected
weighted graph adding increasing cost arcs at each step.

asy
Void kruskal(Graph G)
En
{
Int EdgesAccepted;
Disjset S;
gi nee
PriorityQueue H;
rin
Vertex U,V;
g.n
SetType Uset,Vset;
Edge E;
Initialize(s);
e t
ReadGraphIntoHeapArray(G,H);
BuildHeap(H);
EdgesAccepted=0;
While(EdgesAccepted < NumVertex-1)
{
E=DeleteMin(H);
Uset=Find(U,S);
Visit=find(V,S);

137

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

If(Uset != Vest){
EdgesAccepted++;
SetUnion(S,Uset,Vset);
}}}
CONNECTED COMPONENTS

7. Explain in detail about connected components.


A connected undirected graph is biconnected if there are no vertices whose removal
disconnects the rest of the graph.Articulation point:If a graph is not biconnected the vertices

ww
whose removal would disconnect the graph are known as articulation points.

B
w.E A

asy
C
En D F

gi nee
G
rin
E

g.n
Figure shows A graph with articulation points C and D.If a graph is not biconnected, the
vertices whose removal would disconnect the graph are known as articulation points.
e
These nodes are critical in many applications. The graph in Figure 9.64 is not biconnected: t
C and D are articulation points. The removal of C would disconnect G, and the removal of
D would disconnect E and F, from the rest of the graph.The figure is not biconnected : C
and D are articulation points.

B A Fig(1) B A Fig(2)

D F C F

E
G E
138 G

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Fig 1: The removal of C would disconnect G.


Fig 2: The removal of D would disconnect E and F
Depth-first search provides a linear-time algorithm to find all articulation points in a
connected graph.

ww
w.E
asy
1.Starting at any vertex, we perform a depth-first search and number the nodes as they are

En
visited. For each vertex, v, we call this preorder number Num(v).

gi
2. compute the lowest numbered vertex, which we call Low(v), that is reachable from v by

nee
taking zero or more tree edges and then possibly one back edge (in that order).
By the definition of Low, Low(v) is the minimum of
1. Num(v) rin
2. the lowest Num(w) among all back edges (v, w)
g.n
3. the lowest Low(w) among all tree edges (v, w)
The first condition is the option of taking no edges e t
the second way is to choose no tree edges and a back edge
the third way is to choose some tree edges and possibly a back edge
It is easy to compute Low(v)
• The root is an articulation point if and only if it has more than one child, because if it has
two children, removing the root disconnects nodes in different subtrees, and if it has only
one child,removing the root merely disconnects the root.
Any other vertex v is an articulation point if and only if v has some child w such that
Low(w) ≥ Num(v). The time taken to compute this aglorithm O(|E| + |V|) .
Routine to assign Num to vertices (pseudocode)

139

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

void Graph::assignNum( Vertex v )


{
v.num = counter++;
v.visited = true;
for each Vertex w adjacent to v
if( !w.visited )
{
w.parent = v;
assignNum( w );

ww
}
}

w.E
Pseudocode to compute Low and to test for articulation points
(test for the root is omitted)

asy
void Graph::assignLow( Vertex v )
{
En
v.low = v.num; // Rule 1
gi
for each Vertex w adjacent to v
{ nee
if( w.num > v.num ) // Forward edge
rin
{
g.n
assignLow( w );
if( w.low >= v.num ) e
cout << v << " is an articulation point" << endl;
t
v.low = min( v.low, w.low ); // Rule 3
}
else
if( v.parent != w ) // Back edge
v.low = min( v.low, w.num ); // Rule 2
}
}

140

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

UNIT-V

SORTING, SEARCHING

Sorting algorithms: Insertion sort – Quick sort – Merge sort – Searching: Linear
search –Binary Search

PART A

1. State why quick sort is more efficient than merge sort.

ww Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime.
However, it’s superior to merge sort in many scenarios because many factors influence an

w.E
algorithm’s runtime. In particular, the often-quoted runtime of sorting algorithms refers to
the number of comparisons or the number of swaps necessary to perform to sort the data.

asy
Quicksort in particular requires little additional space and exhibits good cache locality, and

En
this makes it faster than merge sort in many cases.

gi
2. Explain the principle used in quick sort.
nee
rin
It is a partition method using the particular key the given array is partitioned

g.n
into 2 subarrays so that first, the original key will be in proper position in the sorted
sequence and secondly all the keys to the left of this pivot will be less in value and all keys
to the right of it will be greater in value.
e t
3. How many passes does the insertion sort algorithm do to sort a list of 5 elements?
What happens in its ith pass?

Number of passes: Total number of elements =5. So insertion sort requires 4 passes.
ith pass: in ith pass of insertion sort will insert ithelement A[i] into its right place among
A[i],A[2]….A[i-1] elements.

141

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. Determine the average running time of quick sort.


Best case: Input array is evenly divided.So the running time complexity is O(n log n)
Worst case: Input array is not evenly divided.So the running time complexity is O(n2).
Average Case: running time complexity is O(n log n).

5. What are the various factors to be considered in deciding a sorting algorithm?


✓ Programming time
✓ Execution time of the program.
✓ Memory needed for program environment.

ww
6. Mention the time complexity of merge sort

w.E
Merge sort algorithm passes over the entire list and requires atmost log n

asy
passes and merges n elements in each pass. The total number of comparisons required by

En
the merge sort is given by O(nlogn).

gi
7. Define Efficiency, worst case, best case and average class of an algorithm?

nee
Efficiency: It denotes the rate at which an algorithm solves a problem of size n. It is
measured by the amount of resources it uses, the time and the space.
rin
g.n
Worst case: It is the longest time that an algorithm will use over all instances of size n for a
given problem to produce the result.
Best case e
It is the shortest time that an algorithm will use over all instances of size n for
t
a given problem to produce the result.
Average case
It is the average time that an algorithm will use over all instances of size n for
a given problem to produce the result.

8. What is searching?
Searching is used to find the position of a given number (or) any value in the
given list. If element is not found search is unsuccessful.

142

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

9. What is sorting? April/May2015

Sorting is the process of arranging the given items in a logical order. Sorting is
an example where the analysis can be precisely performed.

10. What is time complexity? April/May2015

It is the analysis of the amount of memory and time an algorithm requires to


completion.There are two types of Complexity Space Complexity and Time Complexity

ww
Time complexity is the amount of computer time an algorithm requires to run to
completion.

w.E
11. What is insertion sort?

asy
En
The main idea of insertion sort is to consider each element at a time, into the

gi
appropriate position relative to the sequence of previously ordered elements, such that the
resulting sequence is also ordered
nee
rin
12. How many passes does the insertion sort algorithm do to sort a list of 5 elements?
What happens in its ith pass?
g.n
Number of e
passes: Total number of elements =5 So insertion sort requires 4
t
passes.Ith pass: in ith pass of insertion sort will insert ith element A[i] into its right place
among A[i],A[2]….A[i-1] elements.

13. What is the time complexity of quick sort and binary search? Nov/Dec 2014

• The worst-case and average-case time complexity for binary search is O(log n). The best-
case is O(1).
• The worst-case time complexity is O(n2). The average-case (typical) and best-case is O(n
log n)

143

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

14. How an array element is sorted using merge sort? Nov/Dec 2015

Merge sort is based on divide and conquer strategy the problem is divided into
smaller problems and solved recursively.Finally it merges to sorted list.

15. With an example compute the number of comparisions ,required to search an


element using binary search. Nov/Dec 2015

Example:

ww
0
-40 11
1 2
33
3
37 42
4
45
5
99
6
100
7

w.E
Find the middle element of the array.Compare it with the key.The element to be

asy
searched is 99. i.e Key=99 divide the list into two sublists.
Sublist1
En
-40
gi 11 33

nee
37

Middle element is 42
Sublist2 rin
45 99 100
g.n
So the match is found at 7th position of array i.e array[6].Thus we can find the
element 99 present in the given list at array [6]th location. e t

144

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

PART-B

QUICK SORT

1. Write routines for quick sort and explain in detail. Nov/Dec 2014,2015
Or
Illustrate the quick sort working to sort the list {88,11,22,44,66,99,32,67,54,10}
[April/May 2015]

A sorting technique that sequences a list by continuously dividing the list into two
parts andmoving the lower items to one side and the higher items to the other. It starts by

ww
picking one item in the entire list to serve as a pivot point.The pivot could be the first item
or a randomly chosen one. All items that compare lower than the pivot are moved to the left

w.E
of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left
side and moves those items to left and right of the pivot and continues the pivot picking and
asy
dividing until there is only one item left in the group. It then proceeds to the right side and

En
performs the same operation again. Also known as Partition Exchange Sort.

gi
Quick sort algorithm applies a special designing technique called Divide and

nee
Conquer, The divide-and-conquer strategy solves a problem by:
1. Breaking it into sub problems that are themselves smaller instances of the same type of
problem rin
2. Recursively solving these sub problems
g.n
3. Appropriately combining their answers
e t
Divide and Conquer in Quick sort
1) Divide: If the sequence S has 2 or more elements, select an element x from S to be your
pivot.
Any arbitrary element, like the last, will do. Remove all the elements of S and divide
them into 3 sequences:
L, holds S’s elements less than x
E, holds S’s elements equal to x
G, holds S’s elements greater than x
2) Recurse: Recursively sort L and G

145

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3) Conquer: Finally, to put elements back into S in order, first inserts the elements of L,
then those of E, and those of G.
88 11 22 44 66 99 32 67 54 10
Given the input the array has to be sorted using quick sort

Steps:
1. Increment i till the element in the position is greater than pivot
88 11 22 44 66 99 32 67 54 10
Pivot i=1 i=2 i=3 i=4 i=5
11<88 22<88 44<88 66<88 99>88

ww
2. Decrement j till the element in j position is less than pivot
88
Pivot
11
w.E
22
i=1 i=2
44
i=3
66 99
i=4
32
i=5
67 54 10
j=9

asy 10<88

3.
En
Swap elements in i and j position
88
Pivot
11 22
i=1 i=2
44 66
i=3 gi i=4
10
i=5
32

nee
67 54 99
j=9

4. Increment i till the element in the position is greater than pivot


rin
88
Pivot
11
i=1
22
i=2
44
i=3
66 10
i=4
32
i=5
67
i=6
54
i=7 i=8 g.n 99
j=9,i=9
32<88 67<88 54<88
e 99>88
t
5. Decrement j till the element in j position is less than pivot
88 11 22 44 66 10 32 67 54 99
Pivot j=8 j=9, i=10
54<88 99>88

6. As i>j swap pivot element and element in j position


54 11 22 44 66 10 32 67 88 99
Pivot j=8 i=10

146

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

7. Now 88 is placed in its position and the same procedure is continued in the left and right
sublists of 88.
Left sublist of 88

8. Increment i till the element in the position is greater than pivot


54 11 22 44 66 10 32 67
Pivot i=1 i=2 i=3 i=4
11<54 22<54 44<54 66>54

9. Decrement j till the element in j position is less than pivot


54 11 22 44 66 10 32 67
Pivot i=1 i=2 i=3 i=4 j=6 j=7

ww 11<54 22<54 44<54 66>54 32<54 67>54

54 w.E
10. As i < j swap elements in the i and j position
11 22 44 32 10 66 67
Pivot i=1 i=2
asy i=3 i=4 j=6 j=7

En
11. Increment i till the element in the position is greater than pivot
54
Pivot
11 22
gi44 32
i=4
32<54 nee
10
i=5
10<54
66
i=6,j=6
66>54
67

rin
12. Decrement j till the element in j position is less than pivot
54 11 22 44 32 10 66 g.n 67
Pivot j=5
10<54
i=6,j=6
66>54
e t
13. As i>j swap pivot element and element in j position
10 11 22 44 32 54 66 67
Pivot j=5 i=6

14. Left sublist of 54


10 11 22 44 32

Pivot

15. As 10 is in its position the right sublist of 10 is chosen

147

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

44 32
Pivot i=4
j=4
32<44
11 22 44 32
Pivot

16. As 11 is in its position the right sublist of 11 is chosen


22 44 32

ww
17. As 22 is in its position the right sublist of 22 is chosen
44
Pivot w.E 32
i=4

asy 32<44

En
18. i cannot be incremented as there are no further elements in the sublist.

gi
19. As i=j, swap pivot and element in j position
nee
32 44
rin
Finally the sorted list is as follows: g.n
10 11 22 32 44 54 66 67 88 99
e t
Code:
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int left, int right);
int main()
{
int arr[30];
int i,n;
printf("Enter total no. of the elements : ");
148

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

scanf("%d",&n);
printf("Enter total %d elements : \n",size);
for(i=0; i<n; i++)
scanf("%d",&arr[i]);
qsort(arr,0,n-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<n; i++)
printf("%d\t",arr[i]);
getch();

ww
}
return 0;

w.E
void qsort(int arr[20], int left, int right)
{
int i,j,pivot,tmp; asy
if(left<right)
En
{
pivot=left;
i=left+1;
gi nee
j=right;
rin
while(i<j)
g.n
{
while(arr[i]<=arr[pivot] && i<right)
i++;
e t
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}

149

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
qsort(arr,left,j-1);
qsort(arr,j+1,right);
}
}
INSERTION SORT

ww
2. Explain Insertion sort algorithm and Illustrate its working to perform the list

w.E
{35,12,14,9,15,45,32,95,40,5}

The insertion sort, although still O(n2), works in a slightly different way. It always

asy
maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted”

En
back into the previous sublist such that the sorted sublist is one item larger. The shaded

Routine gi
items represent the ordered sublists as the algorithm makes each pass.

void insertionsort(int a[],int n) nee


{
rin
int j,t;
g.n
for(int i=1;i<n;i++)
{
t=a[i];
e t
for (int j=i; j>0 && t<a[j-1]; j--)
a[j]=a[j-1];
a[j]=t;
}
}
• It requires two steps:
1. Scan the sorted part to find the place where the element from unsorted part can be
inserted. While scanning shift the elements towards right to create space

150

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

2. Insert the element in the created space.


35 12 14 9 15 45 32 95 40 5
Given the input, the array has to be sorted using insertion sort
Steps:
1. Take 12 and check with the previous element and insert it in a sorted manner
12 35 14 9 15 45 32 95 40 5
2. Take 14 and place it in the correct position

12 14 35 9 15 45 32 95 40 5

ww
3. Take 9 and place it in the correct position
9 12
w.E
14 35 15 45 32 95 40 5

asy
4. Take 15 and place it in the correct position
9 12 14 15
En 35 45 32 95 40 5

gi
5. Take 45 and 32 & place it in the correct position
nee
9 12 14 15 32 35 45 95
rin 40 5

6. Take 95 and 40 & place it in the correct position


g.n
9 12 14 15 32 35 40 45 95
e 5
t
7. Remaining elements are in their position except 5. Take 5 & place it in the correct
position
5 9 12 14 15 32 35 40 45 95

Finally array is sorted.

151

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

LINEAR SEARCH ALGORITHM

3. Explain Linear Search algorithm.


Nov/Dec 2015,April/May 2015, Nov/Dec 2014
This algorithm has the benefit of simplicity; it is difficult to get wrong, unlike other more
sophisticated solutions. The above code follows the convention of this article, they are as
follows:
1. All search routines return a true/false boolean value for success or failure.
2. The list will be either an array of integers or a linked list of integers with a
key.

ww 3. The found item will be saved in a reference to a pointer for use in client code.
The algorithm itself is simple. A familiar 0 - n-1 loop to walk over every item in the

w.E
array, with a test to see if the current item in the list matches the search key. The loop can

asy
terminate in one of two ways. If i reaches the end of the list, the loop condition fails. If the
current item in the list matches the key, the loop is terminated early with a break statement.

En
Then the algorithm tests the index variable to see if it is less that size (thus the loop was

gi
terminated early and the item was found), or not (and the item was not found).

nee
In Linear Search the list is searched sequentially and the position is returned if the
key element to be searched is available in the list, otherwise -1 is returned. The search in

rin
Linear Search starts at the beginning of an array and move to the end, testing for a match at
each item.
g.n
e
All the elements preceding the search element are traversed before the search element is
traversed. i.e. if the element to be searched is in position 10, all elements form 1-9 are t
checked before 10.
Algorithm : Linear search implementation

bool linear_search ( int *list, int size, int key, int* rec )
{
// Basic Linear search
bool found = false;
int i;
for ( i = 0; i < size; i++ )

152

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
if ( key == list[i] )
break;
}
if ( i < size )
{
found = true;
rec = &list[i];
}

ww return found;
}

w.E
The code searches for the element through a loop starting form 0 to n. The loop can
terminate in one of two ways. If the index variable i reach the end of the list, the loop

asy
condition fails. If the current item in the list matches the key, the loop is terminated early

En
with a break statement. Then the algorithm tests the index variable to see if it is less than

was not found).


Example
gi
that size (thus the loop was terminated early and the item was found), or not (and the item

nee
rin
Assume the element 45 is searched from a sequence of sorted elements 12, 18, 25,

g.n
36, 45, 48, 50. The Linear search starts from the first element 12, since the value to be

e
searched is not 12 (value 45), the next element 18 is compared and is also not 45, by this
way all the elements before 45 are compared and when the index is 5, the element 45 is
compared with the search value and is equal, hence the element is found and the element
t
position is 5.

153

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

BINARY SEARCH

4. Explain Binary search routine. Nov/Dec 2015,2014

Consider a list in ascending sorted order. It would work to search from the beginning
until an item is found or the end is reached, but it makes more sense to remove as much of
the working data set as possible so that the item is found more quickly. If we started at the
middle of the list we could determine which half the item is in (because the list is sorted).
This effectively divides the working range in half with a single test. By repeating the
procedure, the result is a highly efficient search algorithm called binary search. the time

ww
complexity of binary search is O(log n).the Disadvantage of binary search is all the
elements should be in sorted form.
Routine
w.E
{ int m,e; asy
int binarysearch(int a[],int n)

int i=0,j=n-1;
En
cin>>e; gi
cout<<”enter the element to be searched”;

nee
while(i<=j)
{ rin
m=(i+j)/2;
g.n
if(a[m]==e)
return m; e t
else if (a[m]<e)
i=m+1;
else
j=m-1;}
A dichotomizing search in which the set of items to be searched is divided at each
step into two equal, or nearly equal, parts, Also known as binary chop. The most efficient
method used for searching a sequential table is binary search. It doesn’t need any primary or
secondary index.

154

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

A binary search or half-interval search algorithm finds the position of a specified


value (the input "key") within a sorted array. At each stage, the algorithm compares the
input key value with the key value of the middle element of the array.
If the keys match, then a matching element has been found so its index, or position, is
returned.
Otherwise, if the sought key is less than the middle element's key, then the algorithm
repeats its action on the sub-array to the left of the middle element or, if the input key is
greater, on the sub-array to the right. If the remaining array to be searched is reduced to
zero, then the key cannot be found in the array and a special "Not found" indication is

ww
returned.

w.E
Suppose we have an array of 7 elements
9 10 25 30 40 45 70

0 1 asy 2 3 4 5 6

En
Following steps are generated if we binary search a data =45 from the above array

Step 1: LB gi nee UB
9 10 25 30 40 45 70
rin
LB=0;
0 1
UB=6
2 3 4
Mid=(0+6)/2 = 3
5 6
A[3] = 30 g.n
Step 2:
e t
Since A[3] < ITEM ie., 30 <45 reinitalise LB, UB and mid
LB UB
9 10 25 30 40 45 70

0 1 2 3 4 5 6
LB=3; UB=6 Mid=(3+6)/2 = 4 A[3] = 40

Step3:
Since A[4] < ITEM ie., 40 <45 reinitalise LB, UB and mid
LB UB

155

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

9 10 25 30 40 45 70
0 1 2 3 4 5 6
LB=4; UB=6 Mid=(4+6)/2 = 5 A[5] = 45

Step 4:
Since A[5] == ITEM 45 = 45 , search is successful.
Code:
#include<stdio.h>
#include<conio.h>
void main()

ww
{
int a[10],i,n,m,c=0,l,u,mid;

w.E
printf("Enter the size of an array: ");
scanf("%d",&n);
asy
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
En
}
scanf("%d",&a[i]);
gi nee
printf("Enter the number to search: ");
scanf("%d",&m); rin
l=0,u=n-1; g.n
while(l<=u)
{
e t
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
156

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is present in location %d\n.",mid+1);
getch();

ww
}
Output:

w.E
Enter the size of an array
5

asy
Enter the elements in ascending order
12
En
13
16
20
gi nee
32
rin
Enter the number to search
g.n
20
The number is present in location 4 e t
MERGE SORT

5. Write routines for merge sort and explain. Nov/Dec 2014


MergeSort is a Divide and Conquer algorithm. It divides input array in two halves,
calls itself for the two halves and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is key process that
assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays
into one.

157

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:

ww Call merge(arr, l, m, r)
The following diagram shows the complete merge sort process for an example array

w.E
{38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the
array is recursively divided in two halves till the size becomes 1. Once the size becomes

asy
1, the merge processes comes into action and starts merging arrays back till the complete
array is merged.
En
gi nee
rin
g.n
e t

Routine
void mergesort( int a[],int l,int r)
{

158

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

if(l<r)
{
c=(l+r)/2;
mergesort(a,i,c);
mergesort(a,c+1,r);
mergesort(a,i,c+1,r);
}
}
void merge(int a[],int l,int r,int rend)

ww
{
int temp[20];

w.E
int lend=r-1;
int t=l;

asy
int noe=rend-l+1;
while(l<=lend && r<=rend)
En
{
if(a[l]<=a[r]) gi
temp[t++]=a[l++]; nee
else
rin
temp[t++]=a[r++];
g.n
}
while(l<=lend)
temp[t++]=a[l++];
e t
while(r<=rend)
temp[t++]=a[r++];
for(int i=0;i<noe;i++;rend--)
a[rend]=temp[rend];
}

159

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

PART – C

EXAMPLE PROGRAMS

6. Write a program to implement binary search with example?

The input should be sorted. The search in the list can be made faster by using “divide
and conquer” technique.It has the following characteristics:
• The input list must be sorted
• It is faster as compared to linear search.

Program
#include<iostream.h>
#include<conio.h>

ww void main()
{

w.E
clrscr();
int a[100],n,i,beg,end,mid,item;

asy
cout<<"----------- BINARY SEARCH ------------ ";
cout<<"Enter No. of Elements= ";
cin>>n;
En
for(i=1;i<=n;i++)
{
gi
cout<<"Elements in Sorted Order=";

nee
cin>>a[i];
}
cout<<"Item you want to Search= "; rin
cin>>item;
beg=1; g.n
end=n;
mid=(beg+end)/2; // Find Mid Location of Array e t
while(beg<=end && a[mid]!=item) // Compare Item and Value of Mid
{
if(a[mid]<item)
beg=mid+1;
else
end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
{
cout<<"is Found at Location : "<<mid;
}
else
160

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
cout<<"Data is Not Found";
}
getch();
}

Example

Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}.


Step 1 (middle element is 19 > 6): -1 5 6 18 19 25 46 78 102 114
Step 2 (middle element is 5 < 6): -1 5 6 18 19 25 46 78 102 114
Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114

ww
7. Write an algorithm to sort a set of 'N' numbers using Radix sort. Trace the
algorithm for the following set of numbers.

w.E 88,11,22,44,66,99,32,67,54,10

Radix sort is a non-comparative integer sorting algorithm that sorts data with

asy
integer keys bygrouping keys by the individual digits which share the same
significant position and value

En
Sort by the least significant digit first (counting sort)

gi
Numbers with the same digit go to same bin

nee
Reorder all the numbers: the numbers in bin 0 precede the numbers in bin
1, which precede the numbers in bin 2, and so on
Sort by the next least significant digit
rin
Continue this process until the numbers have been sorted on all k digits
Given the input the array has to be sorted using radix sort
Code: g.n
#include<stdio.h>
#include<conio.h>
radix_sort(int array[], int n);
e t
void main()
{
int array[100],n,i;
clrscr();
printf("Enter the number of elements to be
sorted: "); scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nArray Before Radix Sort:"); //Array Before Radix Sort
161

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

for(i = 0; i < n; i++)


{
printf("%d ", array[i]);
}
printf("\n");
radix_sort(array,n);

printf("\nArray After Radix Sort: "); //Array After Radix Sort


for(i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
printf("\n");
getch();

ww
}
void radix_sort(int arr[], int n)
{
w.E
int bucket[10][5],buck[10],b[10];

asy
int i,j,k,l,num,div,large,passes;

div=1;
num=0;
En
large=arr[0];
gi
for(i=0 ; i<n ; i++)// Find the largest no
{ nee
if(arr[i] > large)
{ rin
}
large = arr[i];
g.n
while(large > 0)// Get the number of digits of the largest no
{
e t
num++;
large = large/10;
}
for(passes=0 ; passes<num ; passes++)//For all the digits do the following
{
for(k=0 ; k<10 ; k++)
{
buck[k] = 0;
}
for(i=0 ; i<n ;i++)
{

162

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

l = ((arr[i]/div)%10);//Find the position of the element and insert


bucket[l][buck[l]++] = arr[i];
}
i=0;
for(k=0 ; k<10 ; k++)
{
for(j=0 ; j<buck[k] ; j++)// Rearrange the elements in the array
{
arr[i++] = bucket[k][j];
}
}
div*=10;
}

ww
}
}

Sort by comparing and ordering the one’s digits:

w.E
10 11 22 32 asy
Combine the numbers in order
44 54 66 67 88 99.\

En Digit Sub list

gi 0 10
nee
1 11

rin
2 22
g.n
3

4
32

44
e t
5 54

6 66

7 67

8 88

9 99

It is already sorted. Therefore it is not necessary to go for the next significant digit.

163

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

INDUSTRIAL /PRACTICAL CONNECTIVITY OF THE SUBJECT

• Modular coding, OOP in particular, offers many advantages over monolithic


code including ease of test, reuse of code, and portability to different
hardware target platforms.

• It only takes one programmer to properly develop an OOP framework. That


framework can then be used by other programmers. The beauty of OOP lies in
its ability to manage complex tasks, its flexibility, and its efficient use of
hardware.
ww
Real time Systems : -

w.E
A real time system is nothing but a dynamic system. OOP approach is very useful for

asy
Real time system because code changing is very easy in OOP system and it leads

En
toward dynamic behaviour of OOP codes thus more suitable to real time system.

gi
Simulation and Modeling: -
nee
rin
System modelling is another area where criteria for OOP approach is countable.

g.n
Representing a system is very easy in OOP approach because OOP codes are very
easy to understand and thus is preffered to represent a system in simpler form.

Hypertext And Hypermedia : -


e t
Hypertext and hypermedia is another area where OOP approach is spreading its legs.
Its ease of using OOP codes that makes it suitable for various media approaches.

CAM/CAE/CAD System : -

Computer has wide use of OOP approach. This is due to time saving in writing OOP
codes and dynamic behaviour of OOP codes.

164

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Office Automation System : -

Automation system is just a part or type of real time system. Embeded systems make
it easy to use OOP
In networking, the following are the applications of data structures
Stacks -
E.g., Conversion of recursive routines to non-recursion
Queues -Managing IDs

ww
Linked lists are more common than arrays to maintain stacks or queues-
To have flexibility in the number of entries and for memory efficiency

w.E
Hashing
Used when order is not important but Lookup needs to be fast and it is used for
MAC table asy
Sorting-
En
gi
E.g., to display list of users in a show command

nee
E.g., to show the forwarding table used for switching

rin
g.n
e t

165

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ANNA UNIVERSITY QUESTIONS


B.E / B.Tech DEGREE EXAMINATION NOV / DEC 2014
Third Semester
Electronics and Communication Engineering
EC6301 – OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time : Three Hours Maximum : 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)

ww
1. Write a C++ code to swap values of two variable using reference variables in

w.E
fuction.[Page No.10]
2. Write a C++ code to display “pen object instantiated” and “pen object destroyed”when

asy
class for pen constructor and destructor are called.[Page No.12]
3. Write a C++ code to display as area of square or rectangle using function overriding.
[Page No.42] En
gi
4. Write a sample to code to show the usage of this pointer in C++.[Page No.44]

nee
5. Evaluate the value of expression ab+c*d using stack. [Page No.74]

rin
6. Find the maximum number of nodes in complete binary tree if d is depth. [Page No.110]
7. Write short notes on connected components. [Page No.112]
g.n
8. Give the representation of network of cities(Chennai,Delhi,kolcutta and Mumbai)as
weighted graph. [Page No.111]
9. How to perform union operation? [Page No.113]
e t
10. What is the time complexity of quick sort and binary search? [Page No.146]
PART B – (5 x 16 = 80 marks)
11. (a) Write a member function and friend function to subtract two complex numbers in
C++. [Page No.26] Or
(b) Write a member function to perform matrix addition,simple addition and string
concatenatation.by overloading + operator. [Page No.27]

166

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

12. (a)Write a C++ code to construct classes of a person with name and age as public
properties,account details as private properties and percentage of mark as protected
property.Construct a class with sports details of person.Construct a class to rank person
based on the equal weightage to academic and sports details.Use inheritance
concept.(16)[Page No.66]
Or
(b) Explain class object to Base and Base to class object conversions using C++ with
suitable examples. [Page No.50]

ww
13. (a)Write a C++ code to sum up all odd numbers in a single linked list.[Page No.102]
Or

w.E
(b)Write a C++ code to perform addition of two polynomials using linked list form of
queue. [Page No.74]

asy
14. (a)Explain BFS and DFS with suitable example. [Page No.118]

En Or

gi
(b)Write a c++ code for the implementation of different types of tree traversals.State the
tree applications. [Page No.114]
nee
15. (a)Write a C++ code to implement quick sort with suitable examples.Write C++ code to
implement linear search with suitable examples. [Page No.147,154]
rin
Or
g.n
implement binary search with suitable examples. [Page No.159,156]
.
e
(b)Write a C++ code to implement merge sort with suitable examples.Write C++ code to

167

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

B.E / B.Tech DEGREE EXAMINATION APRIL /MAY 2015

ThirdSemester
Electronics and Communication Engineering
EC6301 – OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time : Three Hours Maximum : 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)
1. What is a reference variable? [Page No.9]

ww
2. What is a friend function? [Page No.9]
3. What is overriding? [Page No.33]

w.E
4. Why there is need for operator overloading? [Page No.34]

asy
5. What is abstract data type? [Page No.71]
6. Write short notes on queue.[Page No.71]

En
7. What is a tree? [Page No.110]

gi
8. How a graph is represented? [Page No.85]
9. What is meant by sorting? [Page No.143]
nee
10. What is time complexity?[Page No.143]
PART B – (5 x 16 = 80 marks) rin
11. (a) Describe the major components of object oriented programming with
g.n
illustrations.(16) [Page No.30]
Or e t
(b)What is the purpose of constructor and destructor? Explain with suitable example
the different types of constructors in C++.(16)[Page No.33]

12. (a) What is inheritance? Discuss in detail about the various types of inheritances in
c++ with suitable examples. (16) [Page No.57]
Or
(b) What is virtual function? Explain with an example how latebinding is achieved
using virtual function.(16) [Page No.52]

168

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

13. (a) Write a set of routines for implementing two stacks within a single array.
[Page No.86]
Or
(b) Write a set of routines for implementing queue using linked Lists. (16)
[Page No.90]
14. (a) Discuss the different methods traversing a binary tree with algorithm. (16)
[Page No.114]
Or
(b) Illustrate the depth First Search algorithm with a graph and explain.(16)

ww [Page No.118]
15. (a) Discuss the Quick sort algorithm and apply the same for the following

w.E
numbers:90,77,60,99,55,88,66 (16) [Page No.147]
Or

asy
(b) Explain in detail about linear search algorithm with an example.(16)
[Page No.154]
En
gi nee
rin
g.n
e t

169

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

B.E / B.Tech DEGREE EXAMINATION NOV / DEC 2015


Third Semester
Electronics and CommunicationEngineering
EC6301– OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time : Three Hours Maximum : 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)
1. What is destructor?. [Page No.9]

ww
2. Define friend function. [Page No.9]
3. Differentiate private and protected members of a class. [Page No.45]

w.E
4. What is dynamic binding? [Page No.37]
5. Define ADT. [Page No.71]

asy
6. What do you mean by queue ADT? [Page No.71]

En
7. What is binary tree? [Page No.112]

gi
8. When a graph is said to be connected?[Page No.110]

nee
9. How an array elements are sorted using merge sort? [Page No.143]
10. With an example compute the number of comparison, required to search an element
using binary search. [Page No.114]
rin
PART B – (5 x 16 = 80 marks)
g.n
of them. (16) [Page No.16]
Or
e
11. Narrate on parameterized constructor and copy constructorwith an example for each

t
(b) (i) What do you mean by function overloading and explain it with an example? (8)
[Page No.21]
(ii) Elaborate on binary operator overloading with an example.(8) [Page No.21]

12. (a)(i) Explain base and derived classes with examples.(8) [Page No.45]
(ii) Write a program to illustrate how constructors are implemented when the classes
are inherited? (8) [Page No.70]
Or

170

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

(b) (i) Give an account on virtual functions with an example(8) [Page No.41]

(ii) Write a note on “this” pointer with an example. (8) [Page No.44]

13. (a)(i)Write a note on singly linked list.(8) [Page No.74]


(ii) Explain List ADT. (8)[Page No.77]
Or
(b)Explain the applications of stack in detail.(16) [Page No.79]

ww
14.(a) (i) How can you construct an expression tree?Describe your answer with an
example.(8) [Page No.127]

w.E
(ii) Discuss how sets are represented?(4) [Page No.131]
(iii) Explain union find operations. (4) [Page No.133]

asy
En Or

[Page No.118] gi
(b)Describe in detail about breadth-first search and depth-first search in a graph.

nee
15. (a) Explain quick sort in detail. (16) [Page No.147]
rin
Or
g.n
(b) (i) Describe binary search in detail.(8) [Page No.156]
(ii) Explain linear search in detail. (8) [Page No.154] e t

171

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

B.E / B.Tech DEGREE EXAMINATION NOV / DEC 2016


Third Semester
Electronics and CommunicationEngineering
EC6301– OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time : Three Hours Maximum : 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)
1. What is meant by default constructor?

ww
2. State the difference between structure and class.
3. What is the role of this pointer?

w.E
4. Define virtual function.
5. What is a data structure? How it is classified?

asy
6. List the applications of linked list.

En
7. What are the two ways of representing binary tree?

gi
8. Differentiate breadth first and depth first search strategies.
9. What is the time complexity of linear search?
nee
10. Name the sorting techniques which use the divide and conquer strategy.
PART B - (5*13=65 Marks)
rin
11. a) Explain in detail about the features of object oriented programming.
g.n (13)
Or
b) i) Write a program for swapping two numbers using friend function. e
ii) Write a program to find the area of a rectangle and triangle using function
(6)
t
overloading. (7)
12. a) Explain the concept of composition with example. (13)
Or
b) Describe the types of inheritance in C++ with an example. (13)
13. a) Implement insertion, deletion and search operations in single linked list. (13)
Or
b) Develop an algorithm to implement queue ADT. Give relevant examples and
diagrammatic representation. (13)

172

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

14. a) Discuss the graph traversals with suitable algorithms and examples. (13)
Or
b) Explain the algorithm for union and find operations in disjoint sets. (13)
15. a) Explain the algorithm of quick sort by sorting ther following set of numbers as an
example: 42 47 52 57 62 37 32 27 22
Or
b) Write the algorithm to perform binary search on an array and demonstrate with an
example.

ww PART C – (1 * 15 = 15 Marks)
16. a) Implement the ATM transaction in C++. (15)

w.E Or
b) Define an abstract class called employee. Derive two classes called hourly

asy
employee and salaried employee. Hourly employee has number of hours (integer),

En
and wage per hour (float).

gi
Salaried Employee has salary of type float. Calculate salary() in an abstract function

nee
in class employee which inherited by derived classes. Write a main program to create
objects of all classes and calculate salary of each object. (15)

rin
g.n
e t

173

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

B.E / B.Tech DEGREE EXAMINATION APRIL/MAY 2017


Third Semester
Electronics and CommunicationEngineering
EC6301– OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time: Three Hours Maximum: 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)
1. List the benefits of using ststic class data. Give an example of a class with static

ww members.
2. What operation is performed when the default assignment operator = is applied to

w.E
objects?
3. When is the protected access specifier used in a class?

asy
4. State the purpose of virtual base classes.

En
5. Write a procedure to insert an element in the beginning of a list ADT implemented

gi
using a singly linked list.

nee
6. List the advantages in the linked list implementation of stack.
7. The inorder traversal of a binary tree resulted in E A C K F H D B G. What would its
preorder traversal return?
rin
8. What is a graph? List the two ways to represent a graph.
g.n
9. State the drawbacks of insertion sort.
10. Give the algorithm to search an element in an array using linear search. e t
PART B – (5 x 13 = 65 Marks)
11. a) i) What is function overloading? Explain with example, why it is important? (6)
ii) Write a program in C++ using friend function to find the product of two
complex numbers. (7)
Or
b) i) What is a container? Explain the types of sequence containers with examples.(7)
ii) Write a program in C++ to demonstrate the addition of two complex numbers by
overloading + operator. (6)

174

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

12. a) i) Demonstrate the order of invocation and execution of constructors and


destructors in multilevel inheritance with an example. (7)
ii) Explain overriding of member functions with an example. (6)
Or
b) i) Write a program in C++ to find the area of a rectangle and a triangle using
virtual function. (8)
ii) Demonstrate with an example, how a member function can find out the address
of the object to which belongs using this pointer. (5)

ww
13. a) i) Represent two polynomials using singly linked lists and develop procedures to
add them. (6)

w.E
ii) Develop algorithms to perform insertion, deletion and search operations in a
queue implemented using singly linked lists. (7)

asy Or

En
b) Develop procedures to perform push and pop operation on an array

1 2 3 * - 4 +. gi
implementation of statch and use the same to evaluate a postfix expression

nee (13)

rin
14. a) i) How can binary trees be represented using arrays? Write routines to perform
insertion and deletion in a tree.
g.n (7)

elements. Illustrate with examples.


Or
e
ii) Write routines to convert a set as a tree and perform find operation on the
(6)
t
b) With necessary algorithms, explain the two graph traversal methods. Demonstrate
with examples. (13)

15. a) Write a recursive algorithm for quick sort and apply the same to sort the elements
12, 3, 2, 26, 5, 21, 18, 25 and 50 and trace the output. (13)
Or
b) i) Sort the elements 12, 3, 2, 26, 5, 21, 18, 25 and 50 using merge sort and trace
the output. (6)

175

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ii) Develop an algorithm to perform binary search on an array of elements and


demonstrate with an example. (7)

PART – C (1*15 = 15 Marks)

16. a) Design an algorithm to convert an infix expression to postfix expression using


stacks and apply to the expression (a + b – d * e + ( f * g + h ) * i ). (15)
Or
b) Design procedures to count the number of connected components and the number

ww of vertices in each component of a graph. Illustrate with examples. (15)

w.E
asy
En
gi nee
rin
g.n
e t

176

Downloaded From : www.EasyEngineering.net

You might also like