You are on page 1of 249

Visit & Downloaded from : www.LearnEngineering.

in

ENGINEERING COLLEGES
2017 – 18 Odd Semester
IMPORTANT QUESTIONS & ANSWERS
Department of CSE

SUBJECT CODE: CS6301

SUBJECT NAME: PROGRAMMING AND DATA STRUCTURES II

Regulation: 2013 Year and Semester: II Year/ 03 Sem

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

SYLLABUS
CS6301 PROGRAMMING AND DATA STRUCTURES II L T P C 3003
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS 9
C++ Programming features – Data Abstraction – Encapsulation – class – object –
constructors – static members – constant members – member functions – pointers –
references – Role of this pointer – Storage classes – function as arguments.
UNIT II OBJECT ORIENTED PROGRAMMING CONCEPTS 9
String Handling – Copy Constructor – Polymorphism – compile time and run time
polymorphisms – function overloading – operators overloading – dynamic memory
allocation – Nested classes – Inheritance – virtual functions.
UNIT III C++ PROGRAMMING ADVANCED FEATURES 9
Abstract class – Exception handling – Standard libraries – Generic Programming –
templates – class template – function template – STL – containers – iterators –
function adaptors – allocators – Parameterizing the class – File handling concepts.
UNIT IV ADVANCED NON-LINEAR DATA STRUCTURES 9
AVL trees – B-Trees – Red-Black trees – Splay trees – Binomial Heaps – Fibonacci
Heaps – Disjoint Sets – Amortized Analysis – accounting method – potential method
– aggregate analysis.
UNIT V GRAPHS 9
Representation of Graphs – Breadth-first search – Depth-first search – Topological
sort – Minimum Spanning Trees – Kruskal and Prim algorithm – Shortest path
algorithm – Dijkstra‟s algorithm – Bellman-Ford algorithm – Floyd – Warshall
algorithm.
TOTAL: 45 PERIODS
TEXT BOOKS:
1. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson
Education,2007.
2. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, 2nd Edition,
Pearson Education, 2005

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

INDEX
Sl.no Topic Page No

a 1
Aim and Objective of the Subject
b Detailed Lesson Plan 2
UNIT I OBJECT ORIENTED PROGRAMMING
FUNDAMENTALS
c Part A 4
d Part B 9
1 Object Oriented Concepts 9
2 Constructors and Destructors 14
3 Member Functions 19
4 Static Member Functions 23
5 Pointers 24
e Part C 27
6 Write a C++ program Compare Two Strings Using 27
Pointers
7 Write A C++ Program To Add And Subtract Two 28
Matrices
UNIT II OBJECT ORIENTED PROGRAMMING CONCEPTS
f Part A 30
g Part B 34
8 Dynamic Memory Allocation 34
9 Operator overloading 37
10 Inheritance(Single, Mulitlevel and hierarchial) 44
11 Inheritance(Multiple, Hybrid) 56
12 Polymorphism 62
h Part C 67
13 Program - String handling 67
14 Program - Constructor, Destructor 70
15 Program - Copy Constructor 75
16 Friend Function - Program 78
UNIT III C++ PROGRAMMING ADVANCED FEATURES
i Part A 80
j Part B 85
17 Exception handling 85
18 Components of STL 91
19 Generic Programming, Templates and 98

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

parameterizing the class


20 File handling concepts 105
21 Function Adaptors and Allocators 112
k Part C 116
UNIT IV ADVANCED NON-LINEAR DATA STRUCTURES
k Part A 128
l Part B 133
22 Binary search Tree 133
23 Red-black Tree 142
24 AVL Tree 148
25 B-Tree 155
26 Splay Tree 165
l Part C 169
27 Heaps 169
28 Amortized Analysis 192
UNIT V GRAPHS
m Part A 202
n Part B 204
29 Representation of Graphs & Traversals 201
30 Topological sort 206
31 Minimum Spanning Trees 208
32 Shortest path algorithm 215
33 Bellman-Ford Algorithm 218
o Part C
p Industrial/Practical Connectivity of the subject 228
34 University Question Bank 229

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Aim and Objective of the Subject

The student should be made to:

 Be familiar with the C++ concepts of abstraction, encapsulation, constructor,


polymorphism, overloading and Inheritance.
 Learn advanced nonlinear data structures.
 Be exposed to graph algorithms.
 Learn to apply Tree and Graph structures

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Detailed Lesson Plan

Name of the Subject& Code: CS6301: PROGRAMMING AND DATASTRUCTURES II

Text Books:
1. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson
Education, 2007.
2. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, 2nd Edition,
Pearson Education, 2005
Unit Hours Cumulative Books
Topics
no required hours Referred
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
C++ Programming features - Data
Abstraction - Encapsulation - class - 2 2 T1
object
Constructors – Static members 1 3 T1
I
Constant members – Member functions 1 4 T1
Pointers – References 2 6 T1
Role of this pointer 1 7 T1
Storage classes – Function as arguments 2 9 T1
UNIT II OBJECT ORIENTED PROGRAMMING CONCEPTS
String Handling – Copy Constructor 1 10 T1
Polymorphism – Compile time and run
2 12 T1
time polymorphisms
Function overloading – Operators
2 14 T1
overloading
II
Dynamic memory allocation - Nested
1 15 T1
classes
Inheritance 2 17 T1
Virtual functions 1 18 T1
UNIT III C++ PROGRAMMING ADVANCED FEATURES
T1
III Abstract class – Exception handling 2 20

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Standard libraries - Generic


1 21 T1
Programming
Templates – class template - function
2 23 T1
template
STL – containers – Iterators 2 25 T1
Function adaptors – Allocators 1 26 T1
Parameterizing the class - File handling 1
27 T1
concepts
UNIT IV ADVANCED NON-LINEAR DATA STRUCTURES
AVL trees 2 29 T2
B-Trees – Red-Black trees 2 31 T2
Splay trees - Binomial Heaps –
2 33 T2
IV Fibonacci Heaps
Disjoint Sets – Amortized Analysis 1 34 T2
Accounting method – Potential method 1 35 T2
Aggregate analysis 1 36 T2
UNIT V GRAPHS
Representation of Graphs – Breadth-first
1 37 T2
search – Depth-first search
Topological sort 2 39 T2
Minimum Spanning Trees – Kruskal
2 41 T2
and Prim algorithm
V
Shortest path algorithm – Dijkstra‟s
2 43 T2
algorithm
Bellman-Ford algorithm 1 44 T2
Floyd - Warshall algorithm 1 45 T2

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT I
OBJECT ORIENTED PROGRAMMING FUNDAMENTALS

C++ Programming features - Data Abstraction - Encapsulation - class - object


- constructors - static members – constant members – member functions –
pointers – references - Role of this pointer – Storage classes – function as
argument

PART – A
1. When do you declare a member of a class static? [Apr/May 16]
(or)
Give the significance of declaring a member of a class static. [Nov/Dec 15]
When we declare a member of a class as static it means no matter how many
objects of the class are created, there is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to
zero when the first object is created, if no other initialization is present.

2. List out the advantages of using storage classes. [Apr/May 16]


 A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C++ Program.
 Declaring a variable using register storage class makes it quick to access it.
 When static is used, it is shared by all objects.
 The extern storage class can be used to give reference of a global variable that is
visible to all.

3. Which is used for achieving Data Hiding in C++? List its types.
[Apr/May 15]
A member can be hidden using private visibility mode(access specifier) in
C++. There are three access specifier in C++. They are
 Private

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Public
 Protected

4. With which concept, visibility and lifetime of the variable differ in C++?
List its types. [Apr/May 15]
C++ defines the visibility and lifetime of a variable using the storage classes. There
are four storage classes available. They are
 auto
 static
 extern
 register

5. Define Data Abstraction. [Nov/Dec 14]


Object Oriented Programming has a special feature called data abstraction. Data
abstraction allows ignoring the details of how a data type is represented. While
defining a class, both member data and member functions are described. However
while using an object (that is an instance of a class) the built in data types and the
members in the class are ignored. This is known as data abstraction.

6. Write a member function to find the greatest of two numbers using ‘this’
pointer. [Nov/Dec 14]
class sample
{
int a;
public:
sample(){}
sample(int n)
{
a=n;
}
void max(sample);

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

};
void sample::max(sample obj)
{
cout<<“The maximum is:”;
if(this.n>obj.n)
{
cout<<this.n;
}
else
{
cout<<obj.n;
}
}
void main()
{
sample obj(5), obj1(10);
obj.max(obj1);
}
7. Differentiate pointer and a reference. [Nov/Dec 11]
A pointer variable is used to access the address of a variable.
Syntax
Data-type *pointername;
Eg:
int *ptr;
ptr=&a; //Ptr points to address of a
A reference variable provides an alias(alternative name) for a previously defined
variable.
For example , if make the variable sum a reference to the variable total, then sum and
total can be used interchancheably to represent that variable.
Syntax:
Data-type &reference-name = variable-name

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Eg:
float total = 100;
float sum = total;

8. Differentiate class and object. [Nov/Dec 12] [Nov/Dec 10]


The entire set of data and code of an object can be made a user-defined data
type with the help of a class. Once a class has been defined, we can create any number
of objects belonging to the classes. Classes are user-defined data types and behave like
built-in types of the programming language.

Objects are basic run-time entities in an object-oriented system. They may


represent a person, a place, a bank account, a table of data or any item that the
program has to handle. Each object has the data and code to manipulate the data and
theses objects interact with each other.

9. Write any four features of OOPS.


 Emphasis is on data rather than on procedure.
 Programs are divided into objects.
 Data is hidden and cannot be accessed by external functions.
 Follows bottom-up approach in program design.

10. What are manipulators?


setw, endl are known as manipulators.
Manipulators are operators that are used to format the display. The endl manipulator
when used in an output statement causes a linefeed to be inserted and its effect is
similar to that of the newline character "\n”.
Eg:Cout<<setw(5)<<sum<<endl;

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

11. What is the use of ‘this’ pointer? [Nov/Dec 15]


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.

12. How the class is specified? [Nov/Dec 15]


Generally class specification has two parts
 class declaration
It describes the type and scope of its member
 class function definition
It describes how the class functions are implemented
The general form is
class class_name
{
private:
variable declarations;
function declaration;
public:
variable declaration; function declaration;
};

13. Define copy constructor [Nov/Dec 11]


A copy constructor is used to declare and initialize an object from another object. It
takes a reference to an object of the same class as an argument
Eg: integer i2(i1);
would define the object i2 at the same time initialize it to the values of i1.
Another form of this statement is
Eg: integer i2=i1;
The process of initializing through a copy constructor is known as copy initialization.

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

14. Define destructor. [May/June 12][Apr/May 11]


It is used to destroy the objects that have been created by constructor. Destructor name
is same as class name preceded by tilde symbol(~)
Eg;
~integer()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler
upon exit from the program will invoke it.

15. What is static member function?


A member function that is declared as static has the following properties
 A static function can have access to only other static member declared in the
same class
 A static member function can be called using the classname as follows
classname ::function_name;
PART – B

1. Object Oriented Programming Concepts

 List the C++ programming features and explain in brief, how each of those
are achieved [April/May 15]
 Explain the Object Oriented Programming concepts. [Nov/Dec 11]
 Explain the characteristics of OOPS in detail [Nov/Dec 12]

C++ Programming Features


 Classes
 Objects
 Data Abstraction and Encapsulation
 Inheritance

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Polymorphism
 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.
Eg: fruit mango;
Where fruit is the class name and mango is the object name
Objects
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 match closely with the real world objects. Objects communicate with each other
by passing message.
Each object contains data and code to manipulate the data.

Object : Student
DATA
Name
STUDENT
DOB
Marks TOTAL

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

10

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

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.

Inheritance

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 reusability which means that we can add additional
features to an existing class without modifying it. The newly created class is called as
derived class and the old class is called as base class.

BIRD

FLYING NON-FLYING
BIRD BIRD

EAGLE CROW PENGUIN KIWI

Polymorphism

It is derived from a Greek word which means the ability to take more than one
form. It is classified into two types. They are

11

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 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.
'+' 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()

Circle Rectangle Triangle

Draw() Draw() Draw()

Dynamic Binding

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


response to the function call. Dynamic Binding means that the code to be used for a
function call is not known until the time of the call at run time. It is related to
inheritance and polymorphism.

12

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Message Passing

An object oriented programming consist of a set of objects that communicate


with each other. The steps for communicating are
 Create class with data and code
 Create objects for that class
 Establish communication
employee.salary(name)

Information
Object 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.

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

13

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Constructors and Destructors

 What is Constructor? Explain the different types of constructor with


suitable examples. [Apr/May 16]
 List the different types of constructors. Write a program to illustrate the
use of different types of constructors. [Nov/Dec 14]

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
{
int m,n;
public:
sample()
{
m=0;
n=0;
}
};
The rules to be followed
 It should be in public section
 It should have the same name as that of the class name
 It has no return type
 It cannot be virtual
 It cannot be inherited

14

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

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
{
int a,b;
public:
sample()
{
a=5;
b=10;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj;
obj.display();
}

Output:
5 10

15

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Parameterized Constructor

A constructor with arguments is called as parameterized constructor. It is


invoked when an object is created with matching arguments.
Eg:
class sample
{
int a,b;
public:
sample()
{
a=0;
b=0;
}
sample(int d,int e)
{
a=d;
b=e;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj(10,5);
obj.display();
}
Output:
10 5

16

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Copy Constructor
It is used to declare and initialize an objects from another object.
Eg:
class sample
{
int a,b;
public:
sample()
{
a=0;
b=0;
}
sample(int d,int e)
{
a=d;
b=e;
}
sample(sample &obj)
{
a=obj.a;
b=obj.b;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj(10,5);
sample obj1(obj)

17

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

obj1.display();
}
Output:
10 5
Destructor
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
{
int id;
public:
sample()
{
id=5;
}
~sample()
{
cout<<id;
}
};
void main()
{
sample obj;
}
Output:
5

18

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

3. Member Functions

 Explain the ways in which member functions of a class can be defined and
called using suitable examples. [Apr/May 15]

Member functions are the functions that are declared inside the class definition and
works on the data members of the class. A member function can be defined in two
ways.
 Inside the class
 Outside the class
If the function is defined inside the class definition it is called as inline function
which can be defined directly. If it is declared outside the class then it should be
defined using the scope resolution operator :: along with the class name and function
name.
Inside the Class
A Function can be defined inside the class in the usual manner. Since it is an inline
function, it cannot contain any conditional statements.
class sample
{
int a,b;
public:
void getdata()
{
cout<<"Enter two numbers:";
cin>>a>>b;
}
void sum()
{
int sum;
sum=a+b;
cout<<sum;

19

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
};
void main()
{
sample obj;
obj.getdata();
obj.sum();
}

Outside the Class


A function can be defined outside the class using the following syntax
returntype classname::functionname(args)
{
//sts
}
class sample
{
int a,b;
public:
void getdata();
void sum();
};
void sample::getdata()
{
cout<<"Enter two numbers:";
cin>>a>>b;
}
void sample::sum()
{
int sum;
sum=a+b;

20

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<sum;
}

void main()
{
sample obj;
obj.getdata();
obj.sum();
}

 Describe the different mechanisms for accessing data members and


member functions in a class with a suitable example. [Apr/May 16]

Accessing a data member depends solely on the access control of that data member. If
its public, then the data member can be easily accessed using the direct member
access (.) operator with the object of that class.

If, the data member is defined as private or protected, then we cannot access the data
variables directly. Then we will have to create special public member functions to
access, use or initialize the private and protected data members. These member
functions are also called getter and setter functions.

Accessing Public Data Members:

#include<iostream.h>
class sample
{
public:
int a;
void display()
{
cout<<a;
}

21

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

};
void main()
{
sample obj;
obj.a=5; //Public Variable
obj.display();
}

Accessing Private Data Members:


#include<iostream.h>
class sample
{
int a; //Private Variable
public:
void get_a(int n)
{
a=n;
}
void put_a()
{
cout<<a;
}
};
void main()
{
sample obj;
obj.get_a(5);
obj.put_a();
}

22

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4. Static Member Functions

 What do you understand by static member and static function? How to


declare them? Illustrate with an example program. [Apr/May 15]

Static Data Member


A variable which is a part of the class but not a part of an object is called as a static
member. When a data member is declared as static then only one copy of the data is
maintainer for all objects of the class. It is automatically initialized to 0, when the first
object of the class is created. It must be initialized always outside the class using
scope resolution operator.
Static Member Function
A function that needs access to members of a class, without invoking for a particular
object is defined as static member function. It can be declared by prefixing it with the
keyword static. A static function has the following properties
 A static function can access only static members or static function declared in
the same class
 A static function will be called using the class name as follows
class_name::function_name();
 A static function is common to the entire class

Example:
class sample
{
static int num;
public:
static void increment()
{
num++;
}
void display()

23

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
cout<<num<<"\n";
}
};
int sample::num=10;
void main()
{
sample a,b;
sample::increment();
sample::increment();
a.display();
b.display();
}
Output
12
12
5. Pointers

 Explain the role of this pointer. [Apr/May 16][Apr/May 15]


C++ uses a 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 was
called. This unique pointer is automatically passed to a member function when
it is called. It act as an implicit argument to all the member functions.
Example

#include<iostream.h>
class sample
{
int num;
public:
sample(int x)

24

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
num=x;
}
sample & greater(sample &x)
{
if(num>=x.num)
return *this;
else
return x;
}
void display()
{
cout<<num;
}
};
void main()
{
sample n1(5), n2(10);
sample ans;
ans=n1.greater(n2);
ans.display();
}

Output
10

 Distinguish between pointer to constant and constant pointers? Give an


example program. [Apr/May 15]

Constant Pointers Pointers to Constant


These type of pointers are the one which These type of pointers are the one which

25

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cannot change address they are pointing cannot change the value they are
to. pointing to. This means they cannot
change the value of the variable whose
address they are holding.
int *const ptr; const int *ptr;
Program: Program:
#include<iostream.h> #include<iostream.h>
void main() void main()
{ {
int a=5, b=10; int a=5
int * const ptr=&a; const int * ptr=&a;
ptr=&b; *ptr=10;
cout<<*ptr; cout<<*ptr;
} }

This is will lead to an error This is will lead to an error

Part - C

1. a) Write a C++ program Compare Two Strings Using Pointers.

#include<iostream>
#include<stdio.h>
using namespace std;
main()
{
char str1[50],str2[50];
int str_cmp(char*,char*);
cout<<“Enter first string:”;
gets(str1);
cout<<“Enter second string:”;
gets(str2);
if(str_cmp(str1,str2))
cout<<“nStrings are equal”;
else
cout<<“nStrings are not equal”;
return 0;

26

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
int str_cmp(char *s1,char *s2)
{
while(*s1==*s2)
{
if(*s1==‟‟||*s2==‟‟)
break;
s1++;
s2++;
}
if(*s1==‟‟&&*s2==‟‟)
return 1;
return 0;
}

1. (b) Write A C++ Program To Read And Display Student Data By Using Structure
With Pointer.

#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rn;
float fees;
}st[10], *p;
int n,j,q=0;
clrscr();
cout<<"\nHow Many Students have Data : ";
cin>> n;
cout<<"\nEnter the data :";
for(p=st; p< st+n; p++)
{
q++;
cout<<"\nEnter the Roll No of "<<q<<" Student : ";
cin>>p->rn;
cout<<"\nEnter the Fee of "<<q<<" Student : ";
cin>>p->fees;
}
p=st;
cout<<"\nYour Entered Data is:";
q=0;
while(p< st+n)

27

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
q++;
cout<< "\nRoll No of "<<q<<" Student : "<< p->rn;
cout<< "\nFee of "<<q<<" Student is : "<< p->fees;
p++;
}
getch();
}

2. Write A C++ Program To Add And Subtract Two Matrices

