Professional Documents
Culture Documents
in
ENGINEERING COLLEGES
2017 – 18 Odd Semester
IMPORTANT QUESTIONS & ANSWERS
Department of CSE
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
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
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
UNIT I
OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
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.
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
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
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);
};
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
Eg:
float total = 100;
float sum = total;
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]
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
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
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
Shape
Draw()
Dynamic Binding
12
Message Passing
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
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
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
Default Constructor
Output:
5 10
15
Parameterized Constructor
16
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
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
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
}
};
void main()
{
sample obj;
obj.getdata();
obj.sum();
}
20
cout<<sum;
}
void main()
{
sample obj;
obj.getdata();
obj.sum();
}
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.
#include<iostream.h>
class sample
{
public:
int a;
void display()
{
cout<<a;
}
21
};
void main()
{
sample obj;
obj.a=5; //Public Variable
obj.display();
}
22
Example:
class sample
{
static int num;
public:
static void increment()
{
num++;
}
void display()
23
{
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
#include<iostream.h>
class sample
{
int num;
public:
sample(int x)
24
{
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
25
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;
} }
Part - C
#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
}
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
{
q++;
cout<< "\nRoll No of "<<q<<" Student : "<< p->rn;
cout<< "\nFee of "<<q<<" Student is : "<< p->fees;
p++;
}
getch();
}
#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
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
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(?:)
30
};
main()
{
A a,b;
int x,y;
cin>>x>>y;
//Respective constructors are called and initialized
a=A(x);
b=A(x,y);
}
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
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.
33
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
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
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.
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
array[i]=i+1;
cout<<array[i]<<" ";
}
delete[]array;
return0;
}
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
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:
37
Unary operators:
op x or x op
Binary operators:
x op y
Unary operators operate on a single operand with the user defined data types.
Examples of unary operator are:
38
The increment and decrement operators fall into a special category because there are
two variants of each:
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
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
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
#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
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:
43
------
44
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
Syntax:
class derivedclass:accessspecifier base_class
{
---
};
#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
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
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
Multilevel Inheritance:
Syntax:
class Base
{
----
48
};
class derived1:accessspecifier Base
{
----
};
class derived2:accessspecifier derived1
{
----
};
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
cout<<"Gender: "<<gender<<endl;
}
};
50
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
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
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
person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};
54
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
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
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
{
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
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:
Example:
Combination of multilevel and multiple inheritance
59
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
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
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
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.
#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
}
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
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
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.
66
{
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
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
{
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
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
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
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
{
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
{
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
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
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
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.
# include <iostream.h>
# include <conio.h>
# include <string.h>
76
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
{
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
#include<iostream.h>
class A
{
int a;
public:
A(int b){a=b;}
friend A operator+(A,A);
void display()
{
78
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
UNIT-III
C++ PROGRAMMING ADVANCED FEATURES
PART-A
80
}
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:
81
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.
82
}
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
83
{
//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.
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
ios::out
Open a file for output (default for ofstream objects)
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
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:
86
try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}
catch(int i)
{
87
getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40
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.
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
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.
#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
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
{
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)
91
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:
1)Sequence containers
2)Associative containers
3)Derived containers
Sequence Container:
iterator
begin()
92
Elements in all these containers can be accessed using an iterator. The difference
between three of them are related by the performances.
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
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
94
Output examples:
#include<iostream.h>
void main()
{
stack<string> allwords;
string word;
while(cin>>word)
{
95
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.
96
Example:
using namespace std;
void main()
{
vector<int> myIntVector;
vector<int>::iterator myIntVectorIterator;
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
Class template:
Syntax:
template<class T>
class classname
{
…..
};
Example:
98
#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
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
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>
101
min=arr[i];
}
return(min);
}
void main()
{
clrscr();
int iarr[5];
char carr[5];
double darr[5];
getch();
}
102
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.
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
#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
O/P:
test1: 1.5 and 34
test2: 45 and A
File handling:
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
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
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:
107
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
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
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
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::ofstream os("filename.txt");
cout<<"Writing to a file\n";
os << s;
os.close();
ifstream is("filename.txt");
is>>s;
cout<<s<<endl;
O/P:
hello world
111
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
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.
Example:
include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using std::cout;
using std::endl;
typedef std::vector <int>::const_iterator const_iterator;
112
{
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;
113
Negators
The negator function adaptor can be used to store the opposite result of a function
object.
Example:
#include<iostream.h>
using namespace std;
void main()
114
{
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
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
116
#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
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:
#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
O/P:
#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
{
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
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
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
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
#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();
124
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:
copied......
Target File Contents....
125
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 () {
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
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
UNIT IV
ADVANCED NON-LINEAR DATA STRUCTURES
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
128
3. How does a Fibonacci heap differ from binomial heaps? (April/May 2015)
S.No Binomial Heap Fibonacci Heap
2 Trees within binomial heaps are Trees within Fibonacci heaps are
arranged monotonically rooted but unordered.
increasing order of degree.
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.
129
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.
130
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
131
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.
132
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.
133
134
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
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
137
}
}
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
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.
8 8
4 4
1 6 1
139
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.
8 8
4 5
1 6 1 6
140
141
2. Red-Black Tree
142
Case 1
Case 2
143
Transform to case 3
Case 3
Example:
144
145
Case 1
x's sibling is red
Case 2a
x's sibling is black
x's parent is black
Case 2b
x's sibling is black
x's parent is red
146
Case 3
Case 4
147
3. AVL Tree
148
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 α.
149
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
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;
}
150
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
151
{
K1 -> Right = SingleRotateWithLeft(K1 -
Right); return SingleRotateWithRight (K1);
}
#ifndef
_AvlTree_H struct
AvlNode;
152
{
if( P = = NULL)
return -1;
else
return P -> Height;
}
153
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
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.
155
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 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 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
157
// 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)
}
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);
158
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.
159
returning.
}
}
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
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
162
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
164
5.Splay Tree
Define splay tree. Explain the splaying operation with its code in detail.
(Nov/Dec 2014, April/May 2015)
Novel characteristics:
Does not require any accounting information (color, level, height, etc.)
165
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
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.
167
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
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:
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
The name comes from the shape: a binomial tree of order has nodes at
depth .
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
170
• 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
• 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:
• Example:
• Create heap
• Find minimum key
172
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
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
174
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
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
Binomial-Heap-Insert(H,x)
1 H‟ <- Make-Binomial-Heap()
2 p[x] <- NIL
3 child[x] <- NIL
176
• 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
4 H <- Binomial-Heap-Union(H,H‟)
5 Return x
178
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
Delete a Node:
Binomial-Heap-Delete(H,x)
1 Binomial-Heap-Decrease-Key(H,x,-∞)
2 Binomial-Heap-Extract-Min(H)
180
Binomial Tree:
A binomial tree of order 0 is a single node. A binomial tree of order k has a
181
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
Node Pointers
- left [x]
- right [x]
- degree [x]
- number of children in the child list of x
- mark [x]
Properties:
Find Min
183
Insert
Example
Min [H]
3
23 7 17 24
18 52 38 30 26 46
39 41 35
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
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
0 1 2 3 4
A
w,x
7 21 18 52 38
24 17 23 39 41
26 46 30
35
186
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
min [H]
7 18 38
24 17 23 21 39 41
26 46 30 52
35
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
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
min [H]
15 7 18 38
24 17 23 21 39 41
30 52
26
35
189
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
2. Amortized Analysis
191
192
193
194
– 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).
195
196
• Thus the worst case running time is O(n) for a sequence of n INCREMENTs.
So the amortized cost per operation is O(1).
198
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
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
UNIT V
GRAPHS
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.
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
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
Example:
202
Example:
204
Traversals:
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
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
206
}
}
}
}
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.
207
Definition:
208
Pseudocode:
Example:
209
Topological sort can be performed only if the graph doesn‟t have any
cycle
The running time for this algorithm is O(IEI+IVI)
210
Example:
Prim‟s Algorithm
Kruskal‟s Algorithm
Prim’s Algorithm:
211
Example:
Initial Configuration:
212
213
(v2, v1), (v3, v4), (v4, v1), (v4, v7), (v6, v7), (v7, v5)
The total cost =16
Kruskal’s Algorithm:
Example:
215
216
The worst case running time of this algorithm is O(|E| log |V|)
Definition:
217
Example:
Initial Configuration:
218
219
Explanation:
220
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
5.Bellman-ford algorithm
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
223
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:
Rules for generating elements of matrix R(k) from elements of matrix R(k-1)
224
225
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])
226
Efficiency:
The time efficiency is θ(n3).The principle of optimality holds for these problem
where there is an optimization.
Example:
227
228
229
230
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
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
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
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
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
(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
(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]
(b) Explain the Dijkstra‟s algortithm for finding the shortest path with a sample
graph [Pg.no:215] (16)
237
(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
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)
Or
239
(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
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
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
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
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]
15. (a) Consider the following graph. Determine the shortest distance to all
other nodes using Dijikatra's algorithm. Write Procedure [Pg.no:208]
244
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