#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,a[10][10],b[10][10],c[10][10],d[10][10],n,m;
clrscr();
cout<<"\nEnter the Number of Rows and Columns of Matrix A and B:";
cin>>n>>m;
cout<<"\nEnter the Elements of Matrix A: \n";
for(i=0; i<n;i++)
{
for(j=0;j<m;j++)
{
cin>>a[i][j];
}
}
cout<<"\nEnter the Elements of Matrix B: \n";
for(i=0; i<n; i++)
{
for(j=0;j<m;j++ )
{
cin>>b[i][j];
}
}
for(i=0; i<n; i++)
{
for(j=0;j<m ;j++)
{
c[i][j]=a[i][j]+b[i][j];
d[i][j]=a[i][j]-b[i][j];
}
}
cout<<"\nThe Resultant Matrix C=A+B is :\n";
for(i=0; i<n; i++)
{
for(j=0; j<m; j++ )
{

28

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<c[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n The Resultant Matrix D=A-B is : \n";
for(i=0; i<n; i++)
{
for (j=0; j<m; j++ )
{
cout<<d[i][j]<<" ";
}
cout<<"\n";
}
getche();
}

29

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT-II
OBJECT ORIENTED PROGRAMMING CONCEPTS
String Handling – Copy Constructor – Polymorphism – compile time and run time
polymorphisms – function overloading – operators overloading – dynamic memory
allocation – Nested classes – Inheritance – virtual functions.

PART-A
1. Mention any 4 operators of C++ that cannot be overloaded.
Nov/Dec 2014/May/June 2014(2008)/Nov/Dec 2010
 Class Member Access Operators (. , .*)
 Scope resolution Operators(::)
 Size operator(sizeof)
 Conditional Operator(?:)

2. What are pure virtual function? Give example.


Nov/Dec 2014/May/June 2013(2008)
What is meant by abstract class? Nov/Dec 2013(2008)
A pure virtual function is a function declared in a base class but has no definition(i.e.,
virtual function with no body). The declaration is assigned the value of 0. A class
containing a pure virtual function is called abstract base class. The function should be
redefined in the derived class.
class shape
{
public:
void calc_area()=0;
};

3. Define Copy constructor and its use. April/May 2015


A constructor is a special member function whose task is to initialize the objects of its
class. A Copy constructor is a special type of constructor which will create an object

30

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

as a copy of a previously created object. It takes a reference to an object of the same


class as an argument.
Example: Integer I2(I1) ot Integer I2=I1 used to initialize I1 to I2

4. What are the special properties of virtual functions? April/May 2015


 A member function of a class.
 Declared with virtual keyword.
 Usually has a different functionality in the derived class.
 A function call is resolved at run-time to achieve runtime polymorphism.

5. How a C string differs from a C++ String? Nov/Dec2015,May/June 2016

C String C++ String

A c-string (or c-style string, or NULL C++-string is an instance of the


terminated string) is a sequence of class std::string that is part of the C++
characters that ends at the standard library.
first „\0‟ (ASCII NULL) character.
C-style string by definition cannot (as it std::string can contain embedded NUL
ends at the first NULL character). characters within its contents.

6. What is dynamic initialization of objects? Nov/Dec 2015


Class Objects can be initialized i.e., the initial value of an object may be provided
during runtime. One advantage of dynamic initialization is that we can provide
various initialization formats using overloaded constructors. This provides the
flexibility of using different format of data at run time depending on the situation.
Example:
class A
{

A(int a){ }
A(int a,int b){}
31

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

};
main()
{
A a,b;
int x,y;
cin>>x>>y;
//Respective constructors are called and initialized
a=A(x);
b=A(x,y);
}

7. Distinguish term Overloading and Overriding. May/June 2016


Overloading Overriding
Overloading can occur without Overriding of functions occurs when one
inheritance. class is inherited from another class.
Overloaded functions must differ in In overriding, function signatures must be
function signature i.e., either number of same.
parameters or type of parameters should
differ.
Overloaded functions are in same scope. Overridden functions are in different
scopes
Overloading is used to have same name Overriding is needed when derived class
functions which behave differently function has to do some added or
depending upon parameters passed to different job than the base class function.
them.

8. What are the two types of polymorphism? Give an example for each.
April/May 2015(2008)
Distinguish between early binding and late binding. Nov/Dec 2010
Define Dynamic Binding. May/June 2014(2008)

32

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Polymorphism means the ability to take more than one form. It gives different
meanings or functions to the operations or methods.
There are two types of polymorphism namely
 Compile Time Polymorphism:
For every function call compiler binds the call to one function definition at compile
time based on formal arguments of the function, their data type and their sequence.
Since the function call is determined during compilation, it is also called as Early
binding or Static binding. It is achieved using operator and function overloading.
 Run Time Polymorphism:
It allows binding to be delayed till run time. Since the function is linked with a
particular class much later after the compilation and during run time, it is called Late
binding or Dynamic binding. It is achieved through inheritance and virtual functions.

9. What is Inheritance? Illustrate. Nov/Dec 2013(2008)


What are the types of inheritance? Nov/Dec 2012
Inheriance is the most important property of object oriented programming which
supports reusability. It allows to extend the definition of a class without making the
physical changes to the existing class. The old class is referred to as base class and the
new one is called derived class.
Types of Inheritance:
 Single Inheritance
 Multi-level Inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

10. What are the visibility modes in inheritance? Nov/Dec 2009


When the access specifier for a base class is public, what the public,private
and protected members of the base class will become in the inherited class?
May/June 2013(2008)
Public Members: Can be accessed from anywhere.

33

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Protected Members: Can be accessed in the respective class and derived class.
Private members: Can be accessed only in the respective class and not anywhere else.
When the access specifier is public the protected and public members of the base class
will become protected and private members of inherited class but the private members
are not accessible.
PART-B

1. Dynamic Memory Allocation & Nested Classes

 Explain how memory is dynamically allocated and recovered in C++?


Illustrate with an example program April/May 2015

Dynamic Memory Allocation:

Dynamic memory allocation is the allocation and ownership of memory for a certain
data structure during runtime. This makes data sizes to be flexible and allows creation
of objects dynamically.
Memory is divided into two parts:
 Stack: All variables inside the function will take up memory
 Heap: This is unused memory of the program and can be used to allocated the
memory dynamically when the program runs.

Operators used:
new operator:
Memory is allocated at runtime within the heap for the variable of a given type using
“new” operator which returns the address of the space allocated.
General Syntax:
new data_type;
Example:
new int;//Dynamically allocates an integer
new int[10]//Dynamically allocates an array of 10 integers

34

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Syntax for declaring a new pointer:

Pointer_var=new data_type //allocating a variable


Pointer_var=new data_type[number of elements]//allocating an array

Example:
int *ptr; //Pointer Declared
ptr=new int; //Dynamically allocated and address assigned to ptr
*ptr=5; //5 is the value assigned to the memory
The main advantage of new over malloc( ) is that new doesn‟t just allocate memory, it
constructs objects which is the prime purpose of C++.
delete operator:
To deallocate memory that was created with “new”, the unary operator “delete” is
used.
Syntax:
delete ptr;// Release the memory pointed by pointer to a variable.
delete []ptr;// Release the memory pointed by pointer to an array.

Program to illustrate the Dynamic Memory allocation:

This program is to dynamically allocate array of size “size” and store values from 1 to
size in the array and display the contents in the screen and dynamically de-allocate the
memory after usage.
intmain()
{
intsize;
cout<<"Class size: ";
cin>>size;
//Dynamically allocated "array" of size 'size'
int*array=newint[size];
for(inti=0;i<size;i++)
{

35

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

array[i]=i+1;
cout<<array[i]<<" ";
}
delete[]array;
return0;
}

 Explain Nested classes with examples

Nested Classes:
 Classes that are defined inside other classes are called nested classes
 Nested classes are considered to be within the scope of the enclosing class and
available for use within the scope
 The members of an enclosing class have no special access to members of a
nested class;the usual access rules shall be obeyed.
Example:
#include <iostream.h>
class Nest
{
public:
class Display
{
private:
int s;
public:
void sum( int a, int b)
{
s =a+b;
}
void show( )
{

36

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout << "\nSum of a and b is:: " << s;}


}
};
void main()
{
Nest::Display x;
x.sum(12, 10);
x.show();
}
O/P:
Sum of a and b is::22
In the above example, the nested class "Display" is given as "public" member of the
class "Nest".
2. Operator Overloading
 List the rules associated with operator overloading? What are the
operators that cannot be overloaded? Write a program to overload anyone of the
binary operators. April/May 2015
 Write a C++ program to overload the decrement operator with prefix and
postfix forms. May/June 2016
 Write a C++ program to overload the increment operator with prefix and
postfix forms. Nov/Dec 2015

C++ has the ability to provide the operators with a special meaning for a data type.
The mechanism of giving such special meanings to an operator is known as operator
overloading. To define an additional task to an operator, we must specify what it
means in relation to the class to which the operator is applied. This is done with the
help of a special function, which describes the task.

Operator Functions:

The general form of an operator function is

37

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

return type classname::operator op(arglist)


{
Function body
}
where return type is the type of the value returned by the specific operation and op is
the operator being overloaded. op is the function name and operator is the keyword.

Operator functions must be either member functions or friend functions. A basic


difference between them is a friend function will have one argument for unary
operators and two for binary operators. While a member function has no arguments
for unary operators and two for binary operators because the object is implicitly
passed as one argument in this case.

Invoking operator functions:

Unary operators:

op x or x op

Binary operators:

x op y

Types of operator overloading:

 Unary operator overloading:

 Unary operators operate on a single operand with the user defined data types.
 Examples of unary operator are:

38

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

o Unary Minus(-) operator


o Increment(++) and Decrement(--) Operator
o Logical not(!) operator

The increment and decrement operators fall into a special category because there are
two variants of each:

 Preincrement and postincrement


 Predecrement and postdecrement

When we write overloaded operator functions, it can be useful to implement separate


versions for the prefix and postfix versions of these operators. To distinguish between
the two, the following rule is observed: The prefix form of the operator is declared
exactly the same way as any other unary operator; the postfix form accepts an
additional argument of type int.

Program to overload the increment and decrement operator with prefix and
postfix forms:

class Point
{
int _x,_y;
public:
// Declare prefix and postfix increment operators.
Point& operator++(); // Prefix increment operator.
Point operator++(int); // Postfix increment operator.
// Declare prefix and postfix decrement operators.
Point& operator--(); // Prefix decrement operator.
Point operator--(int); // Postfix decrement operator.
// Define default constructor.

39

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Point() { _x = _y = 0; }
// Define parameterised constructor.
Point(int a,int b) { _x = a;_y = b; }
// Define accessor functions.
int x() { return _x; }
int y() { return _y; }
void show() { cout<<”(“<<_x<<”,”<<_y<<”)”<<endl;}
private:
int _x, _y;
};
// Define prefix increment operator.
Point& Point::operator++()
{
_x++;
_y++;
return *this;
}
// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
// Define prefix decrement operator.
Point& Point::operator--()
{
_x--;
_y--;
return *this;
}

40

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

// Define postfix decrement operator.


Point Point::operator--(int)
{
Point temp = *this;
--*this;
return temp;
}
main()
{
Point P1(2,3);
Point P2(3,4);
P1--;
P2--;
P1.show();
P2.show();
}
O/P:
(1,2)
(2,3)

P1 and P2 is decremented both in x and y co-ordinates.


Binary operator overloading:

Binary operator overloading operates on two operands with the user defined data
types. Here the first operand becomes the operator overloaded function caller and the
second is passed as an argument. Therefore overloading of operators must receive one
argument.
Examples:
 Arithmetic operators(+,-,*,/)
 Equality operators(==)

41

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

This program is used to add two complex number using operator


overloading.

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

class complex
{
int real;
int img;
public:
void getdata()
{
cout<<"Enter the real and img part";
cin>>real>>img;
}
void show()
{
cout<<"\n"<<real<<"+"<<img<<"i"<<"\n";
}
void operator+(complex c);
};
complex complex::operator+(complex c)
{
complex t;
t.real=real+c.real;
t.img=img+c.img;
return t;
}
void main()
{

42

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

clrscr();
complex c1,c2,c3;
c1.getdata();
c2.getdata();
c3=c1+c2;
cout<<"The complex number of c1:";
c1.show();
cout<<"The complex number of c2:";
c2.show();
cout<<"The result is:";
c3.show();
}
Output:
Enter the real and img part 4 5
Enter the real and img part 2 3
The complex number of c1:
4+5i
The complex number of c2:
2+3i
The result is:
6+8i
Rules associated with operator overloading:

 Only existing operators can be overloaded. New operators cannot be created.


 The overloaded operator must have atleast one operand that is of user defined
type.
 The basic meaning of an operator cannot be changed. That is the plus operator
cannot be used to subtract one value from the other.
 Overloaded operator follow the syntax rules of the original operators. They
cannot be overridden.
 There are some operators that cannot be overloaded. They are Size of, . ,: :,?:.

43

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Friend function cannot be used to overload certain operators ( = ,( ) ,[ ] ,-


>).However member functions can be used to overload them.
 Unary operators, overload by means of a member function, take no explicit
arguments and return no explicit values,but,those overloaded by means of a
friend function, take one reference argument.
 Binary operators overloaded through a member function take one explicit
argum ent and those which are overloaded through a friend function take two
explicit arguments.
 When using binary operator overloaded through a member function, the left
hand operand must be an object of the relevant class.
 Binary arithmetic operators such as +,-,*,and / must explicitly return a value.
They must not attempt to change their own arguments.

3. Inheritance – Single, Multilevel & Hierarchical

 Explain any two types of inheritance supported in C++ with suitable


examples May/June 2016

Inheritance is the most important property of object oriented programming which


supports reusability. It allows to extend the definition of a class without making the
physical changes to the existing class. The old class is referred to as base class and the
new one is called derived class.

Syntax for declaring the derived class:


class derived_class:member_access_specifier base_class
{

------

44

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The member access specifier be public, protected or private. This access specifier
describes the access level for the members that are inherited from the base class.

Types of Inheritance:
 Single Inheritance
 Multi-level Inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Single Inheritance:
Single Inheritance enables a derived class to inherit properties and behavior from a
single base class.
45

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Syntax:
class derivedclass:accessspecifier base_class
{
---
};

PROGRAM: PAYROLL SYSTEM USING SINGLE INHERITANCE:

#include<iostream.h>
#include<conio.h>
class emp
{
public:
int eno;
char name[20],des[20];
void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
};
class salary:public emp
{
float bp,hra,da,pf,np;
public:
void get1()
{
cout<<"Enter the basic pay:";

46

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
void display()
{

cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"
<<pf<<"\t"<<np<<"\n";
}
};
void main()
{
int i,n;
char ch;
salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();

47

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

s[i].calculate();
}
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for(i=0;i<n;i++)
{
s[i].display();
}
getch();
}
O/P:
Enter the Number of employee:1
Enter the employee No: 150
Enter the employee Name: ram
Enter the designation: Manager
Enter the basic pay: 5000
Enter the HR allowance: 1000
Enter the Dearness allowance: 500
Enter the profitability Fund: 300

E.No E.name des BP HRA DA PF NP


150 ram Manager 5000 1000 500 300 6200
In the above program, salary class is inherited from employee class.

Multilevel Inheritance:

In multllevel inheritance, a class is derived from another derived class.

Syntax:
class Base
{
----

48

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

};
class derived1:accessspecifier Base
{
----
};
class derived2:accessspecifier derived1
{
----
};

Program to create a programmer derived from employee which is himself


derived from person:

class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;

49

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<"Gender: "<<gender<<endl;
}
};

class employee: public person


{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};

class programmer: public employee


{
int number;
public:
void getdata()
{

50

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

employee::getdata();
cout<<"Number of programming language known: ";
cin>>number;
}
void display()
{
employee::display();
cout<<"Number of programming language known: "<<number;
}
};
int main()
{
programmer p;
cout<<"Enter data"<<endl;
p.getdata();
cout<<endl<<"Displaying data"<<endl;
p.display();
getch();
return 0;
}
Output
Enter data
Name: Karl Lens
Age: 31
Gender: Male
Name of Company: Dynamic Info
Salary: $21000
Number of programming language known: 4
Displaying data
Name: Karl Lens
Age: 31

51

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Gender: Male
Name of Company: Dynamic Info
Salary: $21000
Number of programming language known: 4
This program is an example of multiple inheritance. Here, programmer class is
derived from employee which is derived from person. Each class has required
attributes and methods. The public features of person is inherited by employee and the
public features of employee is inherited by programmer. The method getdata() asks
user to input data, while display() displays the data.
Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from one base class.
Syntax:
class base
{
----
};
class derived1:accessspecifier base
{
-----
};
class derived2:accessspecifier base
{
-----
};
Program to create Employee and Student inheriting from Person:
#include <iostream>
#include <conio.h>
class person
{
char name[100],gender[10];
int age;

52

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

public:
void getdata()
{
cout<<"Name: ";
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
class student: public person
{
char institute[100], level[20];
public:
void getdata()
{
person::getdata();
cout<<"Name of College/School: ";
gets(institute);
cout<<"Level: ";
cin>>level;
}
void display()
{

53

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};

class employee: public person


{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
int main()
{
student s;
employee e;
cout<<"Student"<<endl;

54

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<"Displaying data"<<endl;
s.display();
cout<<endl<<"Employee"<<endl;
cout<<"Enter data"<<endl;
e.getdata();
cout<<endl<<"Displaying data"<<endl;
e.display();
getch();
return 0;
}
Output
Student
Enter data
Name: John Wright
Age: 21
Gender: Male
Name of College/School: Abc Academy
Level: Bachelor
Displaying data
Name: John Wright
Age: 21
Gender: Male
Name of College/School: Abc Academy
Level: Bachelor
Employee
Enter data
Name: Mary White
Age: 24
Gender: Female

55

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Name of Company: Xyz Consultant


Salary: $29000
Displaying data
Name: Mary White
Age: 24
Gender: Female
Name of Company: Xyz Consultant
Salary: $29000
In this program, student and employee classes are derived from person. Person has
two public methods: getdata() and display(). These methods are inherited by
both student and employee. Input is given using getdata() method and displayed
using display() method. This is an example of hierarchical inheritance since
two classes are derived from a single class.

4. Inheritance – Multiple, Hybrid

 Illustrate any four types of inheritance supported in C++ with suitable


example Nov/Dec 2015
 Write a Program to illustrate the process of multi-level, multiple
inheritance concept of C++ language. Nov/Dec 2014

Multiple Inheritance:
When a class is derived from two or more base classes, such inheritance is
called Multiple Inheritance. It allow us to combine the features of several existing
classes into a single class.
Syntax:
class Derivedclass:Accessspecifier Base1,Accessspecifier Base2
{
----
----
};

56

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Program to display petrol's data using Multiple Inheritance from fuel and liquid:
#include <iostream>
#include <conio.h>
class liquid
{
float specific_gravity;
public:
void input()
{
cout<<"Specific gravity: ";
cin>>specific_gravity;
}
void output()
{
cout<<"Specific gravity: "<<specific_gravity<<endl;
}
};
class fuel
{
float rate;
public:
void input()

57

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
cout<<"Rate(per liter): $";
cin>>rate;
}
void output()
{
cout<<"Rate(per liter): $"<<rate<<endl;
}
};
class petrol: public liquid, public fuel
{
public:
void input()
{
liquid::input();
fuel::input();
}
void output()
{
liquid::output();
fuel::output();
}
};
int main()
{
petrol p;
cout<<"Enter data"<<endl;
p.input();
cout<<endl<<"Displaying data"<<endl;
p.output();
getch();

58

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

return 0;
}
Output
Enter data
Specific gravity: 0.7
Rate(per liter): $0.99
Displaying data
Specific gravity: 0.7
Rate(per liter): $0.99
In this program, petrol is derived from fuel having attribute rate and liquid having
attribute specific gravity. So the public features of both fuel and petrol are inherited to
petrol. Every class has a method named input() for providing input and another
method named output() to display the data.

Hybrid Inheritance:

Hybrid inheritance is combination of two or more inheritances such as


single,multiple,multilevel or Hierarchical inheritances.

Example:
Combination of multilevel and multiple inheritance

Program to display the result of students:


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

59

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
out<<"Roll no"<<rno<<"\n";
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports
{

60

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"sports:"<<score<<"\n";
}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}
int main()
{
clrscr();
result stu;
stu.get_no(123);

61

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}
OUTPUT:
Roll no 123
Marks obtained :
part1=27.5
Part2=33
Sports=6
Total score = 66.5

5. Polymorphism
 With suitable C++ program, explain how polymorphism is achieved at
compile time and run time. May/June 2016
 Write a C++ program to explain how the runtime polymorphism is
achieved
Nov/Dec 2015
Polymorphism means the ability to take more than one form. It gives different
meanings or functions to the operations or methods.
There are two types of polymorphism namely
 Compile Time Polymorphism:
For every function call compiler binds the call to one function definition at compile
time based on formal arguments of the function, their data type and their sequence.
Since the function call is determined during compilation, it is also called as Early
binding or Static binding. It is achieved using operator and function overloading.
Operator overloading is explained in the previous section with example.
Function Overloading:
Using the concept of function overloading, we can design a family of functions with
one function name but with different argument lists. The function would perform

62

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

different operations depending on the argument list in the function call. The correct
function is to be invoked is determined by checking the number and type of arguments
but not on the function type.

A function call first matches the prototype having the same number and type of
arguments and then calls the appropriate function for execution. The function
selection involves the following steps:
 The compiler first tries to find an exact match in which the types of actual
arguments are the same.
 If an exact match is not found, the compiler uses the integral promotions to the
actual arguments such as char to int, float to double
 When either of them fails, the compiler tries to use the built-in conversions to
the actual arguments and then uses the function whose match is unique. But if there
are multiple matches then the compiler will generate an error message.

Program to find the area of different shapes using function overloading

#include<iostream.h>
#include<conio.h>
const float pi=3.14;
float area(float n,float b,float h)
{
float ar;
ar=n*b*h;
return ar;
}
float area(float r)
{
float ar;
ar=pi*r*r;
return ar;

63

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
float area(float l,float b)
{
float ar;
ar=l*b;
return ar;
}
void main()
{
float b,h,r,l;
float result;
clrscr();
cout<<“\nEnter the Base & Height of Triangle: \n”;
cin>>b>>h;
result=area(0.5,b,h);
cout<<“\nArea of Triangle: “<<result<<endl;
cout<<“\nEnter the Radius of Circle: \n”;
cin>>r;
result=area(r);
cout<<“\nArea of Circle: “<<result<<endl;
cout<<“\nEnter the Length & Breadth of Rectangle: \n”;
cin>>l>>b;
result=area(l,b);
cout<<“\nArea of Rectangle: “<<result<<endl;
getch();
}
O/P:
Enter the Base & Height of Triangle:
2
3
Area of Triangle: 3

64

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Enter the Radius of Circle:


4
Area of Circle: 50.24
Enter the Length & Breadth of Rectangle:
2
3
Area of Rectangle: 6
In the above program, there are three functions having the same name “area” and each
one is distinguished by the number of arguments with respect to the shape(triangle,
rectangle or circle) for which the area has to be calculated. The respective function is
invoked by calling with the required number of arguments, one for circle, 3 for
triangle and 2 for rectangle.

 Run Time Polymorphism:


It allows binding to be delayed till run time. Since the function is linked with a
particular class much later after the compilation and during run time, it is called Late
binding or Dynamic binding. It is achieved through inheritance and virtual functions.

Virtual functions:
A virtual function is a member function in a base class that is declared using the
keyword virtual. When a class containing virtual function is inherited, the derived
class redefines the virtual function. The selection of the function to be called at any
given point in the program to be based on the kind of object for which it is called is
referred to as dynamic linkage or late binding.

Properties:
 Virtual functions must be member of some class.
 They cannot be static members and they are accessed by using object pointers.
 Virtual function in a base class must be defined.
 Prototypes of base class version of a virtual function and all the derived class
versions must be identical.

65

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 If a virtual function is defined in the base class, it need not be redefined in the
derived class
 Virtual constructors cannot be defined but Virtual destructors can be defined.

Program to illustrate virtual functions:


#include<iostream.h>
class B
{
public:
virtual void display()
{
cout<<”Content of base class\n”;
}
};
class D1:public B
{
public:
void display()
{
cout<<”Content of first derived class\n”;
}
};
class D2:public B
{
public:
void display()
{
cout<<”Content of second derived class\n”;
}
};
int main()

66

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
B *b;
D1 d1;
D2 d2;
b=&d1;
b->display();//calls display() of derived class D1
b=&d2;
b->display();//calls display() of derived class D2
return 0;
}
O/P:
Content of first derived class
Content of Second derived class.
Here the display function of the respective class is called by assigning the address of
the object of the class during run time. This is also called as Run Time Type
Identification (RTTI).

PART - C
1. Program - String handling
 Consider the following arithmetic expressions C=2+B and K=S-T, where
B,C,K,S and T are the objects of a class called ‘1D Array’. Write a program to
perform these operations by overloading the + and – operators appropriately.
Nov/Dec 2014

#include<iostream.h>
#include<conio.h>
#define size 10
Class DArray
{
int a[size];
int n;

67

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

public:
void getarray();
DArray operator+(int);
DArray operator-(DArray);
void display();
};
void DArray::getarray()
{
cout<<”Enter the number of elements\n”;
cin>>n;
cout<<”Enter the elements\n”;
for(int i=0;i<n;i++)
cin>>a[i];
}
DArray DArray::operator+(int b)
{
DArray t;
t.n=n;
for(int i=0;i<n;i++)
t.a[i]=a[i]+b;
return t;
}
DArray DArray::operator-(DArray x)
{
DArray t;
t.n=n;
for(int i=0;i<n;i++)
t.a[i]=a[i]-x.a[i];
return t;
}
void DArray::display()

68

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
cout<<”The Array Details\n”;
for(int i=0;i<n;i++)
cout<<a[i]<<”\t”;
}
void DArray::display()
{
cout<<”The Array details\n”;
for(int i=0;i<n;i++)
couy<<a[i]<<”\t”;
}
void main()
{
DArray B,C,K,S,T;
B.getarray();
S.getarray();
T.getarray();
C=B+2;
K=S-T;
Cout<<”C\n”
C.display();
Cout<<”K\n”
K.display();
getch();
}
O/P:
Enter the number of elements
4
Enter the elements
1 2 3 4
Enter the number of elements

69

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4
Enter the elements
1 2 3 4
Enter the number of elements
4
Enter the elements
1 2 3 4
C
The Array Details
3 4 5 6
K
The Array Details
0 0 0 0

2. Program - Constructor, Destructor


a. Define a class Shape with constructor, destructor and pure virtual functions
GetArea(), GetPerim() and Draw(). Derive classes Circle and Rectangle from
Shape. Derive another class Square from Rectangle. Implement this hierarchy
with essential functions and write a main. April/May 2015

class Shape
{
public:
Shape(){}
virtual ~Shape(){}
virtual float GetArea()=0;
virtual float GetPerim()=0;
virtual void Draw0=0;
};
class Circle:public Shape
{
int cradius,ccircum;
70

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

public:
Circle(float radius):cradius(radius){}
~Circle(){}
float GetArea()
{
return 3.14*cradius*cradius;
}
float GetPerim()
{
return 2*3.14*cradius;
}
void Draw()
{
cout<<”Circle Drawing\n”;
}
};
class Rectangle:public Shape
{
float len,wid;
public:
Rectangle(int l,int w):len(l),wid(w){}
virtual ~Rectangle()
float GetArea()
{
return len*wid;
}
float GetPerim()
{
return 2*len+2*wid;
}
virtual float GetLength()

71

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
return len;
}
virtual float GetWidth()
{
return wid;
}
void Draw();
};
void Rectangle::Draw()
{
for(int i=0;i<len;i++)
{
for(int j=0;j<wid;j++)
{
cout<<”x”;
}
cout<<”\n”;
}
}
class Square:public Rectangle
{
public:
Square(float l):Rectangle(float l,float l){}
Square(float l,float w):Rectangle(l,w)
{
if(GetLength()!=GetWidth())
cout<<”Error:Not a square but a rectangle”;
}
~Square(){}
float GetPerim()

72

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
return 4*GetLength();
}
};
void main()
{
Square s(5.5);
Circle c(2.5);
Rectangle r(2.5,2.5);
cout<<”The Area of the Square: ”<<s.GetArea()<<endl;
cout<<”The Perimeter of the Square: ”<<s.GetPerim()<<endl;
cout<<”The Area of the Rectangle: ”<<r.GetArea()<<endl;
cout<<”The Perimeter of the Rectangle: ”<<r.GetPerim()<<endl;
cout<<”The Area of the Circle: ”<<c.GetArea()<<endl;
cout<<”The Perimeter of the Circle: ”<<c.GetPerim()<<endl;
}
O/P:
The Area of the Square: 30.25
The Perimeter of the Square: 22
The Area of the Rectangle: 5.5
The Perimeter of the Rectangle: 10
The Area of the Circle: 19.62
The Perimeter of the Circle: 15.7

b. Define a class Area to identify the area of square and rectangle using
constructor and destructor. Use parameters length(l) and breadth (b) for
constructor functions
April/May 2015
(or)
Write a program to perform dynamic initialization of objects Nov/Dec 2014
class area
{

73

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

int l,b,a;
public:
area(int l,int b)
{
a=l*b;
}
area(int l)
{
a=l*l;
}
void disparea()
{
cout<<”Area is%d\n”,a);
};
void main()
{
Area A(5,2),B(5);
cout<<”rectangle\n”;
A.disparea();
cout<<”square\n”;
B.disparea();
}
O/P:
rectangle
Area is10
square
Areas is 25

74

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

3. Copy Constructor
a. Write an object oriented program in C++ that prints the student details using
a copy constructor and a destructor member function

#include<iostream.h>
#include<conio.h>
class student
{
private:
int roll, marks, age;
public:
student(int r,int m,int a) //parameterized constructor
{
rol l = r;
marks = m;
age = a;
}
student(student &s) //copy constructor
{
roll = s.roll;
marks = s.marks;
age=s.age;
}
void display( )
{
cout<<"Roll number :" <<roll <<endl;
cout<<"Total marks :"<<marks<<endl;
cout<<"Age:"<<age<<endl;
}
};
int main( )
{
75

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

clrscr();
student t(3,350,17);
student k(t); // invokes copy constructor
cout<<"\nData of student t:"<<endl;
t.display();
cout<<"\n\nData of student k:"<<endl;
k.display();
getch();
return 0;
}
The output of the above program will be like this:
Data of student t :
Roll number : 3
Total marks : 350
Age : 17
Data of student k :
Roll number : 3
Total marks : 350
Age : 17
The statements
student t(3,350,17); //invokes parameterized constructor
student k = t; //invokes copy constructor
Initializes one object k with another object t. The data members of t are copied
member by member into k. When we see the output of the program we observe that
the data of both the objects t and k are same.

b. Write a Program to perform string copy and concatenate operation using


dynamic constructor Nov/Dec 2014

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

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

class str
{
char *name;
int len;
public:
str()
{
len=0;
name=newchar[len+1];
}
str(char *s)
{
len=strlen(s);
name=newchar[len+1];
strcpy(name,s);
}
void show()
{
cout<<"NAME IS:->"<<name<<endl;
}
void join(str &a,str &b);
};
void str::join(str &a,str &b)
{
len=a.len+b.len;
delete name;
name=new char[len+1];
strcpy(name,a.name);
strcat(name,b.name);
};
main()

77

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
clrscr();
char *first="HARSHIL";
str n1(first),n2("NINAD"),n3("PRATIK"),n4,n5;
n4.join(n1,n2);
n5.join(n4,n3);
n1.show();
n2.show();
n3.show();
n4.show();
n5.show();
}
O/P:
NAME IS:->HARSHIL
NAME IS:->NINAD
NAME IS:->PRATIK
NAME IS:-> HARSHIL NINAD
NAME IS:-> HARSHIL NINAD PRATIK

4. Friend Function - Program


 Write a C++ program to overload ‘+’ operator to add two objects of a
class using friend function April/May 2015

#include<iostream.h>
class A
{
int a;
public:
A(int b){a=b;}
friend A operator+(A,A);
void display()
{
78

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<a<<endl;
}
};
A operator+(A x,A y)
{
A t;
t.a=x.a+y.a;
return t;
}
void main()
{
A x(5),y(6),z;
z=x+y;
z.display();
}
O/P:
11
Friend function takes in two objects and adds them and returns the result

79

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT-III
C++ PROGRAMMING ADVANCED FEATURES

Abstract class – Exception handling – Standard libraries – Generic Programming –


templates – class template – function template – STL – containers – iterators –
function adaptors – allocators – Parameterizing the class – File handling concepts.

PART-A

1. What is the significance of iterators? Nov/Dec 2014


 Iterators are pointers like entities that are used to access individual elements in
a container
 Iterators are used to move sequentially element by element to the container
 Iterators are of 5 types
o Input
o Output
o Forward
o Bidirectional
o Random access

2. Give an example on function template Nov/Dec 2014


Write a function template that swaps values of two variables
May/June 2013
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp=x;
x=y;
y=temp;

80

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
void fun(int a,int b,float c,float d)
{
cout<<"\na and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\na and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\nc and d after swaping :"<<c<<"\t"<<d;
}

void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}

Output:

Enter A, B values (integer): 10 20


Enter C, D values (float): 2.50 10.80

A and B before swapping: 10 20


A and B after swapping: 20 10

81

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

C and D before swapping: 2.50 10.80


C and D after swapping: 10.80 2.50

3. Give the various file stream classes needed for file manipulation
April/May 2015
a. ifstream – input file stream
b. ofstream – output file stream
c. fstream – input/output file stream

4. Is abstract base class used to create objects? Justify your answer in brief
April/May 2015
Abstract base class is the base class containing atleast one pure virtual function.
virtual return_type func_name()=0;
Objects cannot be created for this class. Abstract classes are used to provide only an
Interface for its sub classes. Derived classes should implement the functions.

5. Compare Overloaded functions Vs Function templates Nov/Dec 2015


Overloaded Functions Function Templates
Two or more functions can have the same Ability to define functions with generic
name if their parameters are different; types, known as function templates. This
either because they have a different allows a function to work on many
number of parameters, or because any of different data types without being
their parameters are of a different type. rewritten for each one.
int operate (int a, int b) template <class T>
{ T sum (T a, T b)
return (a*b); {
} T result;
double operate (double a, double b) result = a + b;
{ return result;
return (a/b); }

82

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
The compiler knows which one to call in Instantiating a template is applying the
each case by examining the types passed template to create a function using
as arguments when the function is called. particular types or values for its template
parameters.
operate(5,6) – operate(int,int) is called x = sum<int>(10,20);
by using int as template argument in the
call, the compiler automatically
instantiates a version of sum

6. When do we use multiple catch handlers? Nov/Dec 2015


Write down the syntax of try-catch and throw in exception handling
April/May 2015
It is possible that a program segment has more than one condition to throw an
exception. In such case we can associate more than one catch statement with a try
block as shown below.
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}

catch(typen arg)

83

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
//catch blockn
}

7. Distinguish the term template class and class template. May/June 2016
Template class: A generic definition or a parameterized class not instantiated until the
client provides the needed information. Its jargon for plain templates.
Class template: A class template specifies how individual classes can be constructed
much like the way a class specifies how individual objects can be constructed. Its
jargon for plain classes.

8. List out the types of containers. May/June 2016


List any two containers in STL May/June 2013
a. Sequence containers - array,vector
b. Associative Containers – set,map
c. Derived Containers (or) Container Adaptors – stack,queue

9. What is file mode? List any for file modes. Nov/Dec 2010
When a file is opened, it must be specified how it is to be opened. This means
whether to create it from new or overwrite it and whether it's text or binary, read or
write and if the content is to be appended to it.
In order to open a file with a stream object open() member function is used.
open (filename, mode);
ios::ate
Write all output to the end of file (even if file position pointer is moved with
seekp)
ios::app
Open a file for output and move to the end of the existing data (normally used
to append data to a file, but data can be written anywhere in the file)
ios::in
The original file (if it exists) will not be truncated

84

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

ios::out
Open a file for output (default for ofstream objects)

10. List the advantages of generic programming Nov/Dec 2013


What is a template? What are their disadvantages? Nov/Dec 2012
Generic programming is a data structure-independent way of developing and
delivering algorithms that need not be bound to a specific object and datatype. It is
achieved using class templates and function templates.
 Example: stack class can be created for int, float, char etc. with a single
implementation

11. What are function adaptors?


The function adapters are the predefined set of functions in standard template library
which will be used to change the function to perform function composition and
binding. Using function adaptors the functions can be combined, transformed, or
manipulated by some value or by using some another functionality. The function
adaptors make use of function objects. The function objects are also known as
functors.
PART-B
1. Exception Handling

 What is an exception? Explain how the control is transferred and handled


in C++ programs April/May 2015
 Illustrate about how exceptions are handled using multiple catch handle
May/June 2016
 Write a program to illustrate the concept of re-throwing an exception
Nov/Dec 2014
 Write a C++ program to handle a divide by zero exception Nov/Dec 2015

Exceptions:
Exceptions are runtime anomalies or unusual conditions that a program may encounter
while executing. Anomalies might include conditions such as division by zero, access
to an array outside of its bounds, or running out of memory or disk space.
Exception Handling:

85

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The purpose of the exception handling mechanism is to provide means to detect and
report an “exceptional circumstance” so that appropriate action can be taken. The
mechanism suggests a separate error handling code that performs the following tasks:
 Find the problem(hit the exception)
 Inform that an error has occurred(throw the exception)
 Receive the error information(catch the exception)
 Take corrective actions(handle the exception)

Mechanism:

Exception handling is done using the following elements


 Try block
o Try block identifies a block of code in which particular exceptions will
be activated. This is done using “try” keyword.
 Catch block
o Program catches an exception with an exception handler at the place
required to handle the problem. This is done using a “catch” keyword.
Catch block can catch exceptions of all types.
o If an exception is thrown in a try block then the remaining statements in
that try block are ignored. The program searches catch blocks in order,
looking for appropriate exception handler.
o If the type of throw exception matches the parameter type then the code
of that catch block executes and ignores other catch blocks.
 Throw expression:
o An exception is thrown from the try block using “throw” keyword.

86

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Program to illustrate exception handling(Divide by zero error):


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;

try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}

catch(int i)
{

87

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<"Answer is infinite because a-b is:"<<i;


}

getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40

Answer is infinite because a-b is: 0

In the above program a-b evaluating to zero is the exception handled as it is in the
denominator leading to infinite result. Catch block is executed after the throw
statement gets executed. Thus the exception is handled.

Multiple Catch statements:

It is possible that a program segment has more than one condition to throw an
exception. In such case we can associate more than one catch statement with a try
block as shown below.
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}

88

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

catch(typen arg)
{
//catch blockn
}

When an exception is thrown, the handlers are searched to find the appropriate match.
The first handler(catch block) that matches gets executed and then the control goes
after the last catch block.

Program using multiple catch handlers:

#include<iostream.h>
void main() {
int numerator, denominator, result;
cout <<"Enter the Numerator:";
cin>>numerator;
cout<<"Enter the denominator:";
cin>>denominator;
try {
if(denominator == 0) {
throw denominator;
} else if (denominator < 0) {
throw "Negative denominator not allowed";
}
result = numerator/denominator;
cout<<"\nThe result of division is:" <<result;
}
catch(int num) {
cout<<"You cannot enter "<<num<<" in denominator.";
}
catch (char* message) {

89

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<message;
}
}
O/P:
Enter the Numerator: 10
Enter the denominator: -4
Negative denominator not allowed.

Here as the denominator is –ve and a string message is thrown. The matching catch
handler is executed and the message is displayed.

Re-throwing an exception:

A handler may decide to re-throw the exception caught without processing it. In such
situations throw statement is used without any arguments.
throw;
This causes the current exception to be thrown to the next enclosing try/catch
sequence and is caught by the catch statement after the try block. When an exception
is re-thrown it will not be caught by an appropriate catch in the outer try/catch
sequence only.
Example:

#include <iostream>
using namespace std;
void MyHandler()
{
try
{
throw “hello”;
}
catch (const char*)

90

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
cout <<”Caught exception inside MyHandler\n”;
throw; //rethrow char* out of function
}
}
int main()
{
cout<< “Main start”;
try
{
MyHandler();
}
catch(const char*)
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
Output :
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
2. Components of STL(Standard Template Library)

 Describe the components of STL


Nov/Dec2015,May/June2016,April/May 2015
 What is STL? Brief on its key components and their types. Nov/Dec 2014

91

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

A set of general purpose templatized classes and functions that could be used as
standard approach for storing and processing data has been developed. The collection
of these generic classes and functions is called the Standard Template Library.
STL Components:

 Container
 Algorithm
 Iterator

Container:

A container is an object that actually stores data. It is a way data is organized in


memory. The STL containers are implemented by template classes and
therefore can be easily customized to hold different types of data.
The STL contains three types of containers

1)Sequence containers
2)Associative containers
3)Derived containers

Sequence Container:

Sequence containers store elements in a linear sequence, like a line. Each


element is related to other elements by its position along the line. They all expand
themselves to allow insertion of elements and all of them support a number of
operations on them.

Element 0 Element 1 Last element


……

iterator
begin()

92

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

There are three types of sequence containers:

1) Vector - static contiguous array


2) list - dynamic contiguous array
3) deque - Double ended queue

Elements in all these containers can be accessed using an iterator. The difference
between three of them are related by the performances.

Container Random access Insertion or Insertion or


deletion in the deletion at the end
middle
Vector Fast Slow Fast at back
List Slow Fast Fast at front
Deque Fast Slow Fast at both the
ends

Associative containers:

Associative containers are designed to support direct access to elements using


keys. They are not sequential. There are four types of associative containers.

1) Set
2) Multiset
3) Map
4) Multimap

All these containers store data in a structure called tree which facilitates fast
searching, deletion and insertion. However these are very slow for random access and
inefficient for sorting.

93

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Containers set and multiset can store a number of items and provide operations for
manipulating them using the values as keys. For example, a set might store objects of
the student class which are ordered alphabetically using names as keys. Multi set
allows duplicate items.

Containers Map and Multimap are used to store pirs of items one called the key and
the other called the value. We can manipulate the values using the keys associated
with them. the values are called mapped values. Multimap permits multiple keys .

Derived Container:

The derived containers do not support iterators and therefore we cannot use
them for data manipulation. They support two member functions pop() and push() for
implementing deleting and inserting operations. They are also called container
adaptors. They provide three derived containers.

They are
1)Stack - Last in First Out Data Structure
2)Queue - First in First Out Data Structure
3)Priority_queue - Highest priority elements are removed

Program to use vector

// C++ STL vector example


#include <iostream>
// vector header file
#include <vector>
using namespace std;
int main(void)
{

94

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

// vector container for integer elements declaration


vector<int> coll;
// using the for loop as the iterator
unsigned int i;

// append elements with values 1 to 10


for(i=1; i <= 10; ++i)
coll.push_back(i);

// print all elements separated by a space


cout<<"coll vector data: ";
for(i=0; i < coll.size(); ++i)
cout<<coll[i]<<" ";
cout<<endl;
return 0;
}

Output examples:

coll vector data: 1 2 3 4 5 6 7 8 9 10


Press any key to continue . . .

Program to use stack container

#include<iostream.h>
void main()
{
stack<string> allwords;
string word;
while(cin>>word)
{

95

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

allwords.push(word);
}
cout<<"Number of words="<<allwords.size()<<endl;
while(!allwords.empty())
{
cout<<allwords.top()<<endl;
allwords.pop();
}
return 0;
}
O/P:
World
Welcome
Number of words =2
Welcome
World

Algorithm:
Algorithms is a procedure that is used to process the data contained in the
containers. The STL includes many different kinds of algorithms to provide support to
tasks such as initializing, searching, copying, and sorting and merging.

Iterator:
An iterator is an object that points to an element in a container. We can use
iterators to move through the contents of containers. Iterators are handled just like
pointers.

Iterators are divided into five categories.


Iterators Descriptions
Input Can read from them
Output Can write to them

96

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Forward Forward iterators are limited to one direction


Bidirectional Can be iterated in both the directions
Randomaccess It is bidirectional and provides the functionality as pointers

Example:
using namespace std;

void main()
{
vector<int> myIntVector;
vector<int>::iterator myIntVectorIterator;

// Add some elements to myIntVector


myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);

for(myIntVectorIterator = myIntVector.begin();
myIntVectorIterator != myIntVector.end();
myIntVectorIterator++)
{
cout<<*myIntVectorIterator<<" ";
}
}
O/P: 1 4 8
3. Generic Programming/Class Templates,Function Templates &
Parameterizing the Class
 Write a Class template to represent a stack of any possible data type.
Nov/Dec 2015
 Write a function template to find the minimum element in an array
Nov/Dec 2014

97

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Templates is a concept in C++ which enables us to define generic classes and


functions and thus provide generic programming. Generic programming is an
approach where generic types are used as parameters in algorithms so that they work
for a variety of suitable data types and data structures.
For example, a class template for an array class would enable us to create
arrays of various data types such as int array and float array. Similarly function
template can be defined to create various versions of say mul() for multiplying
int,float and double type values.

Since a template is defined with a parameter that would be replaced by a


specific data type at the time of actual use of the class or function the templates are
called parameterized classes or functions.

Class template:

A class template provides a specification for generating classes based on parameters.


A class template is instantiated by passing a given set of types to it as template
arguments.

Syntax:

template<class T>
class classname
{
…..
};

Example:

Program to implement stack using class template:

98

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

#include<iostream>
using namespace std;

template<class T>
class stack{
T* arr;
static int top;
public:
stack(int);
void push(T);
T pop();
bool empty();
};

template<class T>
int stack<T>::top = -1;

template<class T>
stack<T>::stack(int x){
arr = new T(x);
}

template<class T>
void stack<T>::push(T a){
arr[++top] = a;
}

template<class T>
T stack<T>::pop(){
T a = arr[top--];
return a;

99

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

template<class T>
bool stack<T>::empty(){
return (top==-1);
}

int main(){
stack<int> s(10);
int i;
for(i=0;i<10;i++){
s.push(i);
}
while(!s.empty()){
cout<<s.pop()<<endl;
}
return 0;
}
O/P:
9
8
7
6
5
4
3
2
1
0

100

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

In the above program generic stack class is created using template. In the main
function stack object is instantiated using stack<int> s(10). Thus integer stack is
created. 10 elements from 0 to 9 is pushed into the stack and the elements are popped
and displayed.

Function Template:
Function template can be used to create a family of functions based on the
same code with different argument types. The compiler will automatically instantiate
the function to handle each type of call based on the argument list.

Syntax:
template<class T>
returntype functionname(arguments of type T)
{
// Body of the function
}

Example:
Program to find the minimum in the array
#include <iostream.h>
#include <conio.h>

template <class T>


T findMin(T arr[],int n)
{
int i;
T min;
min=arr[0];
for(i=0;i<n;i++)
{
if(arr[i]<min)

101

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

min=arr[i];
}
return(min);
}
void main()
{
clrscr();
int iarr[5];
char carr[5];
double darr[5];

cout << "Integer Values \n";


for(int i=0; i < 5; i++)
{
cout << "Enter integer value " << i+1 << " : ";
cin >> iarr[i];
}

cout << "Decimal values \n";


for(int k=0; k < 5; k++)
{
cout << "Enter decimal value " << k+1 << " : ";
cin >> darr[k];
}
//calling Generic function...to find minimum value.
cout<<"Generic Function to find Minimum from Array\n\n";
cout<<"Integer Minimum is : "<<findMin(iarr,5)<<"\n";
cout<<"Double Minimum is : "<<findMin(darr,5)<<"\n";

getch();
}

102

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

O/P:
Generic Function to find Minimum from Array

Integer Values:
Enter integer value 1: 22
Enter integer value 2: 8
Enter integer value 3: 12
Enter integer value 4: 4
Enter integer value 5: 32
Integer Minimum is : 4
Decimal values
Enter decimal value 1: 22
Enter decimal value 2: 22
Enter decimal value 3: 22
Enter decimal value 4: 22
Enter decimal value 5: 22
Decimal Minimum is : 4

In the above program function template is defined for finding the minimum in an array
of various data types. It is tested for int and double data type.

Parameterizing the Class:

We can use more than one generic data type in a class template. They are declared as a
comma seperated list within the template specification as shown below:
template<class T1, class T2,…>
class classname
{
….
….
};

103

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Program to illustrate the parameterized class:

#include<iostream.h>
using namespace std;
template<class T1,class T2>
class test
{
T1 a;
T2 b;
public:
Test(T1 x,T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<"and"<<b<<endl;
}
};
void main()
{
Test<float,int> test1(1.5,34);
cout<<"test1:"
test1.show();
cout<<"test2:"
Test<int,char> test2(45,'A');
test2.show();
}

104

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

O/P:
test1: 1.5 and 34
test2: 45 and A

Test class accepts two parameters of different types as input.

4. File Handling Concepts

 Explain in detail the file handling concepts available in C++.


 Write a program to read a string to store it in a file and read the same
string from the file and display it on the output device. Nov/Dec 2014

File handling:

File Stream Classes:

ios (General input/output stream class)


 Contains basic facilities that are used by all other input and output classes.
 Also contains a pointer to a buffer object(streambuf object).
 Declares constants and functions that are necessary for handling formatted
input and output operation.
istream(input stream)
 Inherits the properties of ios
 Declares input functions such as get(),getline() and read().
 Contains overloaded extraction operator.

ostream(output stream)
 Inherits the properties of ios
 Declares output functions such as put() and write().
 Contains overloaded initiation operator.
iostream(input/output stream)
105

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Inherits the properties of ios, istream and ostream through multiple inheritance
and thus contains all the input and output functions.

Streambuf
 Provides an interface to physical devices through buffers.
 Acts as a base for filebuf class used ios files.
File Modes:
When a file is opened, it must be specified how it is to be opened. This means
whether to create it from new or overwrite it and whether it's text or binary, read or
write and if the content is to be appended to it.
In order to open a file with a stream object open() member function is used.
open (filename, mode);
ios::ate
Write all output to the end of file (even if file position pointer is moved with
seekp)
ios::app
Open a file for output and move to the end of the existing data (normally used
to append data to a file, but data can be written anywhere in the file
ios::in
The original file (if it exists) will not be truncated
ios::out
Open a file for output (default for ofstream objects)
ios::trunc
Discard the file's contents if it exists (this is also the default action for ios::out,
if ios::ate, ios::app, or ios::in are not specified)
ios::binary
Opens the file in binary mode (the default is text mode)
ios::nocreate
Open fails if the file does not exist
ios::noreplace
Open fails if the file already exists.

106

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

File Pointers:
Each file has two associated pointers known as file pointers. These pointers are
used to move through the files while reading or writing.
 Input or get pointer – specifies the location in a file where the next read
operation will occur.
 Output or put pointer – specifies the location in a file where the next write
operation will occur.

Example:

Program to write,read, add and modify records in a file:


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
static int totrec=0;
int main(void){
int choice;
while(1){
clrscr();
cout<<"Choose your choice\nNOTE : one choice for one record(except viewing
data)\n";
cout<<"1) Scanning initial records\n";
cout<<"2) Appending records\n";
cout<<"3) Modifying or append records\n";
cout<<"4) Viewing records\n";
cout<<"5) Exit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch (choice){

107

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

case 1 :
{
ofstream outfile;
outfile.open("emp",ios::out);
cout<<"\n\nPlease enter the details as per demanded\n";
cout<<"\nEnter the name : ";
char name[20];
cin>>name;
outfile<<name<<endl;
cout<<"Enter Age : ";
int age;
cin>>age;
outfile<<age<<endl;
cout<<"Enter programming language known by him\her : ";
char lang[25];
cin>>lang;
outfile<<lang<<endl;
totrec= totrec + 1;
outfile.close();
}
break;
case 2 :
{
ofstream outfile;
outfile.open("emp",ios::app);
cout<<"\n\nPlease enter the details as per demanded\n";
cout<<"\nEnter the name : ";
char name[20];
cin>>name;
outfile<<name<<endl;
cout<<"Enter Age : ";

108

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

int age;
cin>>age;
outfile<<age<<endl;
cout<<"Enter programming language known by him\her : ";
char lang[25];
cin>>lang;
outfile<<lang<<endl;
totrec = totrec + 1;
outfile.close();
}
break;
case 3 :
{
ofstream outfile;
outfile.open("emp",ios::ate);
cout<<"Are you interested in adding record\nenter y or n\n";
char ans;
cin>>ans;
if(ans=='y' || ans=='Y')
{
cout<<"\n\nPlease enter the details as per demanded\n";
cout<<"\nEnter the name : ";
char name[20];
cin>>name;
outfile<<name<<endl;
cout<<"Enter Age : ";
int age;
cin>>age;
outfile<<age<<endl;
cout<<"Enter programming language known by him : ";
char lang[25];

109

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cin>>lang;
outfile<<lang<<endl;
totrec = totrec + 1;
}
outfile.close();
}
break;
case 4 :
{
ifstream infile;
infile.open("emp",ios::in);
const int size=80;
char line[size];
int counter=totrec;
while(counter > 0)
{
infile.getline(line,size);
cout<<"\n\nNAME : "<<line<<endl;
infile.getline(line,size);
cout<<"AGE : "<<line<<endl;
infile.getline(line,size);
cout<<"LANGUAGE : "<<line<<endl;
counter--;
}
infile.close();}
getch();
break;
case 5 :
exit(0);
} }}

110

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Write a program to read a string to store it in a file and read the same
string from the file and display it on the output device. Nov/Dec 2014

#include <fstream.h>

#include <iostream.h>

#include <string.h>

std::string s="hello world\n";

std::ofstream os("filename.txt");

cout<<"Writing to a file\n";

if (! os) { std::cerr<<"Error writing to ..."<< std::endl; } else {

os << s;

os.close();

ifstream is("filename.txt");

cout<<"Reading from file\n";

is>>s;

cout<<s<<endl;

O/P:

hello world

5. Function Adaptors & Allocators


 Explain in detail Function Adaptors and Allocators.
Function Adaptors: A function adaptor is an instance of a class that adapts a global
or member function so that the function can be used as a function object (a function
adaptor may also be used to alter the behavior of a function or function object
 Each function adaptor provides a constructor that takes a global or member
function.

111

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The adaptor also provides a parenthesis operator that forwards its call to that
associated global or member function.

STL has predefined function adaptors that will change their function objects(also
called functors) to perform function composition and binding

STL function adaptors include:

 Binders
o A binder can be used to transform a binary function object into an unary
function objects by acting as converter between the function object and an
algorithm
o Binder always store both the binary function object and the argument
internally.

Two forms of binding are:

bind1st(op,Arg) – calls op with „Arg‟as its first parameter


bind2nd(op,Arg)-calls op with „Arg‟ as its second parameter

Example:

include <iostream>
#include <algorithm>
#include <functional>
#include <vector>

using std::cout;
using std::endl;
typedef std::vector <int>::const_iterator const_iterator;

void print(const std::vector <int>& v)

112

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector <int> v(10);
const_iterator p;

for(int i = 0; i < 10; i++)


{
v[i] = i % 8;
}
cout << "Vector : ";
print(v);
p = find_if(v.begin(), v.end(), std::bind1st(std::greater <int>(), 7));
if (p != v.end())
{
std::cout << "Element less than or equal to 7 => "
<< *p << " at position " << p - v.begin() + 1
<< std::endl;
}
else
{
std::cout << "No element less than or equal to 7"
<< std::endl;
}

113

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

p = find_if(v.begin(), v.end(), std::bind1st(std::less <int>(), 7));


if (p != v.end())
{
std::cout << "Element greater than or equal to 7 => "
<< *p << " at position " << p - v.begin() + 1
<< std::endl;
}
else
{
std::cout << "No element greater than or equal to 7"
<< std::endl;
}
}
This C++ program demonstrates the usage of bind1st binder. The program binds the
first parameter of the binary predicate greater and less to 7. A vector of integers is
instantiated and whether there is an element greater than 7 and any element equal to 7
is determined.

 Negators
The negator function adaptor can be used to store the opposite result of a function
object.

Two functions of negators are:

- not1(op) negates the result of unary op


-not2(op) negates the result of binary op

Example:
#include<iostream.h>
using namespace std;
void main()

114

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
int arr[] ={6,7,8,9,10};
cout<<count_if(Arr,Arr+5not1(bind2nd(greater_equal<int>(),8)));
}
O/P:
2

 Member function:
o It can be used to allow class member functions as arguments to STL predefined
algorithms.
o Mem_fun(PtrTo member mf)
Converts a pointer to member to a function object whose first argument is a
pointer to the object

Allocators:
 Allocators are classes that define memory models to be used by STL
containers.
 Allocators save as an abstraction to translate the need to use memory into a
raw call for memory.
 It simply separates the implementation of containers which need to allocate
memory dynamically.

Example program:
#include <memory>
#include <iostream>
#include <string>
int main()
{
std::allocator<int> a1; // default allocator for ints
int* a = a1.allocate(10); // space for 10 ints
a[9] = 7;
std::cout<< a[9] << '\n';

115

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

a1.deallocate(a, 10);
// default allocator for strings
std::allocator<std::string> a2;
// same, but obtained by rebinding from the type of a1
decltype(a1)::rebind<std::string>::other a2_1;
// same, but obtained by rebinding from the type of a1 via allocator_traits
std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;
std::string* s = a2.allocate(2); // space for 2 strings
a2.construct(s, "foo");
a2.construct(s + 1, "bar");
std::cout<< s[0] << ' ' << s[1] << '\n';
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocate(s, 2);
}
O/P:
7
foo bar
PART - C
1. Programs in Templates & File handling

 Write a template function to sort the elements in an array April/May 2015


 Write a function template for finding the maximum value in an array
Nov/Dec 2015
 Write a class template to represent a queue of any possible data type.
May/June 2016
 Write a C++ program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is replaced by a
single space. May/June 2016
 Write a program to write the text in a file. Read the text from the file from
the end of file. Display the contents of file in reverse order. Append the contents
to the existing file. April/May 2015

116

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

1. Write a template function to sort the elements in an array.

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

template<class bubble>
void bubble(bubble a[], int n)
{
int i, j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
bubble element;
element = a[i];
a[i] = a[j];
a[j] = element;
}
}
}
}

void main()
{
int a[6]={1,2,3,4,4,3};
char b[4]={'s','b','d','e'};
clrscr();
bubble(a,6);
cout<<"\nSorted Order Integers: ";
117

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

for(int i=0;i<6;i++)
cout<<a[i]<<"\t";
bubble(b,4);
cout<<"\nSorted Order Characters: ";
for(int j=0;j<4;j++)
cout<<b[j]<<"\t";
getch();
}
O/P:

Sorted Order Integers: 1 2 3 3 4 4

Sorted Order Characters: b d e s

2. Write a function template for finding the maximum value in an array

#include <iostream>
using std::cout;
using std::endl;
template<class T> T max(const T* data, int size) {
T result = data[0];
for(int i = 1 ; i < size ; i++)
if(result < data[i])
result = data[i];
return result;
}
int main() {
double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
int numbers[] = {2, 22, 4, 6, 122, 12, 1, 45};
const int dataSize = sizeof (data)/sizeof(data[0]);
cout << "Maximum double is " << max(data, dataSize) << endl;
118

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

const int numbersSize = sizeof numbers/sizeof numbers[0];


cout << "Maximum integer is " << max(numbers, numbersSize) << endl;
return 0;
}

O/P:

Maximum double is 4.6


Maximum integer is 122
3. Write a class template to represent a queue of any possible data type.

#include<iostream>
#include<stdlib.h>
#include<process.h>
using namespace std;
template<class T>
class Queue
{
private:
int front,rear;
T *queue;
int maxsize;
public:
Queue(int maxqueuesize)
{
front=0;
rear=-1;
maxsize=maxqueuesize;
queue=new T[maxsize];
}
~Queue()

119

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
delete[] queue;
}
int isempty();
int isfull();
void insert();
void deletion();
void atfront();
void atrear();
void display();
};
template<class T>
int Queue<T>::isempty()
{
if(front==0&&rear==-1||front==rear)
return 1;
else
return 0;
}

template<class T>
int Queue<T>::isfull()
{
if(rear==maxsize-1)
return 1;
else
return 0;
}
template<class T>
void Queue<T>::atfront()
{

120

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

if(isempty())
cout<<"\nSorry the queue is empty!";
else
cout<<"\nFront element of the queue is : "<<queue[front];
}
template<class T>
void Queue<T>::atrear()
{
if(isempty())
cout<<"\nSorry the queue is empty!";
else
cout<<"\nRear element of the queue is : "<<queue[rear];
}

template<class T>
void Queue<T>::insert()
{
T ele;
if(isfull())
cout<<"\nSorry the queue is full!";
else
{
cout<<"\nEnter the element to insert : ";
cin>>ele;
queue[++rear]=ele;
}
}
template<class T>
void Queue<T>::deletion()
{
if(isempty())

121

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

cout<<"\nSorry the queue is empty!";


else
cout<<"\nDeleted element of the queue is : "<<queue[front++];
}
template<class T>
void Queue<T>::display()
{
if(isempty())
cout<<"\nSorry the queue is empty!";
else
{
cout<<"\nQueue elements are : ";
for(int i=front;i<=rear;i++)
{
cout<<"\t"<<queue[i];
}
}
}

int main()
{
int ch;
Queue<int> q(10);
do
{
cout<<"\n 1.Insertion \n 2.Deletion \n 3.Display Front Element \n 4.Display
Rear Element \n 5.Display Queue \n 6.Exit \n";
cout<<"Enter your Choice:";
cin>>ch;
switch(ch)
{

122

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

case 1:
q.insert();
break;
case 2:
q.deletion();
break;
case 3:
q.atfront();
break;
case 4:
q.atrear();
break;
case 5:
q.display();
break;
case 6:
exit(0);
break;
default: cout<<"\nWrong Choice Entered!";

}
}while(ch<=6);
system("pause");
return 0;
}
4. Write a C++ program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is replaced by a
single space.

#include<fstream.h>
#include<iostream.h>

123

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

#include<process.h>
#include<conio.h>
void main()
{
clrscr();
ifstream file1;
ofstream file2;
char sfile[13],tfile[13];
cout<<"\nEnter Source file name-";
cin>>sfile;
cout<<"\nEnter Target file name-";
cin>>tfile;
file2.open(sfile);
file2<<"\nMy Name isRAHUL KUMAR"<<endl;
file2.close();
file1.open(sfile);
file2.open(tfile);
if(!file1)
{
cerr<<" Some Error..";
exit(1);
}
char varch,p=file1.get();
while(!file1.eof())
{
file2.put(p);
varch=file1.get();

if(p==' ' && varch==' ')


{
p=varch;

124

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

varch=file1.get();
}
p=varch;

}
cout<<"\ncopied......";
file1.close();
file2.close();
cout<<"\nTarget File Contents....\n";
file1.open(tfile);
while(!file1.eof())
{
file1.get(varch);
cout<<varch;
}
file1.close();
getch();
}

O/P:

Enter Source file name-SOURCE

Enter Target file name-TARGET

copied......
Target File Contents....

My Name is RAHUL KUMAR*/

125

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5. Write a program to write the text in a file. Read the text from the file from the
end of file. Display the contents of file in reverse order. Append the contents to
the existing file.

#include <iostream>
#include <fstream>
using namespace std;
int main () {

//using ofstream to write strings to a text file


ofstream myfile ("myTest.txt");

if (myfile.is_open())
{
myfile << "This is a test.\n";
myfile << "I am learning C++.\n";
myfile.close();
}
else cout << "Can't open file";
//Reverse and display the contents
char rev[30];
ifstream in ("myTest.txt");
in.seekg(0,ios::end);
int size=in.tellg();
for (int j=1; j<=size; j++)
{
in.seekg(-j, ios::end);
ch=in.get();
cout<<ch;
rev[i-1]=ch;
}

126

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

rev[size]=‟\0‟;
in.close();
//Appending the contents to text file
oftsream out(“my Test.txt”,ios::app);
out<<rev;
out.close();
return 0;
}
O/P:
++C gninrael ms I
.tset a si sihT

127

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT IV
ADVANCED NON-LINEAR DATA STRUCTURES

AVL Trees- B-Trees – Red-Black trees – Splay Trees – Binomial Heaps –


Fibonacci Heaps – Disjoint sets – Amortized Analysis – accounting method –
potential method – aggregate analysis

PART A
1. Define Fibonacci heaps. (Nov/Dec – 2014)
Fibonacci heaps is a collection of min-heap ordered trees.
 Trees: rooted but unordered
 Each node x: x.p points to its parent
 x.child points to any one of its children
 children of x are linked together in a circular doubly
linked list
 x.left, x.right: points to its left and right siblings.
 x.degree: number of children in the child list of x
 x.mark: indicate whether node x has lost a child since the last time x
was mode the child of another node
 H.min: points to the root of the tree containing a minimum key
 H.n: number of nodes in H

2. What is meant by amortized analysis? Show that the stack operation


MULTIPOP costs O (1) amortized time. (Nov/Dec 2014, April/May 2015,
May/June 2016)
Amortized analysis is a technique for analyzing an algorithm‟s running
time, by performing a sequence of operations averaged over all other operations
performed.
Techniques used are

1. Aggregate method – total running time is analyzed.

128

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Accounting method – we impose an extra charge on inexpensive operations


and use it to pay for expensive operations later.
3. Potential method – we derive a potential function characterizing the amount of
extra work we can do in each step.
Multipop(S, k)
while not Stack-Empty(S) and k>0
do Pop(S)
k←k–1

3. How does a Fibonacci heap differ from binomial heaps? (April/May 2015)
S.No Binomial Heap Fibonacci Heap

1 A Binomial heap is a heap data A Fibonacci heap is a heap data


structure consisting of a structure consisting of a collection
collection of min_heap ordered of min_heap ordered trees.
trees.

2 Trees within binomial heaps are Trees within Fibonacci heaps are
arranged monotonically rooted but unordered.
increasing order of degree.

3 The children of a node are The children of a node are linked


linked using sibling pointers using sibling pointer into a circular
into a circular singly linked list. doubly linked list.

4 The roots of the trees are also The roots of the trees are also
linked into a singly linked list. linked into a circular doubly linked
list.

5 Each node consists of 5 pointers Each node consists of 6 pointers


namely parent[x], child[x], namely parent[x], child[x], left[x],
sibling[x], degree[x], key[x]. degree[x], key[x], right[x].

129

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4. What are splay trees? What is its purpose.(Nov/Dec 2015, April/May 2012)
A splay tree is a binary search tree in which restructuring is done using a
scheme called splay. The splay is a heuristic method which moves a given
vertex v to a root of the splay tree using a sequence of rotations.
Splaying reduces the total accessing time if the most frequently accessed node
is moved towards the root. It does not require maintaining any information
regarding the height or balance factor and hence saves space and simplifies the
code to some extent.

5. What are the various operations that can be performed on B-Trees? Also
list the applications(Nov/Dec 2015, May/June 2016)
Operations on B trees
a. Insertion
b. Deletion
Applications
1. Database implementation.
2. Indexing on non primary key fields.

6. What is meant by B-tree? Give example. (May/June 2014)


The B tree of order M is a tree that is not binary with the following structural
properties:
 The root is either a leaf or has between 2 and M children.
 All non leaf nodes have between M/2 and M children.
 All leaves are at the same depth.

7. What is meant by sentinel?


 In programming, sentinel is a special value that is used to terminate a
loop.
 This value is chosen in such a way that the loop will encounter and
attempt to perform with.

130

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Example: In a algorithm of computing non negative integers, the value


of “-1” can be set as sentinel value as the computation will never
encounter that value.

8. List ant two applications of binary heaps.


1. The selection problem
2. Event simulation.

9. What is a heap and mention its types.


A heap is defined as a complete binary tree with the property that the value of
each node is at least as small as the value of its child nodes, if they exist. The
root node of the heap has the smallest value in the tree.
Types.
1. Binary heap
2. Binomial heap
3. Fibonacci heap.

10. What is an AVL tree? What is the minimum number of nodes in an AVL
tree of height h?
An empty tree is height balanced. If T is a non-empty binary tree with TL and
TR as its left and right subtrees, then T is height balanced if
i) TL and TR are height balanced and
ii) │hL - hR│≤ 1
Where hL and hR are the heights of TL and TR respectively.
The minimum number of nodes s(h) in a AVL tree of height h is given by
 s(h)= s(h-1)+ s(h-2)+1.
 For h=0, s(h)=1

11. Define disjoint sets and its data structures.


A collection of non-empty disjoint sets S= S1,S2,….,Sk i.e) for each Si is a
non-empty set that has no element in common with any other Sj. In

131

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

mathematical notation this is: Si∩Sj=ϕ. Each set is identified by a unique


element called its representative.

12. How do you calculate the balance factor for each node in a AVL tree.
 The height of the left subtree minus the height of right subtree is called
balance factor of a node in AVL Tree. The balance factor may be either
0,+1 or -1.
 The height of an empty tree is -1.

13. What do you mean by 2-3 tree and 2-3-4 tree?


2-3 tree
A B-tree of order 3 is called 2-3 tree. A B-tree of order 3 is a tree that is not
binary with the following structural properties:
 The root is either a leaf or has between 2 and 3 children.
 All non-leaf nodes (except the root) have between 2 and 3 children.
 All leaves are at the same depth.
2-3-4 tree
A B-tree of order 4 is called 2-3-4 tree. A B-tree of order 4 is a tree that is not
binary with the following structural properties:
 The root is either a leaf or has between 2 and 4 children.
 All non-leaf nodes (except the root) have between 2 and 4 children.
 All leaves are at the same depth.

14. What is meant by equivalence relation and equivalence class?


An equivalence relation is a relation R that satisfies three properties:
1. Reflexive: aRa, for all a ε S.
2. Symmetric: aRb if and only if bRa.
3. Transitive: aRb and bRc implies aRc.

132

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

15. Traverse the given tree using Inorder, Preorder and Postorder traversals.

Inorder : 1 2 3 4 5 6 7
Preorder : 4 2 1 3 6 5 7
Postorder : 1 3 2 5 7 6 4
PART B
1. Binary Search Tree
 Define Binary Search tree. Explain the various operations which are
involved in Binary search tree with an example.
Binary search tree is a binary tree in which every node X in the tree, the values of all
the keys in its left sub tree are smaller than the key value in X, and the values of all
the keys in its right sub tree are larger than the key vale in X.

Comparison between binary tree and binary search tree


Binary tree Binary search tree
A binary search tree is a binary tree in
A tree is said to be a binary tree if it has
which the key values in the left node is
atmost two children. It does not have any
less than the root and the key values in
order.
the right node is greater than the root.

133

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Declaration Routine for binary search tree


struct TreeNode;
typedef struct Treenode *SearchTree;
SearchTree Insert (int X, SearchTree T);
SearchTree Delete (int X, SearchTree T);
int Find (int X, SearchTree T);
int FindMin(SearchTree T);
int FindMax(SearchTree T);
SearchTree MakeEmpty(SearchTree T);
struct TreeNode
{
int Element;
SearchTree Left;
SearchTree Right;
};
MakeEmpty
This operation is mainly for initialization when the programmer prefer to
initialize the first element as a one node tree.
Routine to make an empty tree
SearchTree MakeEmpty(SearchTree T)
{
if (T!=NULL)
{
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
}
return NULL;
}

134

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Find
This operation requires returning a pointer to the node in tree T that has key X
or NULL if there is no such node.
The find operation as follows.
 Check whether the root is NULL if so then return NULL.
 Otherwise, check the value X with the root node value (ie. T->Element)
 If X is equal to T->Element, return T
 If X is less than T->Element, traverse the left of T recursively.
 If X is greater than T->Element, traverse the right of T recursively.
Routine for Find operation
Position Find( ElementType X, SearchTree T )
{
if( T == NULL )
return NULL;
if(X < T->element )
return( Find( X, T->left ) );
else
if( X > T->element )
return( Find( X, T->right ) );
else
return T;
}
Example:
To find an element 4 (X = 4) in the below tree

135

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 In the first fig, the element 4 is checked with root 6. 4 is less than 6. So goto the
left subtree.
 In the second fig, element 4 is checked with node 2. 4 is greater than 2. So goto the
right subtree.
 In the third fig, the element 4 is checked with node 4. The element is equal. So
return 4.

FindMin
This operation returns the position of the smallest element in the tree. To find
the minimum element, start at the root and go left as long as there is a left child. The
stopping point is the smallest element.
Recursive routine for FindMin Non Recursive routine for
FindMin
Position FindMin( SearchTree T ) Position FindMin( SearchTree T)
{ {
if( T = = NULL ) if( T != NULL )
return NULL; {
else while(T>Left!=NULL)
if( T->Left = = NULL ) {
return T; T = T->Left;
else }}
return FindMin ( T->Left ) ; } return T; }

FindMax
This operation returns the position of the largest element in the tree. To find the
maximum element, start at the root and go right as long as there is a right child. The
stopping point is the largest element.

136

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Recursive routine for FindMax Non Recursive routine for


FindMax
Position FindMax( SearchTree T ) Position FindMax( SearchTree T
)
{ {
if( T = = NULL ) if( T != NULL )
return NULL; {
else while(T->Right != NULL)
if( T->Right = = NULL ) {
return T; T = T->Right;
else }}
return FindMax ( T->Right ) ; return T;
} }
Insert
 To insert the element X in to the tree, check with the root node T.
 If it is less than the root, traverse the left sub tree recursively until it reaches the T-
>Left equals to NULL. Then X is placed in T->Left.
 If it is greater than the root, traverse the right sub tree recursively until it reaches
the T->Right equals to NULL. Then X is placed in T->Right.
 If X is found in the tree, do nothing.

Recursive routine to insert an element into a binary search tree


SearchTree Insert( ElementType X, SearchTree T )
{
if( T = = NULL )
{ /* Create and return a one-node tree */
T = malloc ( sizeof (struct TreeNode) );
if( T != NULL )
{
T-Element = X;
T->Left = T->Right = NULL;

137

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
}
else
{
if( X < T->Element )
T->Left = Insert( X, T->Left );
else
if( X > T->Element )
T->Right = Insert( X, T->Right );
/* else X is in the tree already. We'll do nothing */
return T;
}

8 8

Example: To insert 8, 4, 1, 6, 5, 7, 10
i. First insert element 8 which is considered as root.
ii. Next insert element 4, 4 is less than 8, traverse towards left.
iii. Next insert element 1, 1<8 traverse towards left. 1<4 traverse towards left.
iv. To insert element 6,6<8 traverse towards left. 6>4, place it as right child of 4.
v. To insert element 5, 5<8 traverse towards left. 5>4, traverse towards right.
5<6, place it as left child of 6.

8 8 8
8 8

4 4 4
4 4 1
0

1 6
1 1 6 1 6 1 6

5 7
5 5 7

138

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

vi. To insert element 7, 7<8 traverse towards left. 7>4, traverse towards right.
7>6, place it as right child of 6.
vii. To insert element 10, 10>8, place it as a right child of 8.
Delete

While deleting a node from a tree, the memory is to be released. Deletion operation is
the complex operation in the binary search tree. To delete a node from the tree
consider the following three possibilities.

Case 1: Node to be deleted is a leaf node


Case 2: Node with one child.
Case 3: Node with two children.

Case 1: Deleting the leaf node


 Search the parent of the leaf node.
 Make the parent link of the leaf node as NULL.
 Release Memory.
Example: Deletion of node 6

8 8

4 4

1 6 1

Before deletion After Deletion


Case 2: Deleting the node with only one child.
 Search the parent of the node to be deleted.
 Assign the parent link to the child node of the node to be deleted.
 Release the memory of the deleted node.
If a node has one child, it can be deleted by adjusting its parent pointer to point to its
child node.
Eg: Deletion of a node with one child, before and after

139

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Case 3: Deleting a node with two children.

The general strategy is to replace the data of the node to be deleted with its
smallest data of the right sub tree (or) largest data of the left sub tree and recursively
delete the data or node.
Inorder to delete a node with two children, it can be replaced by a node
whose key is larger than any node in P‟s right sub tree to preserve the Binary Search
Tree property. The possible nodes that could replace node P are

Rule 1: The node with the largest value in P‟s left sub tree.
Rule 2: The node with the smallest value in P‟s right sub tree.

Eg: Deletion of a node 4 with two children, before and after

8 8

4 5

1 6 1 6

140

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Deletion routine for binary search tree

SearchTree Delete( ElementType X, SearchTree T )


{
Position TmpCell;
if( T = = NULL )
Error("Element not found");
else
if( X < T->Element ) /* Go left */
T->Left = Delete( X, T->Left );
else
if( X > T->Element ) /* Go right */
T->Right = Delete( X, T->Right );
else /* Found element to be deleted */
if( T->Left && T->Right ) /* Two children */
{ /* Replace with smallest in right subtree */
TmpCell = FindMin( T->Right );
T->Element = TmpCell->Element;
T->Right = Delete( T->Element, T->Right );
}
else /* One or zero child */
{
TmpCell = T;
if( T->Left = = NULL ) /* Only a right child */
T = T->Right;
if( T->Right = = NULL ) /* Only a left child */
T = T->Left;
free(TmpCell );
}
return T;
}

141

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Red-Black Tree

 What is a Red-Black tree? Mention the properties that a Red-Black tree


holds. (Nov/Dec – 2014)

A red–black tree is a data structure which is a type of self-balancing binary


search tree. Balance is preserved by painting each node of the tree with one of two
colors (typically called 'red' and 'black') in a way that satisfies certain properties,
which collectively constrain how unbalanced the tree can become in the worst case.
When the tree is modified, the new tree is subsequently rearranged and repainted to
restore the coloring properties. The properties are designed in such a way that this
rearranging and recoloring can be performed efficiently.

A binary search tree is a red-black tree if:

1. Every node is either red or black


2. Every leaf (nil) is black
3. If a node is red, then both its children are black
4. Every simple path from a node to a descendant leaf contains the same number of
black nodes
Black-height of a node x, bh(x), is the number of black nodes on any path from
x to a leaf, not counting x

142

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Inserting in Red-Black Tree

 Color the node Red


 Insert as in a regular BST
 If have parent is red

Case 1

 x is node of interest, x's uncle is Red

 Decrease x's black height by one

Case 2

 x's uncle is Black, x is a Right child

143

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Transform to case 3

Case 3

 x's uncle is Black, x is a Left child

 Terminal case, tree is Red-Black tree


 Insertion takes O(lg(n)) time
 Requires at most two rotations

Example:

144

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Deleting in a Red-Black Tree

 Find node to delete


 Delete node as in a regular BST
 Node to be deleted will have at most one child
 If we delete a Red node tree still is a Red-Black tree
 Assume we delete a black node
 Let x be the child of deleted node
 If x is red, color it black and stop
 If x is black mark it double black and apply the following:

145

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Case 1
 x's sibling is red

 x stays at same black height. Transforms to case 2b then terminates.

Case 2a
 x's sibling is black
 x's parent is black

 Decreases x black height by one

Case 2b
 x's sibling is black
 x's parent is red

146

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Terminal case, tree is Red-Black tree

Case 3

 x's sibling is black


 x's parent is either
 x's sibling's left child is red
 x's sibling's right child is black

 x stays at same black height


 Transforms to case 4

Case 4

 x's sibling is black


 x's parent is either
 x's sibling's left child is either
 x's sibling's right child is red

147

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Terminal case, tree is Red-Black tree.


 Delete time is O(log(n)).
 At most three rotations are done.

3. AVL Tree

3. a. Explain the rotation, insertion and deletion in an AVL Tree with


suitable example. (Nov/Dec 2014, April/May 2015, Nov/Dec 2015,
May/June 2016)
An AVL (Adelson – Velskii and Landis) tree is a binary search tree with a
balance condition. A balance factor is the height of the left sub tree minus height of
the right sub tree. The height of the empty tree is defined to be -1. For an AVL tree all
balance factor should be +1, 0, or -1.
If the balance factor of any node in an AVL tree becomes less than -1 or greater
than 1, the tree has to be balanced by making a simple modifications in the tree called
rotation.
An AVL tree causes imbalance, when any one of the following conditions
occur. α – is the node must be rebalanced.

148

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Case 1: An insertion from the left sub tree of the left child of node α.
Case 2: An insertion into the right sub tree of the left child of α.
Case 3: An insertion into the left sub tree of the right child of α.
Case 4: An insertion into the right sub tree of the right child of α.

These imbalances can be overcome by


i. Single Rotation
a. Left
b. Right
ii. Double Rotation
a. Left
b. Right

149

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Case 1 and Case 4 imbalance (left – left or right – right) is fixed by a single
rotation of the tree. Case 2 and Case 3 imbalance (left – right or right – left) is fixed
by double rotation.

i. Single rotation

a. Routine to perform Single rotation with left


static Position SingleRotateWithLeft ( Position K2 )
{
Position K1;
K1 = K2->Left;

K2->Left = K1->Right;
K1->Right = K2;
K2->Height = Max ( Height (K2 ->Left), Height(K2->Right))+1;
K1->Height = Max ( Height (K1 ->Left), Height(K1->Right))+1;
return K1;
}

b. Routine to perform single rotation with right


static Position SingleRotateWithRight ( Position K1 )
{
Position K2;
K2 = K1->Right;
K1->Right = K2->Left;
K2->Left = K1;
K2->Height = Max ( Height (K2 ->Left), Height(K2->Right))+1;

150

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

K1->Height = Max ( Height (K1 ->Left), Height(K1->Right))+1;


return K2;
}

ii. Double Rotation

a. Double Rotation with left


Double rotation with left is used to perform case 2. An insertion into the right
sub tree of the left child of node α.
Double Rotation with left is performed by first performing single rotation with
right, and then performing single rotation with left.

Routine to perform double rotation with left

static Position DoubleRotateWithLeft( Position K3)


{
/* Rotate between K1 and K2 */
K3 -> Left = SingleRotateWithRight(K3 -
>Left); /* Rotate between K3 and K2 */
return SingleRotateWithLeft (K3);
}

b. Double Rotation with Right

Double rotation with right is used to perform case 4. An insertion into the left
sub tree of the right child of node α.
Double Rotation with right is performed by first performing single rotation
with left, and then performing single rotation with right.
Routine to perform double rotation with right

static Position DoubleRotateWithRight( Position K1)

151

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
K1 -> Right = SingleRotateWithLeft(K1 -
Right); return SingleRotateWithRight (K1);
}

Node declaration for AVL trees

#ifndef
_AvlTree_H struct
AvlNode;

typedef struct AvlNode *Position;


typedef struct AvlNode *AvlTree; AvlTree
MakeEmpty(AvlTree T);
Position Find( ElementType X, AvlTree T);
Position FindMin( AvlTree T);
Position FindMax( AvlTree T);
AvlTree Insert( ElementType X, AvlTree T);
AvlTree Delete( ElementType X, AvlTree T);
ElementType Retrieve( Position
P); #endif
struct AvlNode
{
ElementType Element;
AvlTree Left;
AvlTree Right;
int Height;
};

Function to compute height of an Avl node


static int Height( Position P)

152

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
if( P = = NULL)
return -1;
else
return P -> Height;
}

Insertion into an Avl tree

AvlTree Insert( ElementType X, AvlTree T)


{
if( T = = NULL)
{
T = malloc( sizeof( struct
AvlNode)); if( T = = NULL)
FatalError( “ Out of Space”);
else
{
T -> Element = X;
T -> Height = 0;
T -> Left = T -> Right = NULL;
}
}
else if( X < T -> Element)
{
T -> Left = Insert(X, T-> Left);

if( Height( T -> Left) – Height( T -> Right) =


= 2) if( X < T -> Left -> Element)
T = SingleRotateWithLeft( T );
else

153

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

T = DoubleRotateWithLeft(T);
}
else if( X > T -> Element)
{
T -> Right = Insert(X, T-> Right);
if( Height( T -> Right) – Height( T -> Left) =
= 2) if( X > T -> Right -> Element)
T = SingleRotateWithRight( T );
else
T = DoubleRotateWithRight(T);
}
/* Else X is in the tree already; we will do nothing */
T -> Height = Max( Height( T-> Left), Height( T ->
Right)) + 1; return T;
}

Example

Insert the following sequence of elements into an AVL tree, starting with an empty
tree:
10, 20, 15, 25, 30, 16, 18, 19. Delete 30 in the AVL tree.

10 15
15
10

10 20 10 25
15
20
25 30
20
20
15 30
16

154

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

15 2 2
0 0
15 25 15 25
20
10

25 10 16 30 10 18 30
16

30 18 16 19

19

Deletion

20
20 18
15 25
18 25
15 20
10 18 30 15 19 10 16 19 25

16 19
10 16

4. B-Tree
 What is a B-Tree? Mention the properties that a B-tree holds. Construct a
B-tree of order m=3. Perform the various operations on the tree. (Nov/Dec 2014,
April/May 2015)

A B-tree is a tree data structure that keeps data sorted and allows searches,
insertions, and deletions in logarithmic amortized time. Unlike self-balancing binary
search trees, it is optimized for systems that read and write large blocks of data. It is
most commonly used in database and file systems.

The B-Tree Rules

Important properties of a B-tree:

 B-tree nodes have many more than two children.

155

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 A B-tree node may contain more than just a single element.

The set formulation of the B-tree rules: Every B-tree depends on a positive constant
integer called MINIMUM, which is used to determine how many elements are held in
a single node.

 Rule 1: The root can have as few as one element (or even no elements if it also
has no children); every other node has at least MINIMUM elements.

 Rule 2: The maximum number of elements in a node is twice the value of


MINIMUM.

 Rule 3: The elements of each B-tree node are stored in a partially filled array,
sorted from the smallest element (at index 0) to the largest element (at the final
used position of the array).

 Rule 4: The number of subtrees below a nonleaf node is always one more than
the number of elements in the node.
o Subtree 0, subtree 1, ...

 Rule 5: For any nonleaf node:


1. An element at index i is greater than all the elements in subtree
number i of the node, and
2. An element at index i is less than all the elements in subtree
number i + 1 of the node.

Rule 6: Every leaf in a B-tree has the same depth. Thus it ensures that a B-tree
avoids the problem of a unbalanced tree.

156

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The Set Class Implementation with B-Trees

"Every child of a node is also the root of a smaller B-tree".

public class IntBalancedSet implements Cloneable


{
private static final int MINIMUM = 200;
private static final int MAXIMUM = 2*MINIMUM;
int dataCount;
int[] data = new int[MAXIMUM + 1];
int childCount;
IntBalancedSet[] subset = new IntBalancedSet[MAXIMUM + 2];
// Constructor: initialize an empty set
public IntBalancedSet()

157

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

// add: add a new element to this set, if the element was already in the set, then there
is no change.
public void add(int element)
// clone: generate a copy of this set.
public IntBalancedSet clone()
// contains: determine whether a particular element is in this set
pubic boolean contains(int target)
// remove: remove a specified element from this set
public boolean remove(int target)
}

Searching for a Target in a Set

The psuedocode:
1. Make a local variable, i, equal to the first index such that data[i] >= target. If
there is no such index, then set i equal to dataCount, indicating that none of the
elements is greater than or equal to the target.
2. if (we found the target at data[i])
return true;
else if (the root has no children)
return false;
else return subset[i].contains(target);

Example, try to search for 10.

158

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

We can implement a private method:


 private int firstGE(int target), which returns the first location in the root such
that data[x] >= target. If there's no such location, then return value is
dataCount.

Adding an Element to a B-Tree

It is easier to add a new element to a B-tree if we relax one of the B-tree rules.
Loose addition allows the root node of the B-tree to have MAXIMUM = 1 elements.
For example, suppose we want to add 18 to the tree:

The above result is an illegal B-tree. Our plan is to perform a loose addition first, and
then fix the root's problem.

The Loose Addition Operation for a B-Tree:

private void looseAdd(int element)


{
i = firstGE(element) // find the first index such that data[i] >= element
if (we found the new element at data[i]) return; // since there's already a copy in the
set
else if (the root has no children)
Add the new element to the root at data[i]. (shift array)
else {
subset[i].looseAdd(element);
if the root of subset[i] now has an excess element, then fix that problem before

159

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

returning.
}
}

private void fixExcess(int i)


// precondition: (i < childCount) and the entire B-tree is valid except that subset[i] has
MAXIMUM + 1 elements.
// postcondition: the tree is rearranged to satisfy the loose addition rule

Fixing a Child with an Excess Element:

 To fix a child with MAXIMIM + 1 elements, the child node is split into two
nodes that each contain MINIMUM elements. This leaves one extra element,
which is passed up to the parent.
 It is always the middle element of the split node that moves upward.
 The parent of the split node gains one additional child and one additional
element.
 The children of the split node have been equally distributed between the two
smaller nodes.

160

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Fixing the Root with an Excess Element:

 Create a new root.


 fixExcess(0).

Removing an Element from a B-Tree

Loose removal rule: Loose removal allows to leave a root that has one element too
few. public boolean remove(int target)
{
answer = looseRemove(target);
if ((dataCount == 0) && (childCount == 1))
Fix the root of the entire tree so that it no longer has zero elements;
return answer;
}
private boolean looseRemove(int target)
{
1. i = firstGE(target)
2. Deal with one of these four possibilities:
2a. if (root has no children and target not found) return false.

161

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2b. if( root has no children but target found) {


remove the target
return true
}
2c. if (root has children and target not found) {
answer = subset[i].looseRemove(target)
if (subset[i].dataCount < MINIMUM)
fixShortage(i)
return true
}
2d. if (root has children and target found) {
data[i] = subset[i].removeBiggest()
if (subset[i].dataCount < MINIMUM)
fixShortage(i)
return true
}
}
private void fixShortage(int i)
// Precondition: (i < childCount) and the entire B-tree is valid except that subset[i] has
MINIMUM - 1 elements.
// Postcondition: problem fixed based on the looseRemoval rule.
private int removeBiggest()
// Precondition: (dataCount > 0) and this entire B-tree is valid
// Postcondition: the largest element in this set has been removed and returned. The
entire B-tree is still valid based on the looseRemoval rule.

162

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Fixing Shortage in a Child:

When fixShortage(i) is activated, we know that subset[i] has MINIMUM - 1 elements.


There are four cases that we need to consider:
Case 1: Transfer an extra element from subset[i-1]. Suppose subset[i-1] has more than
the MINIMUM number of elements.
a. Transfer data[i-1] down to the front of subset[i].data.
b. Transfer the final element of subset[i-1].data up to replace data[i-1].
c. If subset[i-1] has children, transfer the final child of subset[i-1] over to the
front of subset[i].

Case 2: Transfer an extra element from subset[i+1]. Suppose subset[i+1] has more
than the MINIMUM number of elements.

Case 3: Combine subset[i] with subset[i-1]. Suppose subset[i-1] has only MINIMUM
elements
a. Transfer data[i-1] down to the end of subset[i-1].data.
b. Transfer all the elements and children from subset[i] to the end of subset[i-1].

163

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

c. Disconnect the node subset[i] from the B-tree by shifting subset[i+1],


subset[i+2] and so on leftward.

Case 4: Combine subset[i] with subset[i+1]. Suppose subset[i+1] has only


MINIMUM elements. We may need to continue activating fixShortage() until the B-
Tree rules are satisfied.

Removing the Biggest Element from a B-Tree:


private int removeBiggest()
{
if (root has no children)
remove and return the last element
else {
answer = subset[childCount-1].removeBiggest()
if (subset[childCount-1].dataCount < MINIMUM)
fixShortage(childCount-1)
return answer
}
}

164

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

A more concrete example for node deletion:

5.Splay Tree

 Define splay tree. Explain the splaying operation with its code in detail.
(Nov/Dec 2014, April/May 2015)

Splay trees are another variation of the binary search tree.

Novel characteristics:
 Does not require any accounting information (color, level, height, etc.)

165

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 O(N) worst case for any single operation, but O(log N) average case
 Frequently-accessed keys are moved up so that they are near the root.

Splay Operation:

Fundamental operation is the splay: this operation re-arranges the tree to make
a specified node the root. A side-effect of the splay is that imbalances in the tree are
corrected.
The simplest approach to splaying is the bottom-up approach, which is similar
to the rebalancing operations we have seen for AVL, Red-Black, and AA-trees. On
some path from a selected node back to the root, rotations are performed.
There are three cases for splaying. (Note that only the "left" cases are shown: there
are symmetric "right" cases.)
 Zig
 Zig-Zig
 Zig-Zag

Zig Step:

This step is done when p is the root. The tree is rotated on the edge
between x and p. Zig steps exist to deal with the parity issue and will be done only as
the last step in a splay operation and only when x has odd depth at the beginning of the
operation.

166

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Zig-zig Step:

This step is done when p is not the root and x and p is either both right children
or are both left children. The picture below shows the case where x and p are both left
children. The tree is rotated on the edge joining p with its parent g, then rotated on the
edge joining x with p.

Zig-zag Step:
This step is done when p is not the root and x is a right child and p is a left
child or vice versa. The tree is rotated on the edge between p and x, and then rotated
on the resulting edge between x and g.

Overall splaying algorithm (bottom-up): splaying continues until the node X is


the root of the overall tree.
A splay operation is performed after each access. We recursively apply the
splaying strategy until the node of our interest reaches the root.

167

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example: Result of splaying at node 1 (after 1 is accessed).

 Insertion: X is the newly inserted node (and will become the root after
splaying).
 Search:
o If X is in the tree, X is the node found (and will become the root after
splaying).
o If X is not in the tree, the last node accessed prior to reaching the NULL
pointer is splayed.
 Deletion:
o First, X is the node to be deleted. Splay it to the root (and delete it).
o Then for the two subtrees L and R (left and right), we find the largest
element in L. Splay it to the root of L. At this point, L's (new) root has
no right child.
o Finally connect R to the root of L as its right child.
Example: Delete 6

168

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

PART - C
1. Heaps
 What is meant by binomial heap? Illustrate the construction of Binomial
heaps and its operations with suitable example. (April/May 2015, Nov/Dec 2015)

Binomial heaps:

A binomial heap is implemented as a collection of binomial trees (compare with


a binary heap, which has a shape of a singlebinary tree).

A binomial tree is defined recursively:


 A binomial tree of order 0 is a single node
 A binomial tree of order k has a root node whose children are roots of binomial
trees of orders k−1, k−2, ..., 2, 1, 0 (in this order).

Binomial trees of order 0 to 3: Each tree has a root node with subtrees of all
lower ordered binomial trees, which have been highlighted. For example, the order 3
binomial tree is connected to an order 2, 1, and 0 (highlighted as blue, green and red
respectively) binomial tree. A binomial tree of order k has 2k nodes, height k.
169

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The name comes from the shape: a binomial tree of order has nodes at
depth .

Structure of binomial heaps:

A binomial heap is implemented as a set of binomial trees that satisfy the binomial
heap properties:

 Each binomial tree in a heap obeys the minimum-heap property: the key of a
node is greater than or equal to the key of its parent.
 There can only be either one or zero binomial trees for each order, including
zero order.

The first property ensures that the root of each binomial tree contains the
smallest key in the tree, which applies to the entire heap.

The second property implies that a binomial heap with n nodes consists of at
most log n + 1 binomial trees. In fact, the number and orders of these trees are
uniquely determined by the number of nodes n: each binomial tree corresponds to one
digit in the binary representation of number n.

Binomial Tree

• A binomial heap is a collection of binomial trees.

170

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

• Binomial tree Bk is an ordered tree defined recursively. The binomial tree B0


has one node. The binomial tree Bk consists of two binomial trees Bk-1 and
they are connected such that the root of one tree is the leftmost child of the
other.
• Binomial tree properties:
– Bk has 2^k nodes
– Bk has height k
– There are exactly ( ik ) nodes at depth i for i=0, 1, 2,…,k.
– The root has degree k which is greater than other node in the tree. Each
of the root‟s child is the root of a subtree Bi.

Binomial Heap Properties:

• Each binomial tree is heap-order: key of a node is greater or equal to the key of
its parent. The root has the smallest key in the tree.

171

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

• There is at most one binomial tree whose root has a given degree. This means
that there are at most |_log n_| +1 trees in a binomial heap.
• The binomial trees in the binomial heap are arranged in increasing order of
degree

Binomial Heap Implementation:

• Each node has the following fields:


– p: parent
– child: leftmost child
– sibling
– Degree
– Key
– Roots of the trees are connected using linked list.

• Example:

Binomial Heap Operations

• Create heap
• Find minimum key

172

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

• Unit two binomial heap


• Insert a node
• Extract minimum node
• Decrease a key
• Delete a node

Create A New Binomial Heap:

• The operation simply creates a new pointer and sets it to NIL.


• Pseudocode:
Binomial-Heap-Create()
1 head[H] <- NIL
2 return head[H]
 Run time is θ(1).

Find Minimum Key:

• Since the binomial heap is a min-heap-order, the minimum key of each


binomial tree must be at the root. This operation checks all the roots to find the
minimum key.
• Pseudocode: this implementation assumes that there are no keys with value ∞
Binomial-Heap-Minimum(H)

1 y <- NIL
2 x <- head[H]
3 min <- ∞
4 while x is not NIL
5 do if key[x] < min then
6 min <- key[x]
7 y <- x
8 x <- sibling[x]

173

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

9 return y

• Run time: The run time is in the order of O(log n) since the most number of
roots in binomial heap is |_(log n)_| +1

Find Minimum Key Example

Unite Two Binomial Heaps:

• This operation consists of the following steps


– Merge two binomial heaps. The resulting heap has the roots in
increasing order of degree
– For each tree in the binomial heap H, if it has the same order with
another tree, link the two trees together such that the resulting tree obeys
min-heap-order.

174

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Binomial-Heap-Union(H1,H2)
1 Binomial-Heap-Union(H1,H2)
2 H <- Make-Binomial-Heap()
3 Head[H] <- Binomial-Merge(H1,H2)
4 Free the objects H1 and H2 but not the lists they point to

175

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5 If head[H] = NIL
6 then return H
7 Prev-x <-NIL
8 X <- head[H]
9 Next-x <- sibling[x]
10 while next-x not NIL
do if(degree[x] not degree[next-x]) or
(sibling[next-x not NIL and degree[sibling[next-x]]=degree[x])
11 then prev-x <-x
12 x <- next-x
13 else if key[x] <= key[next-x]
14 then sibling[x] <- sibling[next-x]
15 Binomial-Link(next-x,x)
16 else if prev-x = NIL
17 then head[H] <-next-x
18 else sibling[prev-x] <- next-x
19 Binomial-Link(x,next-x)
20 x <- next-x
21 next-x <- sibling[x]
22 return H

Insert New Node

• Create a new heap H‟ and set head[H‟] to the new node.


• Unite the new heap H‟ with the existing heap H.
• Pseudocode:

Binomial-Heap-Insert(H,x)
1 H‟ <- Make-Binomial-Heap()
2 p[x] <- NIL
3 child[x] <- NIL

176

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4 sibling[x] <- NIL


5 degree[x] <- 0
6 head[H‟] <- x
7 H <- Binomial-Heap-Union(H,H‟)
• Run time: O(log n)

Extract Node With Minimum Key:

• This operation is started by finding and removing the node x with minimum
key from the binomial heap H. Create a new binomial heap H‟ and set to the
list of x‟s children in the reverse order. Unite H and H‟ to get the resulting
binomial heap.
• Pseudocode

Binomial-Heap-Extract-Min(H)
1 find the root x with the minimum key in the root list of H,
and remove x from the root list of H.
2 H‟ <- Make-Binomial-Heap()
3 reverse the order of the linked list of x‟s children,
and set head[H‟] to point to the head of the resulting list.

177

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4 H <- Binomial-Heap-Union(H,H‟)
5 Return x

• Run time: O(log n)

178

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Decreasing a key:
• The current key is replaced with a new key. To maintain the min-heap
property, it is then compared to the key of the parent. If its parent‟s key is
greater then the key and data will be exchanged. This process continues until
the new key is greater than the parent‟s key or the new key is in the root.
• Pseudocode:
Binomial-Heap-Decrease-Key(H,x,k)
1 if k > key[x]
2 then error “new key is greater than current key”
3 key[x] <-k
4 y <-x
5 z <-p[y]
6 while z not NIL and key[y] < key[z]
7 do exchange key[y] <-> key[z]
8 if y and z have satellite fields, exchange them, too.
9 y <- z
10 z <- p[y]

Decreasing a key
• Execution time: This procedure takes O(log n) since the maximum depth of x is
|_log n_|.
• Example:

179

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Delete a Node:

• With assumption that there is no node in H has a key of -∞.


• The key of deleting node is first decreased to -∞.
• This node is then deleted using extracting min procedure.
• Pseudocode: (from book)

Binomial-Heap-Delete(H,x)

1 Binomial-Heap-Decrease-Key(H,x,-∞)
2 Binomial-Heap-Extract-Min(H)

• Run time: O(log n) since the run time of both Binomial-Heap-Decrease-Key


and Binomial-Heap-Extract-Min procedures are in order of O(log n).

180

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Implement the Fibonacci heaps and compare their performance with


binary heaps when used in Dijkstra’s algorithm. (May/June 2016)

Binomial Tree:
A binomial tree of order 0 is a single node. A binomial tree of order k has a

181

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

root of degree k and its children are roots of binomial trees of orders k-1, k-2, ..., 2, 1,
0 (in order). A binomial tree of order k has 2k nodes.

Data Structures:
 Heap ordered Trees
 Rooted, but unordered
 Children of a node are linked together in a Circular, doubly linked List, E.g
node 52

182

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Node Pointers
- left [x]
- right [x]
- degree [x]
- number of children in the child list of x
- mark [x]

Properties:

 Collection of unordered Binomial Trees.


 Support Mergeable heap operations such as Insert, Minimum, Extract Min, and
Union in constant time O(1)
 Desirable when the number of Extract Min and Delete operations is small
relative to the number of other operations.
 Most asymptotically fastest algorithms for computing minimum spanning trees
and finding single source shortest paths make use of the Fibonacci heaps.

Fibonacci Heap Operations:

Make Fibonacci Heap

 Assign N[H] = 0, min[H] = nil


 Amortized cost is O(1)

Find Min

 Access Min[H] in O(1) time

183

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Uniting 2 Fibonacci Heaps

 Concatenate the root lists of Heap1 and Heap2


 Set the minimum node of the new Heap
 Free the 2 heap objects
 Amortized cost is equal to actual cost of O(1)

Insert

 Amortized cost is O(1)


 Initialize the structural fields of node x, add it to the root list of H
 Update the pointer to the minimum node of H, min[H]
 Increment the total number of nodes in the Heap, n[H]

Example

Min [H]

3
23 7 17 24

18 52 38 30 26 46

39 41 35

 Node 21 has been inserted


184

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Red Nodes are marked nodes – they will become relevant only in the delete
operation.

Min [H]

3
23 7 21 17 24

18 52 38 30 26 46

39 41 35

Extract Minimum Node

 Amortized cost is O(D(n))


 Make a root out of each of the minimum node‟s children.
 Remove the minimum node from the root list, min ptr to right(x)

 Consolidate the root list by linking roots of equal degree and key[x] <= key[y],
until every root in the root list has a distinct degree value. (uses auxiliary array)

 Root Nodes are stored in the auxiliary array in the index corresponding to their
degree.
 Hence node 7 is stored in index 3 and node 21 is stored in index 0.

185

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

0 1 2 3 4

A
w,x

7 21 18 52 38

24 17 23 39 41

26 46 30

35

 Further, node 18 is stored in index 1


 There are no root nodes of index 2, so that array entry remains empty
 Now the algorithm iterates through the auxiliary array and links roots of equal
degree such that key[x] <= key[y],

186

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Nodes 21 and 52 are linked so that node 21 has degree 1, and it is then linked
to node 18
 The pointers of the auxiliary array are updated.
 But there are now no more remaining root nodes of duplicate degrees.

0 1 2 3 4

w,x
7 18 38

24 17 23 21 39 41

26 46 30 52

35

187

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Extract-Min is now done.


 The pointer min[H] is finally updated to the new minimum.

min [H]

7 18 38

24 17 23 21 39 41

26 46 30 52

35

A node is marked if:


 At some point it was a root then it was linked to anther nodeand 1 child of it
has been cut.
 Newly created nodes are always unmarked
 A node becomes unmarked whenever it becomes the child of another node.

Decrease-Key
 Amortized cost is O(1).
 Check that new key is not greater than current key, then assign new key to x
 If x is a root or if heap property is maintained, no structural changes
 Else
o Cut x: make x a root, remove link from parent y, clear marked field of x
o Perform a Cascading cut on x‟s parent y (relevant if parent is marked):
 if unmarked: mark y, return
 if marked: Cut y, recurse on node y‟s parent
188

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 if y is a root, return
 The Cascading cut procedure recurses its way up the tree until a root, or an
unmarked node is found.
 Update min[H] if necessary.
Example:
 Suppose we want to decrease the keys of node 46 to 15.

min [H]

7 18 38

24 17 23 21 39 41

26 46 30 52

35

 Since the new key of node 46 is 15 it violates the min-heap property, so it is


cut and put on the root.
 Suppose now we want to decrease the key of node 35 to 5.

min [H]

15 7 18 38

24 17 23 21 39 41

30 52
26

35

189

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 So node 5 is cut and place on the root list because again the heap property is
violated.
 But the parent of node 35, which is node 26, is marked, so we have to perform
a cascadingcut.

The cascading cut involves cutting the marked node, 26, unmarking it, and putting it
on the root list.
 We now repeat this procedure (recurse) on the marked nodes parent until we hit
a node on the root listis updated.

Delete-Key
 Amortized cost is O(D(n))
 Call Decease-Key on the node x that needs to be deleted in H, assigning
negative infinity to it.
 Call Extract-Min on H.

190

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Amortized Analysis

 What is meant by amortized analysis? Explain the various methods in detail.

Amortized analysis is a method of analyzing algorithms that considers the


entire sequence of operations of the program. It allows for the establishment of a
worst-case bound for the performance of an algorithm irrespective of the inputs by
looking at all of the operations.
• Not just consider one operation, but a sequence of operations on a given data
structure.
• Average cost over a sequence of operations.
• Probabilistic analysis:
– Average case running time: average over all possible inputs for one
algorithm (operation).
– If using probability, called expected running time.
• Amortized analysis:
– No involvement of probability
– Average performance on a sequence of operations, even some operation
is expensive.
– Guarantee average performance of each operation among the sequence
in worst case.
Three Methods of Amortized Analysis:
• Aggregate analysis:
– Total cost of n operations/n,
• Accounting method:
– Assign each type of operation an (different) amortized cost overcharge
some operations, store the overcharge as credit on specific objects, then
use the credit for compensation for some later operations.
• Potential method:
– Same as accounting method.
– But store the credit as “potential energy” and as a whole.

191

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example for amortized analysis:


• Stack operations:
– PUSH(S,x), O(1)
– POP(S), O(1)
– MULTIPOP(S,k), min(s,k)
while not STACK-EMPTY(S) and k>0
do POP(S)
k=k-1
• Let us consider a sequence of n PUSH, POP, MULTIPOP.
– The worst case cost for MULTIPOP in the sequence is O(n), since the
stack size is at most n.
– Thus the cost of the sequence is O(n2). Correct, but not tight.
ACCOUNTING METHOD:
• Idea:
– Assign differing charges to different operations.
– The amount of the charge is called amortized cost.
– Amortized cost is more or less than actual cost.
– When amortized cost > actual cost, the difference is saved in specific
objects as credits.
– The credits can be used by later operations whose amortized cost <
actual cost.
• As a comparison, in aggregate analysis, all operations have same amortized
costs.
• Conditions:
– Suppose actual cost is ci for the ith operation in the sequence, and
amortized cost is ci',
– i=1n ci' i=1n ci should hold.
• Since we want to show the average cost per operation is small
using amortized cost, we need the total amortized cost is an upper
bound of total actual cost.
• Holds for all sequences of operations.

192

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

– Total credits is i=1n ci' - i=1n ci , which should be nonnegative,


• Moreover, i=1t ci' - i=1t ci ≥0 for anyt>0.
Accounting Method: Stack Operations
• Actual costs:
– PUSH :1, POP :1, MULTIPOP: min(s,k).
• Let assign the following amortized costs:
– PUSH:2, POP: 0, MULTIPOP: 0.
• Similar to a stack of plates in a cafeteria.
– Suppose $1 represents a unit cost.
– When pushing a plate, use one dollar to pay the actual cost of the push
and leave one dollar on the plate as credit.
– Whenever POPing a plate, the one dollar on the plate is used to pay the
actual cost of the POP. (Same for MULTIPOP).
– By charging PUSH a little more, do not charge POP or MULTIPOP.
• The total amortized cost for n PUSH, POP, MULTIPOP is O(n), thus O(1) for
average amortized cost for each operation.
• Conditions hold: total amortized cost ≥total actual cost, and amount of credits
never becomes negative.
Accounting method: binary counter
• Let $1 represent each unit of cost (i.e., the flip of one bit).
• Charge an amortized cost of $2 to set a bit to 1.
• Whenever a bit is set, use $1 to pay the actual cost, and store another $1 on the
bit as credit.
• When a bit is reset, the stored $1 pays the cost.
• At any point, a 1 in the counter stores $1, the number of 1‟s is never negative,
and sois the total credit.
• At most one bit is set in each operation, so the amortized cost of an operation is
at most $2.
• Thus, total amortized cost of n operations is O(n), and average is O(1).
THE POTENTIAL METHOD:
• Same as accounting method: something prepaid is used later.

193

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

• Different from accounting method


– The prepaid work not as credit, but as “potential energy”, or “potential”.
The potential is associated with the data structure as a whole rather than with
specific objects within the data structure.
• Initial data structure D0, n operations, resulting in D0, D1,…, Dn with costs c1,
c2,…, cn.
• A potential function : {Di}  R (real numbers)
• (Di) is called the potential of Di.
• Amortized cost ci' of the ith operation is:
ci' = ci + (Di) - (Di-1). (actual cost + potential change)
i=1n ci'= i=1n(ci + (Di) - (Di-1))
= i=1nci + (Dn) - (D0)
• If (Dn) (D0), then total amortized cost is an upper bound of total actual
cost.
• But we do not know how many operations, so (Di) (D0) is required for any
i.
• It is convenient to define (D0)=0,and so (Di) 0, for all i.
• If the potential change is positive (i.e., (Di) - (Di-1)>0), then ci' is an
overcharge (so store the increase as potential), otherwise, undercharge
(discharge the potential to pay the actual cost).
Potential method: stack operation
• Potential for a stack is the number of objects in the stack.
• So (D0)=0, and (Di) 0
• Amortized cost of stack operations:
– PUSH:
• Potential change: (Di)- (Di-1) =(s+1)-s =1.
• Amortized cost: ci' = ci + (Di) - (Di-1)=1+1=2.
– POP:
• Potential change: (Di)- (Di-1) =(s-1) –s= -1.
• Amortized cost: ci' = ci + (Di) - (Di-1)=1+(-1)=0.

194

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

– MULTIPOP(S,k): k'=min(s,k)
• Potential change: (Di)- (Di-1) =–k'.
• Amortized cost: ci' = ci + (Di) - (Di-1)=k'+(-k')=0.
• So amortized cost of each operation is O(1), and total amortized cost of n
operations is O(n).
• Since total amortized cost is an upper bound of actual cost, the worse case cost
of n operations is O(n).

Potential method: binary counter


• Define the potential of the counter after the ith INCREMENT is (Di) =bi, the
number of 1‟s. clearly, (Di)0.
• Let us compute amortized cost of an operation
– Suppose the ith operation resets ti bits.
– Actual cost ci of the operation is at most ti +1.
– If bi=0, thenthe ith operation resets all k bits, so bi-1=ti=k.
– If bi>0, then bi=bi-1-ti+1
– In either case, bibi-1-ti+1.
– So potential change is (Di) - (Di-1) bi-1-ti+1-bi-1=1-ti.
– So amortized cost is: ci' = ci + (Di) - (Di-1)ti +1+1-ti=2.
• The total amortized cost of n operations is O(n).
• Thus worst case cost is O(n).
AGGREGATE ANALYSIS:
 In fact, a sequence of n operations on an initially empty stack cost at most
O(n).
 Each object can be POP only once (including in MULTIPOP) for each time it
is PUSHed. #POPs is at most #PUSHs, which is at most n.
 Thus the average cost of an operation is O(n)/n = O(1).
 Amortized cost in aggregate analysis is defined to be average cost.

Example: Increasing a binary counter

195

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Binary counter of length k, A[0..k-1] of bit array.


INCREMENT(A)
1. i0
2. whilei<k and A[i]=1
3. do A[i]0 (flip, reset)
4. ii+1
5. if i<k
6. then A[i]1 (flip, set)

Amortized (Aggregate) Analysis of INCREMENT (A)


The running time determined by #flipsbut not all bits flip each time
INCREMENT is called.
A[0] flips every time, total n times.
A[1] flips every other time,n/2 times.
A[2] flips every forth time,n/4 times.
….
for i=0,1,…,k-1, A[i] flips n/2i times.
Thus total #flips is i=0k-1 n/2i
<ni=0 1/2i
=2n.

196

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

• Thus the worst case running time is O(n) for a sequence of n INCREMENTs.
So the amortized cost per operation is O(1).

 Explain the operation of union-by-height and path compression with an


algorithm.

A disjoint set is a data structure which 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
Let x be an object. The following operations are performed. They are
 MAKE-SET( x) creates a new set whose only member is pointed by x; Note
that x is not in the other sets.
 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 =∅;
 FIND-SET( x) returns a pointer to the representative of the set containing x.
 INSERT( a,S) inserts an object a to S, and returns S∪{a}.
197

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

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


 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.
Union find algorithm is used to detect cycle in a graph.
// Naive implementation of find
int find(int parent[], int i)
{
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
// Naive implementation of union()
void Union(int parent[], int x, int y)
{
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
The above union() and find() are naive and the worst case time complexity is linear.
The trees created to represent subsets can be skewed and can become like a linked list.
Let there be 4 elements 0, 1, 2, 3
Initially all elements are single element subsets.
0123
Do Union(0, 1)
1 2 3
/
0
Do Union(1, 2)
2 3
/

198

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

1
/
0
Do Union(2, 3)
3
/
2
/
1
/
0
The above operations can be optimized to O(Log n) in worst case. The idea is to
always attach smaller depth tree under the root of the deeper tree. This technique is
called union by rank.
Example : union by rank
Initially all elements are single element subsets.
0123
Do Union(0, 1)
1 2 3
/
0
Do Union(1, 2)
1 3
/ \
0 2

Do Union(2, 3)
1
/ | \
0 2 3

199

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The second optimization to naive method is Path Compression. The idea is to flatten
the tree when find() is called. When find() is called for an element x, root of the tree is
returned. The find() operation traverses up from x to find root. The idea of path
compression is to make the found root as parent of x so that we don‟t have to traverse
all intermediate nodes again. If x is root of a subtree, then path (to root) from all nodes
under x also compresses.
Let the subset {0, 1, .. 9} be represented as below and find() is called for element 3.
9
/ | \
4 5 6
/ \ / \
0 3 7 8
/ \
1 2
When find() is called for 3, we traverse up and find 9 as representative of this subset.
With path compression, we also make 3 as child of 9 so that when find() is called next
time for 1, 2 or 3, the path to root is reduced.

9
/ / \ \
4 5 6 3
/ / \ / \
0 7 8 1 2
The two techniques complement each other. The time complexity of each operations
becomes even smaller than O(Logn). In fact, amortized time complexity effectively
becomes small constant.

200

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT V
GRAPHS

Representation of Graphs – Breadth-first search – Depth-first search – Topological


sort – Minimum Spanning Trees – Kruskal and Prim algorithm – Shortest path
algorithm – Dijkstra‟s algorithm – Bellman-Ford algorithm – Floyd – Warshall
algorithm.

PART A
1. Define Graph.
A Graph G=(V,E) consists of a set of vertices V and a set of Edges E. Each edge is a
pair (v,w) where v,w € V.

2. Define path and length of a path.


A path in a graph is a sequence of vertices w1, w2 ,w3,….w N such that (wi,wi+1) € E for
1<i<N.
Length of a path is the number of edges of the path.

3. Define connected graph, strongly connected graph and complete graph.


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 graph
A complete graph is a graph in which there is an edge between every pair of vertices

4. What are the two ways to represent a graph. Nov/Dec 2014, April/May
2015,May/June 2016
(i) Adjacency matrix
(ii) Adjacency list

201

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5. Define Topological sort. Nov/Dec 2015


A topological sort is an ordering of vertices in a directed acyclic graph such that if
there is a path from Vi to Vj the Vj appears after Vi in the ordering.

6. Define graph traversal and its types and list the applications of Depth First
Search. May/June 2016
A graph traversal starts at initial vertex and visits each and every vertex exactly once
and finally reaches the end vertex.
Types of graph traversal:
(i) Breadth first search and traversal
(ii) Depth first search and traversal
Applications of depth first Search:
 Biconnectivity
 Euler Circuits

7. Define minimum spanning tree Nov/Dec 2014, Nov/Dec 2015


A minimum spanning tree of an undirected graph G is a tree formed from graph edges
that connects all the vertices of G at lowest total cost. A minimum spanning tree exists
if and only if G is connected. The number of edges in the minimum spanning tree is |
V | -1. Minimum spanning tree must be acyclic.

Example:

202

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

8. Define Dijkstra’s Algorithm.


Given an input a weighted Graph, G=(V,E) and a distinguished vertex S, the shortest
weighted path from S to every other vertex in G is called Dijkstra‟s algorithm.

9. Define Transitive closure


Consider a directed graph G=(V,E), where V is the set of vertices and E is the set of
edges. The
transitive closure of G is a graph G+ =(V,E+) such that for all v,w in V there is a edge
(v,w) in E+ if and only if there is a non-null path from v to w in G.

10. Define Bellman-Ford Algorithm. April/May 2015


Bellman-Ford algorithm is a procedure used to find all shortest path in a graph from
one source to all other nodes. The algorithm requires that the graph does not contain
any cycles of negative length, but if it does, the algorithm is able to detect it.
Part B
1. Representation of Graphs and Traversals

 Explain the different ways to represent a graph.

There are two ways to represent a graph


(i) Adjacency matrix
(ii) Adjacency list

Adjacency matrix representation:

 It uses two dimensional array


 For each edge(u,v), we set A[u][v] to true otherwise the entry in the array is
false
 If the edge has a weight associated with it, we can set A[u][v] equal to the
weight
 The space requirement for adjacency matrix is θ ( I V I 2 )
203

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The adjacency matrix representation is used if the graph is dense

Adjacency list representation:


 If the graph is sparse, adjacency list representation can be used
 The space requirement is O(IEI+IVI) which is the linear size of the graph
 For each vertex, we keep a list of all adjacent vertices
 Adjacency list are the standard way to represent graphs
 If the edges have weights, then this information should also be stored in the
adjacency list

Example:

Fig: A directed graph

Fig: Adjacency list representation of the above graph

204

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Explain the traversals in graph

Traversals:

Breadthe first traversal:

Breadth – first searches are performed by exploring all nodes at a given depth before
proceeding to the next level. This means that all immediate children of nodes are
explored before any of the children‟s children are considered. It has obvious
advantage of always finding a minimal path length solution when one exists.
However, a great many nodes may need to be explored before a solution is found,
especially if the tree is very full.
The only catch here is, unlike trees, graphs may contain cycles, so we may come to
the same node again. To avoid processing a node more than once, we use a boolean
visited array. For simplicity, it is assumed that all vertices are reachable from the
startingvertex.
For example, in the following graph, the BFS of the graph starting from node 1 is : 1,

2, 3, 4, 6, 7, 5

Algorithm
void Graph::BFS(int s)

205

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;

// Create a queue for BFS


list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);

// 'i' will be used to get all adjacent vertices of a vertex


list<int>::iterator i;

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued vertex s


// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);

206

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
}
}
}

Depth first Traversal:

Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a
tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come
to the same node again. To avoid processing a node more than once, we use a boolean
visitedarray.
For example, in the following graph, we start traversal from vertex 2. When we come
to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If
we don‟t mark visited vertices, then 2 will be processed again and it will become a
non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3.

void Graph::DFSUtil(int v, bool visited[])


{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent to this vertex


list<int>::iterator i;

207

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

for (i = adj[v].begin(); i != adj[v].end(); ++i)


if (!visited[*i])
DFSUtil(*i, visited);
}

// DFS traversal of the vertices reachable from v. It uses recursive DFSUtil()


void Graph::DFS(int v)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// Call the recursive helper function to print DFS traversal


DFSUtil(v, visited);
}
2. Topological Sort

 Explain in detail about topological sort. Nov/Dec 2014

Definition:

A topological sort is an ordering of vertices in a directed acyclic graph


such that if there is a path from Vi to Vj the Vj appears after Vi in the
ordering.

Steps to perform topological sort:

 Find any vertex with no incoming edges


 Print this vertex and remove it along with the edges from the graph
 Then we apply the same strategy to the rest of the graph.

208

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Pseudocode:

Example:

Fig: A directed graph

209

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Table: Result of applying topological sort

 Topological sort can be performed only if the graph doesn‟t have any
cycle
 The running time for this algorithm is O(IEI+IVI)

3. Minimum Spanning Trees

 Explain in detail about the Minimum Spanning Trees (MST).


April/May2015, May/June 2016, Nov/Dec2015
Definition:

A minimum spanning tree of an undirected graph G is a tree formed


from graph edges that connects all the vertices of G at lowest total cost.
A minimum spanning tree exists if and only if G is connected. The
number of edges in the minimum spanning tree is | V | -1. Minimum
spanning tree must be acyclic.

210

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example:

Algorithms to represent Minimum Spanning Tree:

 Prim‟s Algorithm
 Kruskal‟s Algorithm

Prim’s Algorithm:

 The idea of Prim‟s algorithm is to construct the tree in successive stages


 At each stage, one node is picked as the root and we add an edge and
thus an associated vertex to the tree
 The algorithm then finds at each stage, a new vertex to add to the tree by
choosing the edge (u,v) such that the cost (u,v) is the smallest among all
edges
 dv is the weight of the shortest path connecting v to the known vertex
 pv is the last vertex to cause a change in dv
 After a vertex V is selected, for each unknown w adjacent to v,
dw=min(dw ,cw, v)

211

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example:

Initial Configuration:

The table after V1 is declared known:

The table after V4 is declared known:

212

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The table after V2 and V3 are declared known:

213

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The table after V7 is declared known:

The table after V6 and V5 are declared known:

Minimum Spanning Tree

 The edges in the minimum spanning tee:


214

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

(v2, v1), (v3, v4), (v4, v1), (v4, v7), (v6, v7), (v7, v5)
 The total cost =16
Kruskal’s Algorithm:

 Kruskal‟s algorithm is a greedy technique


 It continually select the edges in order of smallest weight and accept an
edge if it doesn‟t cause an cycle
 The algorithm terminates when enough nodes are accepted.

Example:

Action of Kruskal’s algorithm on G:

215

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Kruskal’s algorithm after each stage:

216

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Pseudocode of Kruskal’s algorithm:

 The worst case running time of this algorithm is O(|E| log |V|)

4. Shortest Path Algorithm

 Explain in detail about single source shortest path problem of Dijkstra’s


algorithm. Nov/Dec 2014, April/May2015, May/June 2016, Nov/Dec2015

Definition:

Given an input a weighted Graph, G=(V,E) and a distinguished vertex S,


the shortest weighted path from S to every other vertex in G is called
Dijkstra‟s algorithm.

217

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example:

Initial Configuration:

After V1 is declared known:

After V4 is declared known:

218

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

After V2 is declared known:

After V5 and V3 are declared known:

After V7 is declared known:

219

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

After V6 is declared known:

Explanation:

 The starting node S is V1


 The first vertex selected is V1. The vertex is made known. The vertices adjacent
to V1 are V2 and V4. The distance of V1 to V2 is 2 and V1 to V4 is 4 and it is
marked in dv column.
 Next V4 is selected and marked known. Vertices V3, V5, V6 and V7 are adjacent.
The distance value is dv+ 1, if the already existing value is ∞. The distance
between V3 and V4 is 2. It is marked as 2+1=3. Similarly the cost for V5 is
2+1=3. The cost of V6 is 8+1=9 and the cost for V7 is 4+1=5.
 Next V2 is selected. The adjacent vertices of V2 are V4 and V5. V4 is already
known so nothing is changed. V5 is not altered because the dost(dv) will be
2+10=12 which is greater than 3 already in the table.
 The next vertex selected is V5. The adjacent vertex is V7. The cost will be
3+6=9 which is greater than 5 already in the table. So it is not altered.

220

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Then V3is selected. The adjacent vertex is V6. The cost of V6 is adjusted to
3+6=8 replacing the 9 which is already in the table.
 The next vertex selected is V7. The adjacent vertex of V7 is V6. The cost will be
5+1=6 which is adjusted since it is lesser than 8.
 The last vertex selected is V7 and nothing is altered.

Pseudocode:

221

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5.Bellman-ford algorithm

 Explain in detail about Bellman-ford algorithm.

Definition: Bellman-Ford algorithm is a procedure used to find all shortest


path in a graph from one source to all other nodes. The algorithm requires that
the graph does not contain any cycles of negative length, but if it does, the
algorithm is able to detect it.

Description:
 The Bellman-Ford algorithm is based on the relaxation operation.
 The relaxation procedure takes two nodes as arguments and an edge
connecting these nodes.
 If the distance from the source to the first node (A) plus the edge length
is less than distance to the second node, than the first node is denoted as
the predecessor of the second node and the distance to the second node
is recalculated (distance(A) + edge.length). Otherwise no changes are
applied.
 The path from the source node to any other node can be at maximum
|V|-1
edges long, provided there is no cycle of negative length.
 Hence if we perform for all nodes the relaxation operation |V|-1
, than the algorithm will find all shortest paths.
 We will verify the output by running the relaxation once more – if some
edge will be relaxed, than the algorithm contains a cycle of negative
length and the output is invalid. Otherwise the output is valid and the
algorithm can return shortest path tree.

Example:

222

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The asymptotic complexity of Bell-man Ford algorithm is (O|V|.|E|)


Pseudocode:

function <predecessors> Bellman-Ford(G, source)


for i in 1 to |U| do
distance[i] = +inf
predecessors[i] = null
distance[source] = 0

223

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

for i in 1 to (|U| - 1) do
for each Edge e in Edges(G) do
if distance[e.from] + length(e) < distance[e.to] do
distance[e.to] = distance[e.from] + length(e)
predecessors[e.to] = e.from
for each Edge e in Edges(G) do
if distance[e.from] + length(e) < distance[e.to] do
error("Graph contains cycles of negative length")
return predecessors

PART - C
1. Explain in detail about Warshall’s Algorithm. Nov/Dec 2014
Warshall’s Algorithm

Definition:

The Transitive closure of a directed graph with n vertices can be defined as n-


by-n Boolean matrix T={tij}, in which the element in the ith row {1≤j≤n) is 1 if
there exists a non-trivial directed path from ith vertex to jth vertex otherwise tij =
0.
rij(k) = rij(k-1) or rik(k-1) and rkj(k-1)

Rules for generating elements of matrix R(k) from elements of matrix R(k-1)

If ab element rij is 1 in R(k-1), it remains 1 in R(k)


If an element rij is 0 in R(k-1), it has to be changed to 1 in R(k)
If and only if the element in its row i and column k and the element in its
column j and row k are both is in R(k-1).

224

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

225

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Write and explain the algorithm to compute all pair source shortest
path using dynamic programming. April/May2015, May/June 2016
Explain in detail about Floyd’s algorithm.

It is to find the distances (the length of the shortest paths) from each vertex to
all other vertices.
It‟s convenient to record the lengths of shortest paths in an n x n matrix D
called distance matrix.
The element dij in the ith row and jth column of this matrix indicates the length
of the shortest path from the ith vertex to jth vertex (1≤ i,j ≤ n).
Floyd‟s algorithm is applicable to both undirected and directed weighted
graphs provided that they do not contain a cycle of negative length.
It computes the distance matrix of a weighted graph with n vertices thru a
series of n x n matrices.
D0, D (1), …… D (k-1) , D (k),…… D(n)

The path vi to vk is equal to dik(k-1) and vk to vij is dkj(k-1) ,the length of the
shortest path among the paths that use the kth vertex is equal to dik(k-1) + dkj(k-1).
dij(k) = min{ dij(k-1), dik(k-1) + dkj(k-1) } for k ≥ 1, dij(0) = wij.

Algorithm Floyd(w[1..n,1..n])

//Implemnt Floyd‟s algorithm for the all-pairs shortest-paths problem


// Input: The weight matrix W of a graph
// Output: The distance matrix of the shortest paths lengths
D← w
for k ← 1 to n do
for i ← 1 to n do
for j← 1 to n do

226

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

D[i,j] min {D[i,j], D[i,k] + D[k,j]}


Return D.

Efficiency:
The time efficiency is θ(n3).The principle of optimality holds for these problem
where there is an optimization.
Example:

Weight matrix Distance Matrix

227

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

228

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

INDUSTRIAL/PRACTICAL CONNECTIVITY OF THE SUBJECT

 Data Structures are used in almost every program


 Specific data structures are essential ingredients of many efficient
algorithms, and make possible the management of huge amounts of data,
such as large integrated collection of databases.
 Some programming languages emphasize data structures, rather than
algorithms, as the key organizing factor in software design.

229

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

E/B.Tech. Degree Examination, Nov/Dec 2014


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013
PART A
1. Define data abstraction[Pg.no:5]
2. Write a member function to find the greatest of two numbers using „this‟
pointer[Pg.no:5]
3. Mention any four operators of C++ that cannot be overloaded. [Pg.no:27]
4. What are pure virtual functions? Give example. [Pg.no:27]
5. Give an example on function template[Pg.no:77]
6. What is the significance of iterators[Pg.no:77]
7. Define Fibonacci Heaps. [Pg.no:125]
8. What is meant by amortized analysis? [Pg.no:125]
9. Give the ways in which a graph can be represented with an example
[Pg.no:199]
10. Define Minimum spanning tree. [Pg.no:200]
PART B
11. (a) (i) List the different types of constructors. Write a program to illustrate the
use of different types of constructors. [Pg.no:14] (10)
(ii)Brief on the features of C++ programming language [Pg.no:9] (6)
Or
(b) (i) Explain the ways in which member functions of a class can be defined
and called using a suitable example. [Pg.no:19] (10)
(ii) Explain with an example the use of static members[Pg.no:23] (6)
12. (a) (i) Write a program to perform string copy operation using dynamic
constructor[Pg.no:58] (6)
(ii)Consider the following arithmetic expressions:
C=2+B and K=S-T, where B,C,K,S AND T are the objects ofa class called
„IDArray‟. Write a program to perform these operations by overloading the

230

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

+ and – operators appropriately. [Pg.no:64] (10)

Or
(b) (i) Write a program to perform dynamic initialization of Objects. [Pg.no:75]
(6)
(ii)Write a program to illustrate the process of multilevel, multiple
inheritance concept of C++ language. [Pg.no:41&53] (10)
13. (a) (i) Write a program to illustrate the concept of re-throwing an exception.
[Pg.no:82] (8)
(ii)Write a program to read a string to store it in a file and read the same
string from the file to display it on the output device [Pg.no:102] (8)
Or
(b) (i) What is a STL? Brief on its key components and their types. [Pg.no:88]
(8)
(ii) Write a function template to find the minimum value contained in an array.
[Pg.no:95] (8)
14. (a) (i) What is a Red-Black tree? Mention the properties that a Red-Black tree
holds. [Pg.no:139] (6)
(ii)Show the results of inserting 43,11,69,72 and 30 into an initially empty
AVL tree. Show the results of deleting the nodes 11 and 72 one after the other
of the constructed tree. [Pg.no:145] (10)
Or
(b) (i) What is a B-tree? Mention the properties that a B-tree holds.
[Pg.no:152] (6)
(ii) Construct a Binary search tree by inserting 30,10,4,19,62,35,28,73 into an
initially empty tree show the results of splaying nodes 4 and 62 one after the
other of the constructed tree. [Pg.no:162] (10)
15. (a) (i) Write an algorithm for Breadth First Search on a graph and give the
nodes of the graph G given in Fig 15 a based on the algorithm [Pg.no:201] (6)
(ii) Using Dijkstra‟s Algorithm find the shortest path from the source to all
other nodes of the graph G given in fig 15a [Pg.no:215] (10)

231

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Fig 15(a)

Or
(b) (i) Illustrate the working of Warshall‟s algorithm [Pg.no:215] (6)
(ii) Consider a directed acyclic graph „D‟ given in fig 15b.Sort the nodes of D by
applying topological sort on D. [Pg.no:206](10)

A B E F

232

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/B.Tech. Degree Examination, April/May 2015


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013

PART A
1. Which is used for achieving Data Hiding in C++? List its types. [Pg.no:4]
2. With which concept, visibility and lifetime of the variables differ in C++? List its
types. [Pg.no:5]
3. Define copy constructor and its use. [Pg.no:27]
4. What are the special properties of virtual functions? [Pg.no:28]
5. Give the various file stream classes needed for file manipulation. [Pg.no:79]
6. Is Abstract base class, used to create objects? Justify your answer in brief.
[Pg.no:79]
7. How Fibonacci heaps differ from binomial heaps? [Pg.no:126]
8. What is Amortized Analysis? Show that the stack operation MULTIPOP costs O(1)
amortized time. [Pg.no:125]
9. What are the different ways to represent a graph? Explain each of them.
[Pg.no:199]
10. What is the principle behind Bellman-Ford algorithm to detect the negative weight
cycles? [Pg.no:201]
PART B
11. (a) (i) List the C++ programming features and explain in brief, how each of those
are achieved. [Pg.no:9] (8)
(ii)What do you understand by static member and static function? How to declare
them? Illustrate with an example program. [Pg.no:23] (6)
Or
(b) (i) What are the differences between pointer to constant and constant pointers?
Give an example program and explain it. [Pg.no:24] (10)
(ii) Explain the role of „this‟ pointer with suitable program. [Pg.no:24] (6)

233

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

12. (a) (i) Explain how memory is dynamically allocated and recovered in C++?
Illustrate with an example program. [Pg.no:31] (8)

(ii) List the rules associated with operator overloading? What arethe operators that
cannot be overloaded? Write a program tooverload any one of the binary
operators. [Pg.no:34] (8)
Or
(b) (i) Define a class Shape with constructor, destructor and pure virtual functions
getarea(), getperim() and draw(). Derive classes circle and rectangle from shape.
Derive another class square from rectangle. Implement this hierarchy with
essential function and write a main. [Pg.no:64] (10)
(ii)Define a class area to identify the area of square and rectangle using constructor
and destructor. Use the pararmeters length(l) and breadth(b) for the constructor
functions . [Pg.no:64] (6)

13.(a) (i) Write a program to implement stack operation using class template.
[Pg.no:95] (8)
(ii)Write a template function to sort the elements of an array [Pg.no:114] (4)
(iii) What is an exception?Explain how the control is transferred and handled in
C++ program. [Pg.no:82] (4)
Or
(b) (i) Write a program to write the text in a file. Read the text from the file, from
end of the file. Display the contents of file in reverse order. Append the
contents to the existing file [Pg.no:114] (10)
(ii) Discuss about the different components in STL. [Pg.no:88] (6)
14. (a) (i) Perform the splaying operation on a binary search tree obtained by inserting
the key values 1,2,3,4,5,6,7,8 in this order into an initially empty tree. Write the
code to do the same(splay and insert) [Pg.no:162] (10)
(ii)on an initially empty binomial heap, carry out the following sequence of
operations: insert(27), insert(17), insert(19), insert(20), insert(24), insert(12),
insert(11), insert(10), insert(14), insert(18), Deletemin. After each operation
draw resulting structure of the binomial heap. [Pg.no:166] (6)

234

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Or
(b) (i) Construct an AVL tree with the values 3,1,4,5,9,2,8,7,0 into an initially
empty tree. Write the code for inserting into an AVL tree. [Pg.no:145] (10)
(ii) Construct a B-tree with order M=3 for the key values 2,3,7,9,5,6,4,8,1 and
delete the values 4 and 6. Show the tree in performing all operations.
[Pg.no:152] (6)

15.(a) Explain Prim‟s and kruskals algorithm. Find the minimum spanning tree for the
following graph using any one of the algorithms. [Pg.no:208] (16)

Or
(b) for the given graph, [Pg.no:215]
(i) find the shortest path from vertex 1 to all other vertices. (8)
(ii) Find the shortest path from each vertex to all other vertices. (8)
Mention and use the appropriate algorithm.

235

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/B.Tech. Degree Examination, Nov/Dec 2015


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013
PART A
1. Give the significance of declaring a member of a class static. [Pg.no:4]
2. What is the use of „this‟ pointer? [Pg.no:8]
3. How the C string differs from a C++ type string? [Pg.no:28]
4. What is dynamic initialization of objects? [Pg.no:28]
5. Compare overloaded functions versus function templates. [Pg.no:79]
6. When do we use multiple catch handlers? [Pg.no:80]
7. What are the various operations that can be performed on B-trees? [Pg.no:127]
8. What are splay trees? [Pg.no:127]
9. What is the minimum number of spanning trees possible for a complete graph with n
vertices? [Pg.no:200]
10. What is topological sorting? [Pg.no:200]
PART B
11. (a) (i) How can you specify a class? [Pg.no:9] (6)
(ii)Describe the different mechanisms of accessing data members and member
functions in a class with suitable example. [Pg.no:19] (10)
Or
(b) (i) Explain the different types of constructors with suitable examples.
[Pg.no:14](10)
(ii) Describe the types of storage classes. [Pg.no:5] (6)
12. (a) (i) Write a C++ program to overload the increment operator with prefix and
postfix forms. [Pg.no:34] (12)

(ii) Distinguish the term overloading and overriding. [Pg.no: 44] (4)
Or
(b) (i) Write a C++ program to explain how the run time polymorphism is achieved.
[Pg.no:47] (10)
236

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

(ii)illustrate any four types of inheritance supported in C++ with suitable examples.
[Pg.no:41] (6)
13.(a) (i) Write a function template for finding the maximum value in an array.
[Pg.no:114] (8)
(ii)Write a C++ program to handle a divide by zero exception [Pg.no:82] (4)

Or
(b) (i) Describe the components of STL [Pg.no:88] (8)
(ii) Write a class template to represent a stack of any possible data type. [Pg.no:95](6)

14. (a) (i) Define AVL tree and starting with an empty AVL search tree, insert the
following elements in the given order:35,45,65,55,75,12,25 [Pg.no:145] (8)
(ii)Explain the AVL rotations with suitable example. [Pg.no:145] (8)
Or
(b) Illustrate the construction of Binomial heaps and its operations with a suitable
example [Pg.no:166] (16)

15.(a) (i) Compute the minimum spanning tree for the following graph (8)
[Pg.no:208]

(ii)Discuss any two applications of depth-first search. [Pg.no:201] (8)


Or

(b) Explain the Dijkstra‟s algortithm for finding the shortest path with a sample
graph [Pg.no:215] (16)

237

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/B.Tech. Degree Examination,May/June 2016


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013
PART A
1. When do you declare a member of a class static? [Pg.no:4]
2. List out the advantages of storage class. [Pg.no:5]
3. How does a C string differs from a C++ type string? [Pg.no:23]
4. Distinguish the term overloading and overriding. [Pg.no:24]
5. Distinguish the term template class and class template. [Pg.no:81]
6. List out the types of containers. [Pg.no:81]
7. List out the various operations that can be performed on B-trees. [Pg.no:127]
8. What is amortized analysis? [Pg.no:125]
9. What are the different ways to represent graphs? [Pg.no:199]
10. List out the applications of depth-first search. [Pg.no: 200]
PART B
11. (a) (i) Describe the different mechanisms for accessing data members and member
functions in a class with a suitable example. [Pg.no:19] (10)
(ii)Explain the role of this pointer [Pg.no:24] (10)
Or
(b) What is a constructor? Explain the different types of constructors with suitable
examples. [Pg.no:14] (16)
12. (a) (i) Write a C++ program to overload the decrement operator with prefix and
postfix forms [Pg.no:34] (8)

(ii) Write any two types of inheritance supported in C++ with suitable examples.
[Pg.no:41] (8)
Or
(b) With suitable C++ program explain how the polymorphism is achieved at
compile time and run time. [Pg.no:59] (16)

238

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

13.(a) (i) Write a class template to represent a queue for any possible data type
[Pg.no:114] (8)
(ii)Illustrate about how exceptions are handled using multiple catch handlers
[Pg.no:82] (8)

Or
(b) (i) Explain the components of STL [Pg.no:88] (8)
(ii) Write a C++ program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is replaced by
a single space. [Pg.no:114] (8)
14. (a) (i) Define AVL tree and starting with an empty AVL search tree, insert the
following elements in the given order:2,1,4,5,9,3,6,7 [Pg.no:145] (8)
(ii)Explain the AVL rotations with suitable example. [Pg.no:145] (8)
Or
(b) Implement the fibonacci heaps and compare their performance with binary
heaps when used in Dijkstra‟s algorithm [Pg.no:166] (16)

15.(a) (i) Illustrate the Dijkstra‟s algorithm for finding the shortest path with the
following graph. [Pg.no:215] (12)

(ii)Illustrate the comparison of Floyd‟algorithm with Dijktra‟s algorithm.


[Pg.no:215] (4)

Or

239

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

(b) Find the minimum spanning tree for the given graph using both Prim‟s and
Kruskal‟s algorithm and write the algorithms. [Pg.no:208] (16)

240

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/B.Tech. Degree Examination, Nov/Dec 2016


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013
Part A - (10 x 2 = 20 Marks)
1. List the various storage classes available in C++.[Pg.no:4]
2. Mention the role of this pointer. [Pg.no:5]
3. Give the list of operators that cannot be overloaded. [Pg.no:23]
4. Differentiate Compile and run time polymorphism. [Pg.no:24]
5. What is an abstract Class? [Pg.no:81]
6. What is a function adaptor? [Pg.no:81]
7. State the uses of virtual functions. [Pg.no:127]
8. Write a note on amortized analysis. [Pg.no:125]
9. Define minimum spanning tree for a graph. [Pg.no:199]
10. List the drawbacks of Floyd-Warshall algorithm. [Pg.no: 200]

Part B - (5 x 13 = 65 Marks)
11. (a) (i) Explain features of object oriented programming in detail. [Pg.no:9] (7)
(ii) Discuss the types of constructors with examples. [Pg.no:14] (6)
Or
(b) (i) What do you mean by static member function? Explain in detail with an
example. [Pg.no:23] (7)
(ii) Give a detailed note on const member function. [Pg.no:24] (6)
12. (a) Describe in detail dynamic memory allocation in C++ with examples.
[Pg.no:33] (13)
Or
(b) Explain the types of inheritance in detail. [Pg.no:41] (13)
13. (a) (i) Write short notes on C++ exception handling. [Pg.no:82] (7)
(ii) Write a C++ program to write a set of characters to a file. [Pg.no:102] (6)
Or
(b) Explain in detail about different STL containers. [Pg.no:88] (13)
14. (a) Explain the possible AVL rotations with algorithm and example.
[Pg.no:145] (13)
Or
(b) Explain insertion and deletion operations on Fibonacci heaps. Construct
Fibonacci heaps for the following set of elements 10, 11, 5, 35, 8, 4, 2, 3, 77, 1, 45.
[Pg.no:167] (13)
15. (a) Present the pseudo-codes of the different graph traversal methods and
demonstrate with an example. [Pg.no:208] (13)

241

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Or
(b) Explain how transitive closure of a graph can be found using Warshalls algorithm.
[Pg.no:222] (13)
PART C - (1 x 15 = 15 marks)
16. (a) Using Dijkstra's algorithm find the shortest path from the source node A.
[Pg.no:208] (15)

(b) Write a C++ generic function with multiple parameters that performs
recursive binary search on a linear array. [Pg.no:54] (15)

242

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/B.Tech. Degree Examination, Nov/Dec 2016


Third Semester
Computer Science and Engineering
CS6301-PROGRAMMING AND DATASTRUCTURES II
Regulation 2013
Part A - (10 x 2 = 20 Marks)
1. List the features of Object Oriented C++ programming. [Pg.no:4]
2. What is the role of 'this' pointer. [Pg.no:8]
3. Define multiple inheritance. Give Example. [Pg.no:28]
4. List different operators of C++ that can be overloaded. Give one example.
[Pg.no:28]
5. Define abstract class. Give Example. [Pg.no:79]
6. State the uses of templates in C++ programming. [Pg.no:80]
7. Define Balance Factor of AVL Tree. [Pg.no:127]
8. List the properties of Red Black Trees. [Pg.no:127]
9. State the principle of Topological Sorting. [Pg.no:200]
10. Write procedure for Depth First Search algorithm. [Pg.no:200]

Part B - (5 x 13 = 65 Marks)
11 (a) Define class and object. Explain different types of constructors using
C++.[Pg.no:9]
Or
(b) Explain the different types of storage classes of C++ using suitable
examples. [Pg.no:23]
12. (a) Demonstrate the following string operations using C++ program-
[Pg.no:58]
(i) finding the length of the string
(ii) finding the substring from the string
(iii) replace a given substring in a string
(iv) concentrate two strings
(v) compare two strings
(vi) insert a substring in a given string
Or
(b) Assume the classes Person Student and PartTimeStudent are inherited
from one another. Define classes with suitable data members (common and special
attributes) and methods using C++ program to demonstrate the types of inheritance.
[Pg.no:41]
13. (a) (i) Define STL. Explain its key components and types (5) [Pg.no:88]
(ii) Write C++ code using function template to sort items of an array
(8) [Pg.no:92]

243

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Or
(b) (i) Write C++ file handling routing to copy one content of file into
another file. [Pg.no:102] (7)
(ii) Explain the use of exception handling in C++ with example.
[Pg.no:82] (6)
14. (a) (i) Merge the given Binomial heaps. Write procedure for merge
operation. (5+3) [Pg.no:166]

(ii) Delete three elements from the merged Binomial Queue.


[Pg.no:176] (5)
Or
(b) (i) Draw B-tree of order m = 5 for the keys
{K, O, S, V, M, F, B, G, T, U, W} (6)
(ii) Delete the keys K and G in order. (4)
(iii) Justify the number of splits needed for insert/delete with proper
reasons. (3) [Pg.no:160]

15. (a) Consider the following graph. Determine the shortest distance to all
other nodes using Dijikatra's algorithm. Write Procedure [Pg.no:208]

244

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Or
(b) Determine the minimum spanning tree of a given graph using Krushal's
algorithm. Write Kruskal's MST algorithm. [Pg.no:222]

Part C - (1 x 15 = 15 marks)
16. (a) Assume the following keys from the Binary Search tree {50, 30, 60, 40,
35, 80, 90}. Analyze the time complexity involved in searching the keys 90 and then
80, when the given BST is converted into AVL or Splay tree. Identify the suitable tree
data structure for representing this data and justify your answer with valid reasons.
[Pg.no:145]
Or
(b) The Manager Class is derived from Employee class. Use C++ virtual
function to calculate salary of Employee/Manager class. Increments for employees
differ based on their category. Implement this scenario using C++ code to calculate
the monthly and annual payment of each employee category. [Pg.no:23]

245

Visit & Downloaded from : www.LearnEngineering.in

You might also like