skp engineering college -...

93
SKP Engineering College Tiruvannamalai 606611 A Course Material on Programming and Data Structures - II By A.Owaise Ahmed Assistant Professor Computer Science and Engineering Department

Upload: duongdang

Post on 18-Aug-2019

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

SKP Engineering College

Tiruvannamalai – 606611

A Course Material

on

Programming and Data Structures - II

By

A.Owaise Ahmed

Assistant Professor

Computer Science and Engineering Department

Page 2: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 2 PDS-II

Quality Certificate

This is to Certify that the Electronic Study Material

Subject Code: CS6301

Subject Name: Programming and Data Structures -II Year/Sem: II/III

Being prepared by me and it meets the knowledge requirement of the

University curriculum.

Signature of the Author

Name: A.Owaise Ahmed

Designation: Assistant Professor

This is to certify that the course material being prepared by Mr. A.Owaise Ahmed is

of the adequate quality. He has referred more than five books and one among them

is from abroad author.

Signature of HD Signature of Principal

Name: K.Baskar Name: Dr.V.Subramania Bharathi Seal: Seal:

Page 3: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 3 PDS-II

CS6301 PROGRAMMING AND DATA STRUCTURES - II L T P C 3 0 0 3

OBJECTIVES: The student should be made to:

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

polymorphism, overloading and Inheritance.

Learn advanced nonlinear data structures.

Be exposed to graph algorithm.

Learn to apply Tree and Graph structures

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

OUTCOMES:

At the end of the course, the student should be able to:

Design problem solutions using Object Oriented Techniques

Apply the concepts of data abstraction, encapsulation and inheritance for problem

solutions.

Use the control structures of C++ appropriately.

Critically analyse the various algorithms.

Apply the different data structures to problem solutions.

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

Page 4: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 4 PDS-II

CONTENTS

S. No Particulars Page

1 Unit – I 5

2 Unit- II 31

3 Unit – III 46

4 Unit – IV 56

5 Unit – V 81

Page 5: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 5 PDS-II

UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS

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

static members – constant members – member functions – pointers – references - Role of this

pointer – Storage classes – function as arguments.

PART - A

1. Define object oriented programming. [CO1 – L1] Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating such modules on demand.

2. List out the features of OOPS. [CO1 – L1]

Classes

Objects

Data abstraction

Data encapsulation

Inheritance

Polymorphism

Message passing

Extensibility

Persistence

Delegation

Genericity

Dynamic binding.

3. List out the benefits of oops. [CO1 – L1]

Can create new programs faster because we can reuse code

Easier to create new data types

Easier memory management

Programs should be less bug-prone, as it uses a stricter syntax and type checking.

`Data hiding', the usage of data by one program part while other program parts cannot access the data will whiten your teeth

4. List out the application of oops. [CO1 – L1]

Client server computing

Simulation such as flight simulations.

Object-oriented database applications.

Artificial intelligence and expert system

Computer aided design and manufacturing systems.

Real time systems, such as process control, temperature control.

Page 6: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 6 PDS-II

5. What are objects? How are they created? [CO1 – L1] Objects are basic run-time entities in an object-oriented programming system. The class Variables are known as objects. They may represent a person, a place or any data item. Objects contain data and code to manipulate data. Objects are created by using the syntax: classname obj1,obj2,…,objn; (or) during definition of the class: class classname {

-------

-------

}obj1,obj2,…,objn; 6. What is a class? [CO1 – L1] The entire set of data and code of an object that can be made a user defined data type with the help of a class. A class is a collection of objects of type class.

7. What is an identifier? [CO1 – L1] Identifiers are names for various programming elements in c++ program. such as variables, arrays,function, structures, union, labels ect., An identifier can be Composed only of uppercase, lower case letter, underscore and digits, but should start only with an alphabet or an underscore.

8. What is a keyword? [CO1 – L1] Keywords are word whose meanings have been already defined in the c compiler. They are also called as reserved words. (ex) main(), if, else, else, if, scanf, printf, switch, for, goto, while ect.,

9. Define constant in c++. [CO1 – L1] Constants in c++ refers to fixed values that do not change during execution of a program.

10. Define a variable. [CO1 – L1] A quantity, which may vary during execution of a program is called as a variable.

11. What are unary operators? [CO1 – L1] The operators that act upon a single operand are called as unary operators. The unary operators used in c++ are - , ++, -- and sizeof operators.

12. What are binary operators? [CO1 – L1]

The operators that act upon two operands are called binary operators. The binary operators used

in c++ are +, -, *, / , %, =. etc.,

13. What are ternary operators? [CO1 – L1]

The operators that act upon three operands are called as ternary operators. The ternary operator

available in c++ is (?:).This operator is also referred as conditional operator.

14. What is the use of new operator? [CO1 – L1]

The new operator is used to allocate contiguous unnamed memory during execution time and

returns a pointer to the start of it.

Page 7: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 7 PDS-II

15. What is the different between a pre-increment and post-increment operator. [CO1 – L1] A pre-increment operation such as ++a, increments the value of a by 1,before a is used for computation, while a post-increment operation such as a++, uses the current value or present value of a in the calculation and then increments the value of a by 1.

16. What is meant by an expression? [CO1 – L1] An expression is a combination of constant, variable, operators and function calls written in any form as per the syntax of the c++ language.

17. Difference between c and c++. [CO1 – L2] C C++

(i) Procedural programming language Object-oriented programming anguage

(ii) Global variable can be declared It is an error to declare a variable as global

(iii) Function prototypes are optional All functions must be prototyped. (iv) Local variables can be declared only Local variables can be declared anywhere the start

of a c program in a c++ program.

(v) We can call a main() function, within This is not allowed a program.

18. Define modular programming. [CO1 – L1] It is a process of splitting a large program in to smaller modules to perform the operations fast and, which helps in easy error checking. Modules should be designed, implemented and documented with regard to their possible future use in other projects.

19. Define data abstraction. [CO1 – L1 - Nov/Dec 2014] The technique of creating new data types that are well suited to an application to be programmed is known as data abstraction.

20. What is data encapsulation? [CO1 – L1] The wrapping up of data and functions into a single unit called class is known as data

encapsulation. 21. What is data hiding? [CO1 – L1] The insulation of the data from direct access by the program is called data hiding or information hiding

22. What are inheritance / reusability / derivation? [CO1 – L1]

Inheritance is the process by which objects of one class acquire the properties of objects of

another class.

The concept of inheritance provides the idea of reusability. This means that we can add

additional features to an existing class without modifying it.

Derivation involves the creation of new classes (derived class) from the existing ones (base class). 23. What is polymorphism? [CO1 – L1] Polymorphism means the ability to take more than one form.

24. What is the use of a break statement? [CO1 – L1] A break construct terminates the execution of loop and the control is transferred to the statement immediately following the loop. The term break refers to the act of breaking out of a block of code.

Page 8: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 8 PDS-II

25. What is the use of a continue statement? [CO1 – L1] The continue statement skips the remainder of the current iteration initiates the execution of the next iteration. 26. Distinguish between break and continue statement. [CO1 – L2] Break continue

a) Used to terminate the loops or to Used to transfer the control to the Exit loop from a switch. Start of loop.

b) The break statement when executed The continue statement when causes Immediate termination of loop executed caused immediate containing it. Termination of the current iteration of the loop.

27. Distinguish between while and do-while loop. [CO1 – L2]

While loop do-while loop

a) The while loop tests the condition The do-while loop tests the condition before each iteration

after the first iteration

b) If the condition fails initially the loop Even if the condition fails initially Is skipped entirely

even in the first the loop is executed once Iteration.

28. Define function. [CO1 – L1]

The process of splitting a large program into small manageable tasks and designing them

independently is popularly called modular programming or divide and conquer technique. A

repeated group of instructions in a program can be organized as a function. A function is a set of

program statements that can be processed independently.

29. What is a pointer? What are the uses of a pointer? [CO1 – L1]

Pointer is defined as a variable used to store memory addresses.

Uses:

• Accessing array elements.

• Passing arguments to a function when the function needs to modify the original.

• Passing arrays and strings to functions.

• Creating data structures such as linked lists, binary tree etc .

• Obtaining memory from the system dynamically. 30. What is a friend function? [CO1 – L1] Friend function is a special type of function which is used to access all the private and protected members of a class. The functions that are declared with the keyword friend are called friend functions. A function can be a friend to multiple classes. 31. What are the properties of a friend function? [CO1 – L1] • A friend function is not in the scope of the class to which it has been declared as friend.

• It can be invoked like a normal function without the help of any object. • Unlike member functions it cannot access the member names directly and has to use an object

name and dot membership with each member name.

32. What is the difference between friend function and member function? [CO1 – L1] The only difference between a friend function and member function is that, the friend function requires the argument to be explicitly passed to the function and processes them explicitly, whereas, the member function considers the first argument implicitly.

Page 9: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 9 PDS-II

33. What is an inline function? [CO1 – L1] Inline functions are those whose function body is inserted in place of the function call statement during the compilation process. With the inline code the program will not incur any context switching overhead.

34. What is a recursive function? [CO1 – L1] A function that contains a function call to itself or a function call to a second function which eventually calls the first function is known as recursive functions.

35. What is the difference between normal function and a recursive function? [CO1 – L1] A recursive function is a function, which call it whereas a normal function does not. Recursive function can‟t be directly invoked by main function

36. What is data conversion? [CO1 – L1] When we use the assignment operator we assign a value on the right hand side to a variable on the left side & if it is of a different data type then we have to perform data conversion or type conversion. 37. What are the methods of data conversion? [CO1 – L1] There are two methods for data conversion:

(i) Implicit data conversion (ii) explicit data conversion 38. Give the structure of a C++ program. [CO1 – L1] Include files

Class definition

Member function definitions Main function

39. What is function prototype? [CO1 – L1] Function prototype is otherwise known as function declaration. The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values.

40. What is a class? How will you define a class? [CO1 – L1] A class is a way to bind the data and its associated functions together. A class specification has two parts: Class Declaration

Class function definition

41. What are the characteristics of a static data member? [CO1 – L1] • Static data member is initialized to zero when the first object of its class is created. No

other initialization is permitted. • Only one copy of that member is created for the entire class and is shared by all the

objects of that class, no matter how many objects are created. • It is visible only within the class, but its life time is the entire program.

42. What are the properties of a static member function? [CO1 – L1] • A static function can have access to only other static members, declared in the same

class.

• A static member function can be called using the class name as follows

Classname :: function-name;

Page 10: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 10 PDS-II

43. Write a Member function to find the greatest of two numbers using ‘this’ pointer.

[CO1 – L1 - Nov/Dec 2014] #include <iostream>

using namespace std;

class Box

{ public:

// Constructor definition

Box(double l=2.0, double b=2.0, double h=2.0)

{ cout <<"Constructor called." << endl; length = l; breadth = b; height = h; }

double Volume()

{

return length * breadth * height;

}

int compare(Box box)

{

return this->Volume() > box.Volume();

}

private:

double length; // Length of a box double breadth; // Breadth of a box

double height; // Height of a box

};

int main(void)

{

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2))

{

cout << "Box2 is smaller than Box1" <<endl;

}

else

{

cout << "Box2 is equal to or larger than Box1" <<endl;

}

return 0; }

Page 11: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 11 PDS-II

44. Which is used for achieving Data Hiding in C++? List its types. [CO1 – L1 - Apr/May

2015] Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally. Two kinds of abstractions in programming languages are process abstraction and data abstraction. 45. Define process abstraction and data abstraction. [CO1 – L1] The concept of process abstraction is one of the oldest. All subprograms are process abstractions because they provide a way for a program to specify that some process is to be done, without providing the details of how it is to be done. Process abstraction is crucial to the programming process. The ability to abstract away many of the details of algorithms in subprograms makes it possible to construct, read, and understand large programs. All subprograms, including concurrent subprograms, and exception handlers, are process

abstractions 45. With which concept, visibility and lifetime of the variables differ in C++? List its types.

[CO1 – L1 - Apr/May 2015] A storage class defines the scope (visibility) and life-time of variables and/or functions within a

C++ Program. These specifiers precede the type that they modify. There are following storage

classes, which can be used in a C++ Program

auto

register

static

extern

mutable

46. In what way is a private member function different from public member function? [CO1 – L1] A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot operator.

Page 12: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 12 PDS-II

PART – B

1. List the C++ programming features and explain in brief, how each of those are achieved.(8) [CO1 –

L1 - Apr/May 2015] Brief on the features of C++ programming language.(6)(Nov/Dec 2014) BASIC FEATURES OF OBJECT ORIENTED PROGRAMMING These include:

Objects

Classes

Data abstraction and encapsulation

Inheritance

Polymorphism

Dynamic binding

Message passing

Objects: Objects are the basic run-time entities in an object oriented programming. They may represent a

person, a place, a bank account or any item that the program has to handle. They may represent

user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of

objects and the nature of communication b/n them.

When a program is executed, the objects interact by sending messages to another. Each object

contains data and code to manipulate the data. Objects can interact without having to know the

details of each other‟s data or code. It is sufficient to know the type of message accepted, and the

type of message accepted and the type of response returned by the objects.

Classes: A class is a way to bind the data and its associated functions together. It allows the data to be

hidden ifnecessary from external use. While defining a class, we are creating a new abstract data

type that can be treated as abuilt-in data type. A class Specification has two parts:

1. Class declaration – describes the type & scope of its members 2. Class function definitions – describe how the class functions are implemented. 3. The keyword class specifies that what follows is an abstract data of type class_name. 4. The body of the class is enclosed within braces and terminated by a semicolon.

The class body contains the declaration of variables and functions. These functions and

variables are collectivelycalled class members. o The keywords private and public are known as

visibility labels and it specify which members are private which of them are public. These should

followed by a colon. Private members can be accessed only within the class whereas public members can be accessed

form outside the class. By default, the members of a class are private. If both the labels are

missing, the members are private to the class.

// Program to demonstrate objects to print the student name : #include<iostrea.h>

Page 13: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 13 PDS-II

#include<string> using namespace std; class student

{

public : intRollno;

char Name[20];

char Address[20];

void GetDetails()

{ cout<<” Enter the roll number”; cin>>Rollno; cout<<” Enter the Name; cin>>Name;

cout<<”Enter the Address”;

cin>>Address;

}

void PrintDetails()

{ cout<<”Roll Number is ”<<Rollno<<”\n”; cout<<”Name is ”<< Name<<”\n”;

cout<<”Address is ”<< Address<<”\n”;

} };

void main( )

{

student Student1; Student1.GetDetails();

Student1.PrintDetails( ); 10 } OutPut:Roll Number is:11 Name is:saran

Address is: chennai Data Abstraction: Abstraction represents the act of representing the essential features without including the

background details orexplanations.

Classes use the concept of abstraction and are defined as a list of abstract attributes such as

size,weight and cost and functions to operate on these attributes.

The attributes are called data members and functions arecalled member functions or methods.

Abstraction is useful for the implementation purpose.

Actually the end userneed not worry about how the particular operation is implemented. They

should be facilitated only with theoperations and not with the implementation.For example,

Applying break is an operation.

It is enough for the person who drives the car to know how pressure hehas to apply on the break

pad rather than how the break system functions. The car mechanic will take care of the breaking

system.

Page 14: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 14 PDS-II

Data Encapsulation The wrapping up of data and functions into a single unit is known as encapsulation. It is the most

striking feature ofthe class.

The data is not accessible to the outside world and only those functions which are wrapped in the

class can access it.

These functions provide interface between the object‟s data and the program. This insulation of

the data from direct access by the program is called data hiding or information hiding. 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. For example, the person „son‟ is a part of

the class „father‟ which is again apart of the class „grandfather‟.

This concept provides the idea of reusability. This means that we can add additional features to

an existing classwithout modifying it.

This is possible by a deriving a new class from an existing one. The new class will have the

combined features of both the classes.

Types Of Inheritance: Single inheritance

Multiple inheritance

Hierarchical inheritance

Multiple Level inheritance

Polymorphism: Polymorphism is the ability to take more than one form. An operation may exhibit different

behavior depends upon the types of data used in the operation.

Consider the operation of addition. For two numbers, the operation will generate a sum.

If the operands are strings, then the operation would produce a third string by concatenation.

The process of making an operator to exhibit different behaviors in different instances is

known as operator overloading.

shapes Draw()

Triangle object Box object circle

object Draw(circle)

Draw (box)

Page 15: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 15 PDS-II

Draw (Triangle)

Polymorphism A single function name can be used to handle different types of tasks based on the number

and types of arguments.This is known as function overloading.

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

Dynamicbinding (also known as late binding) means that the code associated with a given

procedure call is known until thetime of the call at run-time. It is associated with polymorphism

and inheritance.

Message Passing The process of programming in OOP involves the following basic steps: Creating classes that

define objects and their behavior.

Creating objects from class definitions

Establishing communication among objects

A message for an object is request for execution of a procedure and therefore will invoke a

function (procedure) inthe receiving object that generates the desired result. Message passing

involves specifying the name of the object,the name of the function (message) and the

information to be sent. E.g.: employee.salary(name); Object: employee Message: salary Information: name

2. What do you understand by static member and static function? How to declare them? Illustrate with an example program. (8) (Apr/May 2015) Explain with an example the use of static members. (6) [CO1 – L1 - Nov/Dec 2014]

Static Data & static member Functions:

A static data member is shared by all objects of the class in a program. All static data is initialized to zero when the first object is created, if no other initialization is present. It can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to. Static member function

A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

Page 16: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 16 PDS-II

A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

class Date { int d, m ,y; static Date default_date; public:

Date(intdd=0;int mm=0;int yy=0); //… static void set_default(int , int, int); }; int main() { Date::set_default(10,20,30); // ok Program to find the count object:

#include<iostream.h>

#include<conio.h> class stat

{ int code; static int count;

public: stat()

{ code=++count;

} void showcode() { cout<<"\n\tObject number is :"<<code;

} static void showcount() {

cout<<"\n\tCount Objects :"<<count; }

};

int stat::count;

void main() {

clrscr(

Page 17: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 17 PDS-II

);

stat obj1,obj2;

obj1.showcount(); obj1.showcode();

obj2.showcount(); obj2.showcode();

getch(); }

Output: Count Objects: 2 Object Number is: 1

Count Objects: 2 Object Number is: 2

3. List the different types of constructors. Write a program to Illustrate the different types of constructors. (10) [CO1 – L1 - Nov/Dec 2014]

Constructor It is a member function having same name as it‟s class and which is used to initialize the objects

of that class type with a legal initial value. Constructor is automatically called when object is created. A constructor is a kind of member function that initializes an instance of its class. A

constructor has the same name as the class and no return value. A constructor can have any number of parameters and a class may have any number

of overloaded constructors. Constructors may have any accessibility, public, protected or private. If you don't define any constructors, the compiler will generate a default constructor

that takes no parameters; you can override this behavior by declaring a default

constructor as deleted. Types of Constructor Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor.It does not take any argument.

Syntax: Class name()

{ constructor Definition }

Page 18: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 18 PDS-II

Example: circle :: circle() {

radius = 0; }

Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor. circle :: circle(double r)

{ radius = r;

} Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object. circle :: circle(circle &t) {

radius = t.radius; }

There can be multiple constructors of the same class, provided they have different signatures.

Destructor A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object‟s scope is over. ~circle() { } Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using multiple constructor in class so this example also illustrates the concept of constructor overloading #include<iostream> #include<conio.h> class circle //specify a class { private : double radius; //class data members public: circle() //default constructor

{ radius = 0;

}

circle(double r) //parameterized constructor {

radius = r;

Page 19: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 19 PDS-II

}

circle(circle &t) //copy constructor {

radius = t.radius; }

void setRadius(double r) //function to set data {

radius = r; }

double getArea() return 3.14*radius*radius;

~circle() //destructor circle c1; //defalut

constructor invoked circle c2(2.5);

//parmeterized constructor invoked circle

c3(c2); //copy constructor invoked 4. Explain the ways in which member functions of a class can be defined and called using a suitable example.(10) [CO1 – L1 - Nov/Dec 2014]

Classes and object: The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format:

class class_name members1; protected:

members2;

members3;

Where class_name is a valid identifier for the class.

The body of the declaration can contain members, that can be either data or function

declaraions, The members of a class are classified into three categories:

1. Private

2. Public 3. protected.

Private, protected, and public are reserved words and are called member access specifiers. These specifiers modify the access rights that the members following them acquire. Private members of a class are accessible only from within other members of the same class. You cannot access it outside of the class. protected members are accessible from members of their same class and also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its

Page 20: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 20 PDS-II

members. Therefore, any member that is declared before one other class specifier automatically has private access.

Here is a complete example :

class circle { privat e :

double radius; public:

void setRadius(double r) {

radius = r; } double getArea() {

return 3.14*radius*radius;

} };

Object Declaration Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type circle: circle c1, c2;

Accessing Class Members Once an object of a class is declared, it can access the public members of the class.

c1.setRadius(2.5);

Defining Member function of class Definingfunctions inside the class as shown in above example. Member functions defined inside a class this way are created as inline functions by default. It is also possible to declare a function within a class but define it elsewhere. Functions defined outside the class are not normally inline. When we define a function outside the class we cannot reference them (directly) outside of the class. In order to reference these, we use the scope resolution operator, :: (double colon). In this example, we are defining function setRadius outside the class:

void circle :: setRadius(double r) {

radius = r; }

The following program demostrates the general feature of classes.

Member functionssetRadius() and getArea() defined outside the class. #include <iostream> #include<conio.h>

Page 21: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 21 PDS-II

class circle //specify a class { private : double radius; //class data members public:

void setRadius(double r); double getArea(); //member function to get data from user

};

void circle :: setRadius(double r) {

radius = r; }

double circle :: getArea() {

return 3.14*radius*radius; }

int main() {

circle c1; //define object of class circle c1.setRadius(2.5); //call member function to initialize

cout<<c1.getArea(); return 0; }

OUTPUT:

19.625

5. Difference between Struct and Class in also illustrate with Example.(8) [CO1 – L1]

Struct and Class

• A struct is a class where members are public by default: struct X {

int m;

// …

}; • Means class X { public: int m; // …

}; structs are primarily used for data structures where the members can take any value.

6. Explain about Storage Classes in C++ with Examples(16).

Storage Classes

Page 22: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 22 PDS-II

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program

auto

register

static

extern mutable

The auto Storage Class The auto storage class is the default storage class for all local variables.

{ int mount; autoint month; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.

The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). {registerint miles; } The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. Program #include<iostream> // Function declaration voidfunc(void); staticint count =10;/* Global variable */

main() { while(count--) { func(); }

Page 23: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 23 PDS-II

return0; } // Function definition voidfunc(void) { staticint i =5;// local static variable i++; cout<<"i is "<< i ; cout<<" and count is "<< count <<std::endl; } OUTPUT

i is6and count is9

i is7and count is8

i is8and count is7

i is9and count is6

i is10and count

is5 i is11and

count is4 i

is12and count is3

i is13and count

is2 i is14and

count is1 i

is15and count is0

The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

First File: main.cpp #include<iostream> int count ; externvoidwrite_extern(); main() {

count =5; write_extern(); }

Page 24: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 24 PDS-II

Second File: support.cpp #include<iostream> externint count; voidwrite_extern(void) {

std::cout<<"Count is "<< count <<std::endl; }

Here, extern keyword is being used to declare count in another file. Now compile these two files as follows: $g++ main.cpp support.cpp -o write

This will produce write executable program, try to execute write and check the result as follows: $./write

The mutable Storage Class The mutable specifier applies only to class objects, It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.

6. State the merits and demerits of object oriented methodology. [CO1 – L2]

Merits:

• Can create new programs faster because we can reuse code

• Easier to create new data types

• Easier memory management

• Programs should be less bug-prone, as it uses a stricter syntax and type checking.

• `Data hiding', the usage of data by one program part while other program parts cannot

access the data Will whiten your teeth Demerits:

Disadvantages of C++ over Java:

• Java protects you from making mistakes that C/C++ don‟t, as you‟ve

• C++ has many concepts and possibilities so it has a steep learning curve

• extensive use of operator overloading, function overloading and virtual

• functions can very quickly make C++ programs very complicated

• shortcuts offered in C++ can often make it completely unreadable, just like in C 7. Explain the following (8) [CO1 – L1]

i) Pointer object.

Pointers: A pointer is a variable that holds a memory address, usually the location of another variable in memory. Defining a Pointer Variable int

*iptr; iptr can hold the address of an int

Pointer Variables Assignment: Int num = 25; int *iptr; iptr = &num;

Page 25: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 25 PDS-II

Memory layout To access num using iptr and indirection operator *

cout<<iptr; // prints 0x4a00 cout<< *itptr; // prints 25

Similary, following declaration shows: char *cptr; float *fptr; cptr is a pointer to character and fptr is a pointer to float value. Pointer Arithmetic Some arithmetic operators can be used with pointers: - Increment and decrement operators ++, -- - Integers can be added to or subtracted from pointers using the operators +, -, +=, and =

- Each time a pointer is incremented by 1, it points to the memory location of the next element of

its base type.

1. If “p” is a character pointer then “p++” will increment “p” by 1 byte.

2. If “p” were an integer pointer its value on “p++” would be incremented by 2 bytes.

Pointers and Arrays Array name is base address of array intvals[]

= {4, 7, 11}; cout<<vals; // displays 0x4a00

cout<<vals[0]; // displays 4

Example: intarr[]={4,7,1 1}; int *ptr = arr; What is ptr + 1? It means (address in ptr) + (1 * size of an int) cout<< *(ptr+1); // displays 7 cout<< *(ptr+2); // displays 11

Array Access Array notation arr[i] is equivalent to the pointer notation *(arr + i) Assume the variable definitions intarr[]={4,7,11}; int *ptr = arr; Examples of use of ++ and -- ptr++;

// points at 7 ptr--; // now points at 4

Character Pointers and Strings Initialize to a character string. char* a = “Hello”; a is pointer to the memory location where „H‟ is stored. Here “a” can be viewed as a character array of size 6, the only difference being that a can be reassigned another memory location. char* a = “Hello”; a gives address of „H‟ *a gives

„H‟ a[0]

Page 26: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 26 PDS-II

gives „H‟ a++ gives address of „e‟ *a++ gives „e‟ Pointers as Function Parameters: A pointer can be a parameter. It works like a reference parameter to allow change to argument from within function Pointers as Function Parameters void swap(int *x, int *y)

{ int temp;

temp = *x; *x =

*y; *y = temp; }

swap(&num1, &num2);

Pointers to Constants and Constant Pointers: Pointer to a constant: cannot change the value that is pointed at Constant pointer: address in pointer cannot change once pointer is initialized

Pointers to Structures:We can create pointers to structure variables

struct Student {introllno; float fees;}; Student stu1; Student *stuPtr = &stu1; (*stuPtr).rollno= 104;

-or- Use the form ptr->member: stuPtr->rollno = 104;

Program to find the address stored in pointer variable: #include<iostream>

#include<conio.h>

int main () { intvar=20;// actual variable declaration. int*ip;// pointer variable ip=&var;// store address of var in pointer variable cout<<"Value of var variable:"; cout<<var<<endl; // print the address stored in ip pointer variable cout<<"Address stored in ip variable: "; cout<<ip<<endl; // access the value at the address available in pointer cout<<"Value of *ip variable: "; cout<<*ip<<endl;

return0; }

OUTPUT: Value of var variable:20 Address stored inip variable:0xbfc601ac Value of *ip variable:20

Page 27: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 27 PDS-II

ii) this pointer.

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

A static member function does not have a this pointer.

Program to find the contructor: #include<iostream> #include<conio.h> classBox { public: // Constructor definition Box(double l=2.0,double b=2.0,double h=2.0) { cout<<"Constructor

called."<<endl; length = l; breadth = b; height = h; } doubleVolume() { return length * breadth * height; } int compare(Box box) { returnthis->Volume()>box.Volume(); } private: double length;// Length of a box double breadth;// Breadth of a box double height;// Height of a box }; int main(void) { BoxBox1(3.3,1.2,1.5);// Declare box1 BoxBox2(8.5,6.0,2.0);// Declare box2 if(Box1.compare(Box2)) {

cout<<"Box2 is smaller than Box1"<<endl; } else {

Page 28: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 28 PDS-II

cout<<"Box2 is equal to or larger than Box1"<<endl; } return0; }

OUTPUT: Constructor called.

Constructor called. Box2is equal to or larger than

Box1

8. Explain about call by value ,call by pointer and call by reference with

C++ Programs(16) [CO1 – L2] Call By Value: In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function‟s copy of values and are not reflected back to the calling function. Syntax: // function definition to swap the values. void swap(int x,int y)

{

int temp;

temp = x;/* save the value of x */

x = y;/* put y into x */ y = temp;/* put x into y */ return;

} Program to find swapping of the number by call by value: #include<iostream> #include<conio.h>

// function declaration void swap(int x,int y);

int main ()

{ // local variable declaration: int a =100; int b =200; cout<<"Before swap, value of a :"<< a <<endl; cout<<"Before swap, value of b :"<< b <<endl; // calling a function to swap the values. swap(a, b); cout<<"After swap, value of a :"<< a <<endl; cout<<"After swap, value of b :"<< b <<endl; return0; }

Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200

Page 29: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 29 PDS-II

Call by pointer

The call by pointer method of passing arguments to a function copies the address of an

argument into the formal parameter. Inside the function, the address is used to access the actual

argument used in the call. This means that changes made to the parameter affect the passed

argument. syntax:

// function definition to swap the values. void swap(int*x,int*y) { int temp;

temp =*x;/* save the value at address x */ *x =*y;/* put y into x */ *y = temp;/* put x into y */ return; }

Program to find swapping of the number by call by pointer: #include<iostream> #include<conio.h> // function declaration

void swap(int*x,int*y);

int main () { // local variable declaration: int a =100; int b =200; cout<<"Before swap, value of a :"<< a <<endl; cout<<"Before swap, value of b :"<< b <<endl; /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie.

address of variable b.*/ swap(&a,&b); cout<<"After swap, value of a :"<< a <<endl; cout<<"After swap, value of b :"<< b <<endl; return0; }

Output:

Before swap, value of a :100

Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100

Page 30: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 30 PDS-II

Call by Reference: The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.

Syntax: // function definition to swap the values. void swap(int&x,int&y) {

int temp; temp = x;/* save the value at address x */ x = y;/* put y into x */ y = temp;/* put x into y */ return; } Program to find swapping of the number by call by Reference: #include<iostream> #include<conio.h> // function declaration void swap(int&x,int&y); int main () { // local variable declaration: int a =100; int b =200; cout<<"Before swap, value of a :"<< a <<endl; cout<<"Before swap, value of b :"<< b <<endl; /* calling a function to swap the values using variable reference.*/ swap(a, b); cout<<"After swap, value of a :"<< a <<endl; cout<<"After swap, value of b :"<< b <<endl;

return0; }

Output: Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

Page 31: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 31 PDS-II

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. What is a constructor? [CO2 – L1] A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values f data members of the class. 2. How will you declare and define a constructor. [CO2 – L1]

Constructor declaration: Class integer { int m,n; public:

integer ( void )

}

constructor definition: integer :: integer (void )

{

m=0;

n=0;

}

3. What are the characteristics of a constructor? [CO2 – L1] a .They should be declared in the public section.

b .They are invoked automatically when the objects are created. C. They do not have return types, not even void and therefore, they cannot return values. d. They cannot be inherited, though a derived class can call the base class constructor. e.

Constructors cannot be virtual.

4. What are the types of a constructor? [CO2 – L1]

i. Default constructor ii. Parameterized constructor. iii. Copy constructor

5. What is a parameterized constructor? [CO2 – L1]

The constructors that can take arguments are called parameterized

constructors. Integer ( int x, int y )

{

m=x;

n=y;

}

Page 32: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 32 PDS-II

6. What is a default constructor? [CO2 – L1] A constructor that accepts no parameter is called default constructor.

Default ( )

{

} 7. What is a destructor? [CO2 – L1] A destructor as the name implies is used to destroy the objects that have been created by a constructor. Like a constructor the destructor is a member function whose name is the same as the class name but is preceded by a tilde symbol. ~ integer ( )

{

} 8. What are Dynamic Constructors? [CO2 – L1] The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is known as dynamic constructors. The memory is allocated with the help of the new operator. 9. What is function overloading? Give an example. [CO2 – L1] Function overloading means we can use the same function name to create functions that perform a variety of different tasks. Eg: An overloaded add ( ) function handles different data types as shown below. // Declarations

i. int add( int a, int b); //add function with 2 arguments of same type ii. int add( int a, int b, int c); //add function with 3 arguments of same type iii. double add( int p, double q); //add function with 2 arguments of different type

10. What is operator overloading? [CO2 – L1] C++ has the ability to provide the operators with a special meaning for a data type. This mechanism of giving such special meanings to an operator is known as Operator overloading. It provides a flexible option for the creation of new definitions for C++ operators. 11. List out the operators that cannot be overloaded. [CO2 – L1] Class member access operator (. , .*)

Scope resolution operator (::)

Size operator ( sizeof )

Conditional operator (?:)

12. What is the purpose of using operator function? Write its syntax. [CO2 – L1]

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 by Operator function , which describes the task.

Operator functions are either member functions or friend functions. The general form is

Page 33: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 33 PDS-II

return type classname :: operator (op-arglist )

{

function body } where return type is the type of value returned by specified operation. Op-operator being overloaded. The op is preceded by a keyword operator. operator op is the function name.

13. Write at least four rules for Operator overloading. [CO2 – L1] Only the existing operators can be overloaded. The overloaded operator must have at least one operand that is of user defined data type. The basic meaning of the operator should not be changed. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden. 14. How will you overload Unary & Binary operator using member functions? [CO2 – L1] When unary operators are overloaded using member functions it takes no explicit arguments and return no explicit values. When binary operators are overloaded using member functions, it takes one explicit argument. Also the left hand side operand must be an object of the relevant class.

15. How will you overload Unary and Binary operator using Friend functions? [CO2 – L1] When unary operators are overloaded using friend function, it takes one reference argument (object of the relevant class) When binary operators are overloaded using friend function, it takes two explicit arguments. 16. How an overloaded operator can be invoked using Friend functions? [CO2 – L1] In case of unary operators, overloaded operator can be invoked as

Operator op (x); In case of binary operators, overloaded operator can be invoked as Operator op (x , y)

17. List out the operators that cannot be overloaded using Friend function. [CO2 – L1] Assignment operator = Function

call operator ( ) Subscripting

operator [ ]

Class member access operator 18. Explain basic to class type conversion with an example. [CO2 – L1] Conversion from basic data type to class type can be done in destination class. Using constructors does it. Constructor takes a single argument whose type is to be converted. Eg: Converting int type to class type class time {

int hrs,mins; public: ………….

Time ( int t) //constructor

{

hours= t/60 ; //t in minutes

Page 34: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 34 PDS-II

mins =t % 60;

}

}; Constructor will be called automatically while creating objects so that this conversion is done automatically. 20. Explain class to basic type conversion with an example. [CO2 – L2] Using Type Casting operator, conversion from class to basic type conversion can be done. It is done in the source class itself. Eg: vector : : operator double( )

{ double sum=0;

for(int I=0;I<size;I++) sum=sum+v[ i ] *u[ i ] ; return sqrt ( sum ) ; } This function converts a vector to the corresponding scalar magnitude. 21. Define inheritance? [CO2 – L1] Inheritance is the process of creating new classes from the existing classes. The new classes are called derived classes. The existing classes are called base classes. The derived classes inherit all the properties of the base class plus its own properties. The properties of inheritance do not affect the base classes.

22. What are the types of inheritance? [CO2 – L1]

Single Inheritance

Multiple Inheritance

Hierarchial Inheritance

Multilevel Inheritance

Hybrid Inheritance

Multipath Inheritance

23. What are the advantages of using a derived class? [CO2 – L1] New classes can be derived by the user from the existing classes without any modification.

It saves time and money.

It reduces program coding time.

It increases the reliability of the program. 24. Define multiple inheritance. [CO2 – L1] If a derived class is derived from more than one base class, then it is called multiple inheritance.

Hierarchial inheritance If two or more derived classes are derived from the same base class then it is known as hierarchial inheritance

multilevel inheritance If a derived class is derived from another derived class then it is known as multilevel inheritance.

Page 35: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 35 PDS-II

25. Define abstract class. [CO2 – L1] A class is said to be an abstract class if it satisfies the following conditions:

It should act as a base class It should not be used to create any objects

26. What is a virtual function? [CO2 – L1] A member function whose definition can be changed during run time is called virtual function. The class which contains virtual function is called polymorphic class and it should be a base class. Different versions for the virtual function should be present in different derived classes with

same name as virtual function name

27. Define pure virtual function. [CO2 – L1] Pure virtual function is a virtual function with no body. The general form is Virtual void member-function-name( ) = 0

28. What are the properties of pure virtual function? [CO2 – L1]

It has no definition in the base class.

We cannot create object for the class containing pure virtual function.

Pure virtual function can be called through derived class objects.

It acts as an empty bucket which has to be filled by its derived classes.

29. What are the rules for virtual functions? [CO2 – L1]

Virtual functions must be members of some class.

They cannot be static members.

They are accessed by using object pointers. A virtual function can be a friend of another class.

We can have virtual destructors, but we cannot have virtual constructors.

30. Define Polymorphism. [CO2 – L1] It is the property of the same object to behave differently in different contexts given the same message. A single function name can be used for various purposes and single operator is used to achieve multiple operations and the usage of either the function at the operator depends on the context in such cases. 31. Define Compile time polymorphism. [CO2 – L1]

The compiler while compiling the program resolves the function call or the operator call. This is

known as compile time polymorphism 32. Define Runtime polymorphism. [CO2 – L1] During multiple inheritances if the appropriate member function could be selected while the program is running is known as Runtime polymorphism

33. What is a virtual base class? [CO2 – L1] When a class is declared as virtual c++ takes care to see that only copy of that class is inherited,

regardless of how many inheritance paths exist between the virtual base class and a derived

class.

Page 36: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 36 PDS-II

34. What is the difference between base class and derived class? [CO2 – L1]

The biggest difference between the base class and the derived class is that the derived class

contains the data members of both the base and its own data members. The other difference is

based on the visibility modes of the data members. 35. What are the rules governing the declaration of a class of multiple inheritance? [CO2 – L1]

• More than one class name should be specified after the : symbol.

• Visibility modes must be taken care of.

If several inheritance paths are employed for a single derived class the base class must be

appropriately declared

Page 37: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 37 PDS-II

PART-B

1. State the rules to be followed while overloading an operator. Write a program to

illustrate overloading. [CO2 – L1]

OPERATOR OVERLOADING: Operator overloading means giving additional meaning to

existing operators

• By operator overloading an existing operator can be made to perform different operations than

the stipulated one.

• It doesn‟t change the meaning and precedence of the original operator.

• Almost all the operators in c++ can be overloaded except the following o Sizeof ()

• Conditional operator (?:) o Scope resolution operator (::) o Class member access operator (.,.*)

SYNTAX: Return-type operator op-symbol(argument list)

{ body of the function;

}

Generally there are three general classifications of operator namely

Operator

Unary binary ternary Among the above unary and binary operators can be overloaded and ternary operator

cannot be overloaded.

OVERLOADING UNARY OPERATOR: Unary operators like unary + , Unary - ….. can be overloaded as follows EXAMPLE: #include<iostream.h>

class unary

{

int a;

public:

void get()

{

a=10;

}

void show()

{ cout <<"\n The value of the object is\n";

}

void operator - ()

{

a=-a;

Page 38: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 38 PDS-II

}

};

void main()

{ clrscr();

unary u;

u.get();

u.show();

-u; //unary operator - called u.show(); getch();

}

OUTPUT:

The value of the object is 10

The value of the object is -10 • In the above program, the unary operator minus is overloaded. • In this an object „u‟ is created and given the value 10 • When the unary operator – is called the operator function is invoked and the value of the

member data of the object „u‟ is negated.

• The negated value is then displayed.

2. Explain multiple inheritances with suitable c++ coding Explain hybrid inheritance with

suitable C++ coding. [CO2 – L2] INHERITANCE:

• Inheritance is a mechanism of deriving a new class from a old class.

• It provides the concept of reusability

• By inheritance some or all the properties of a class can be derived in to another class.

• The class which provides the properties is called as base class and the class which derives the

properties is called as derived class. Multiple inheritance:

It is a type of inheritance in which a class can inherit properties from more than one class.

Syntax:

Class derivedclass name : visibility mode baseclass1,visibilitmode baseclass2 {

body of the derived class;

}; visibility mode can be either private or

public.

Example :

#include #include class bc1 {

protected: int a; public : void get()

{ cout <<”\n enter the value for

Page 39: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 39 PDS-II

a\n”; cin >>a;

} }; class

bc2

{ protected: int b; public; void

get1() { cout <<” \n enter the

value for b \n”; cin>>b;

} }; class dc : public bc1, public

bc2

{ public : void

show() {

cout <<”The values of a and b are” ; cout

<<<”\n”<

} }; void main()

{ clrscr();

dc d;

d.get(); d.get1(); d.show(); } 3. Define polymorphism. Explain the different types of polymorphism. [CO2 – L1]

Polymorphism is the ability to use an operator or function in different ways.

Polymorphism gives different meanings or functions to the operators or functions.

Poly, referring too many, signifies the many uses of these operators and functions.

A single function usage or an operator functioning in many ways can be called polymorphism.

Polymorphism refers to codes, operations or objects that behave differently in different contexts.

"Overriding is the example of run-time polymorphism" "Overloading is the example of compile-time polymorphism."

Programfor polymorphism to find the area of the rectangle: #include<iostream> usingnamespacestd; classShape {

protected:

int width, height;

public:

Shape(int a=0,int b=0) {

Page 40: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 40 PDS-II

width= a; height= b; }

int area() {

cout<<"Parent class area :"<<endl; return0; } };

classRectangle:publicShape{

public: Rectangle(int a=0,int b=0):Shape(a, b){} int area () { cout<<"Rectangle class area :"<<endl; return(width * height); } };

classTriangle:publicShape{ public: Triangle(int a=0,int b=0):Shape(a,b){} int area () {

cout<<"Triangle class area :"<<endl; return(width * height /2); } }; // Main function for the program Int main() {

Shape*shape;

Rectanglerec(10,7); Triangle tri(10,5);

// store the address of Rectangle shape=&rec; // call rectangle area. shape->area();

// store the address of Triangle shape=&tri; // call triangle area. shape->area(); return0; }

OUTPUT Parentclass area Parentclass area

Types of Polymorphism: C++ provides two different types of polymorphism.

run-time

compile-time

The appropriate member function could be selected while the programming is running. This is

Page 41: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 41 PDS-II

known as run-time polymorphism. The run-time polymorphism is implemented with inheritance and virtual functions.

Virtual functions A function qualified by the virtual keyword. When a virtual function is called via a pointer, the

class of the object pointed to determines which function definition will be used.

Virtual functions implement polymorphism, whereby objects belonging to different classes can

respond to the same message in different ways.

A virtual function is a function in a base class that is declared using the keyword virtual.

Defining in a base class a virtual function, with another version in a derived class,signals to the

compiler that we don't want static linkage for this function.

What we do want is 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. This sort of operation is referred to as

dynamic linkage, or late binding.

Program for Virtual Fuction to print base class #include<iostream.h> #include<conio.h> class base { public:

virtual void show() {

cout<<"\n Base class show:"; } void display() {

cout<<"\n Base class display:" ; }

};

classdrive:public base { public: void display() {

cout<<"\n Drive class display:"; } void show() {

cout<<"\n Drive class show:"; }

}; void main() {

clrscr(); base obj1; base *p; cout<<"\n\t P points to base:\n" ; p=&obj1;

Page 42: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 42 PDS-II

p->display(); p->show(); cout<<"\n\n\t P points to drive:\n"; drive obj2; p=&obj2; p->display(); p->show(); getch(); } Output:

P points to Base Base class display Base class show P points to Drive Base class Display Drive class Show

Compile-time: The compiler is able to select the appropriate function for a particular call at compile-time itself. This is known as compile-time polymorphism. The compile-time polymorphism is implemented with templates.

Function name overloading Operator overloading

4. Explain the various forms of inheritance in C++ with necessary coding. [CO2 – L2]

Inheritance:

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is inheritance.

Inheritance lets you create new classes from existing class. Any new class that you create

from an existing class is called derived class; existing class is called base class. The inheritance relationship enables a derived class to inherit features from its base

class. Furthermore, the derived class can add new features of its own. Therefore, rather than create completely new classes from scratch, you can take advantage of inheritance and reduce software complexity.

Forms of Inheritance Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class. Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es) Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base class. Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

Syntax: class derived-class: access baseA, access baseB....

Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of inheritance. In order to derive a class from another, we use a colon (:) in the declaration of the derived class using the following format : classderived_class: memberAccessSpecifierbase_class { ... };

Page 43: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 43 PDS-II

Where derived_class is the name of the derived class and base_class is the name of the class on which it is based. The member Access Specifier may be public, protected or private.

This access specifier describes the access level for the members that are inherited from the base

class.

Member How Members of the Base Class Appear in the Derived

Access Class

Specifier

Private Private members of the base class are inaccessible to the

derived class.

Protected members of the base class become private

members of the derived class.

Public members of the base class become private members of

the derived class.

Protected Private members of the base class are inaccessible to the

derived class.

Protected members of the base class become protected

members of the derived class.

Public members of the base class become protected members

of the derived class.

Public Private members of the base class are inaccessible to the

derived class.

Protected members of the base class become protected

members of the derived class.

Public members of the base class become public members of

the derived class.

Program for Single Inheritance to print HRA,DA and Net Pay #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

{

floatbp,hra,da,pf,np; public: void get1() { cout<<"Enter the basic pay:"; cin>>bp; cout<<"Enter the Humen Resource Allowance:"; cin>>hra;

Page 44: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 44 PDS-II

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()

{ inti,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();

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();

} Output: Enter the Number of employee:1 Enter the employee No: 150

Enter the employee Name: ram Enter the designation: Manager

Enter the basic pay: 5000

Enter the HR allowance: 1000

Enter the Dearness allowance: 500

Enter the profitability Fund: 300

E.No E.name desBP HRA DA PF NP

150 ramManager 5000 1000 500 300 6200

Page 45: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 45 PDS-II

Program for Multiple Inheritance to print student details: #include<iostream.h> #include<conio.h> class student { protected: int rno,m1,m2; public: void get()

{ cout<<"Enter the Roll no :"; cin>>rno; cout<<"Enter the two marks :"; cin>>m1>>m2; }}; class sports{ protected:

int sm; // sm = Sports mark public:

voidgetsm() {

cout<<"\nEnter the sports mark :";

cin>>sm;

}

};

Class statement:public student,public sports

{Int tot,avg;

public:

void display() {

tot=(m1+m2+sm); avg=tot/3; cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal: "<<tot;

cout<<"\n\tAverage : "<<avg; }

}; void main()

{ clrscr(); statement obj; obj.get(); obj.getsm();

obj.display(); getch();

} Output:

Enter the Roll no: 100 Enter two marks 90 80 Enter the Sports Mark: 90 Roll No: 100 Total : 260 Average: 86.66

Page 46: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 46 PDS-II

UNIT III C++ PROGRAMMING ADVANCED FEATURES Abstract class – Exception handling - Standard libraries - Generic Programming - templates – class template - function template – STL – containers– iterators – function adaptors – allocators - Parameterizing the class - File handling concepts.

PART-A

1. What is an exception? [CO3 – L1] Exception refers to unexpected condition in a program. The unusual conditions could be faults, causing an error which in turn causes the program to fail. The error handling mechanism of C++ is generally referred to as exception handling.

2. What are the types of exception? [CO3 – L1] They are classified into synchronous and asynchronous exceptions.

Synchronous exception: The exception which occur during program execution , due to some fault in the input data or technique that is not suitable to handle the current class of data, within the pgogram are known as synchronous exception.

For instance errors such as out-of-range, overflow, underflow and so on.

Asynchronous exception : The exceptions caused by events or faults unrelated to the program and beyond the control of the program are called asynchronous exception. For instance, errors such as keyboard interrupts, hardware malfunctions, disk failure, and so on. 3. What are the blocks related to exception handling constructs? [CO3 – L1] The blocks related to exception handling constructs are Try Throw Catch The keyword try is used to preface a block of statements. Which may generate exceptions. This block of statements is known as try block. When an exception is detected, it is thrown using throw statement in the try block. A catch block catches the exception thrown by the throw statement in the try block and handles it appropriately. Syntax:

try {

………

………

throw exception;

}

catch (type arg)

{ }

Page 47: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 47 PDS-II

4. What are the functions supported by C++ to handle uncaught exceptions? [CO3 – L1] The functions supported by C++ to handle uncaught exceptions are

terminate ( ) set_terminate(

) unexpected ( )

set_unexpected ( )

5. What is a template? [CO3 – L1] Templates support generic programming , which allows to develop reusable software components such as functions, classes etc., supporting different data types in a single framework

6. What is function template? [CO3 – L1] The templates declared for functions are called function templates. They perform appropriate operations depending on the data type of the parameters passed to them.

7. What is a class template? [CO3 – L1] The templates declared for classes are called function templates. They perform appropriate operations depending on the data type of the parameters passed to them. 8. What is a stream? [CO3 – L1] Stream is a series of bytes, which act either as a source from which input data can be extracted or as a destination to which the output can be sent. The source stream provides data to the program called te input stream and the destination stream that receives data from the program is called the output stream. 9. What are the types of standard streams? [CO3 – L1]

cin - Standard input corresponding to stdin in C

cout – Standard output corresponding to stdout in C

clog – A fully buffered version of cerr.

10. How do you classify ios class? [CO3 – L1] Istream – input stream does formatted input. Ostream – output stream does formatted output. Iostream – input / output stream does formatted input and output. 11. What are manipulators? [CO3 – L1] Manipulators are special functions that are specifically designed to modify the working of a stream. They can be embedded in the I/O statements to modify the form parameters of a stream.

Page 48: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 48 PDS-II

12. Give few ios class functions and flags? [CO3 – L1]

Function Task performed

Specifies the required number of

Width( ) fields to be used while displaying the

output value.

Specifies the number of digits to be

Precision ( ) displayed after the decimal point.

Fill ( ) Specifies a character to be used to fill

the unused area of a field. By default,

fills blank space character.

Sets format flag that control the form

Setf ( ) of output display.

Unsetf ( ) Clears the specified format flag.

13. What is a file? [CO3 – L1] A file is a collection of related information defined by its creator. Commonly files represent programs ( boyh source and object forms ) and data. Files may be free-form, such as text files or may be rigidly formatted . In general, a file is a

sequence of bits, bytes, lines, or records whose meaning is defined by its creator and user.

14. How many classes are used for handling files? [CO3 – L1] ifstream – for handling input files. ofstream – for handling output files.

fstream – for handling files on which both input and output can be performed.

15. What are the steps involved in manipulating a file? [CO3 – L1] Name the file on the disk Open the file to get the file pointer. Process the file. (Read / Write ) Check for errors while processing. Close the file after its complete usage.

16. What functions are used for manipulation of file pointers? [CO3 – L1]

seekg ( ) – Moves get file pointer to a specific location.

seekp ( ) - Moves put file pointer to a specific location.

tellg ( ) – Returns the current position of the get pointer

tellp ( ) - Returns the current position of the put pointer

17. What do you mean by sequential access? [CO3 – L1] A sequential file has to be accessed sequentially to access the particular data in the file all the preceding data items have to be read and discarded. For example a file on a tape must be accessed sequentially.

Page 49: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 49 PDS-II

18. What do you mean by random access ? [CO3 – L1] A random file allows access to the specific data without the need for accessing its preceding data items. However, it can be accessed sequentially . For example, a file on a hard disk or floppy disk can be accessed either sequentially or randomly. 19. Give the general format of class template. [CO3 – L1]

The general format of a class template is:

template class classname {

//………

//class member specification

//with anonymous type T

//wherever appropriate

//……… }; 20. Can we overlaod template function if so explain how. [CO3 – L1] Yes, a template function can be overloaded either by template functions or ordinary functions of

its name. in such cases, the overloading resolution is accomplished as follows:

1) Call an ordinary function that has an exact match.

2) Call a template function that could be created with an exact match.

3) Try normal overloading resolution to ordinary functions and call the one that matches. 21. List the kinds of exception. [CO3 – L1] Exceptions are of two kinds namely

• Synchronous exceptions

• Asynchronous exceptions

22. What are the errors in synchronous type exceptions? [CO3 – L1] Errors such as “out-of-range index” and “over-flow” belong to the synchronous type exceptions. 23. What are the errors in asynchronous type exceptions? [CO3 – L1]

The errors that were caused by errors beyond the control of the program (such as keyboard

interrupts) are called asynchronous exceptions. 24. What are the tasks that are performed by the error handling mechanism? [CO3 – L1] The mechanism suggests a separate error handling code that performs the following tasks:

1) Find the problem (Hit the exception).

2) Inform that an error has occurred (Throw the exception).

3) Receive the error information (Catch the exception).

4) Take corrective actions (Handle the exception). 25. List the ios format function. [CO3 – L1] The ios format functions are as follows:

• width()

• precision()

Page 50: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 50 PDS-II

• fill() • setf()

• unsetf() 26. List the manipulators. [CO3 – L1] The manipulators are:

• setw()

• setprecision()

• setfill()

• setiosflags()

• resetiosflags() 27. Mention the equicalent ios function for manipulators. [CO3 – L1] Manipulator Equivalent ios function setw(int w) width() setprecision(int d) precision() setfill(int c)

fill() setiosflags(long f) setf() resetiosflags(long f) unsetf() endl \n”

28. Define fill functions. [CO3 – L1] The fill( ) function can be used to fill the unused positions of the field by any desired character rather

than by white spaces (by default). It is used in the following form:

cout.fill(ch); where ch represents the character which is used for filling the unused positions. For example, the

statements cout.fill(„*‟); cout.width(10); cout<<5250<<”\n”;

Page 51: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 51 PDS-II

PART-B

1. Explain multiple catch statement with help of suitable C++ coding. [CO3 – L2]

EXCEPTION HANDLING

Exceptions are run time 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. When a program

encounters an exceptional condition, it is important that it is identified and dealt with

effectively. Exceptions are of two kinds, namely, synchronous exceptions and

asynchronous exceptions. Errors such as “out-of-range index” and “over flow” belong to the synchronous exceptions. The

errors that are caused by events beyond the control of the program are called asynchronous

exceptions. The proposed exception handling mechanism is designed to handle only

synchronous exceptions. The mechanism performs following tasks: ? Find the problem (Hit the exception).

? Inform that an error has occurred (Throw the exception).

? Receive the error information (Catch the expression).

? Take corrective actions (Handle the exceptions). The error handling code basically consists of two segments one to detect errors and to throw

exceptions, and other to catch the exceptions and to take appropriate actions. Exception Handling Mechanism: It is built upon three keywords, namely, try, throw and catch. The keyword try is used to preface a block of statements which may generate exceptions. This

block of statements is known as try block. When an exception is detected, it is thrown using a

throw statement in the try block. A catch block is defined by the keyword catch „catches‟ the exception „thrown‟ by the throw

statement in the try block, and handles it appropriately. If the type of object thrown matches the

arg type in the catch statement, then catch block is executed for handling the exception. If they

do not match the program is aborted with the help of the abort() function is invoked by default.

When no exception is detected and thrown, the control goes to the statement immediately after

the catch block.

Most often exceptions are thrown by the functions that are invoked from within the try blocks. The point at which the throw is executed is called the throw point. The general format

of code for this kind of relationship is shown below Multiple catch statements: It is possible that a program segment has more than one condition to throw an exception. In

such cases, we can associate more than one catch statement with a try as shown below:

Page 52: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 52 PDS-II

try

{ // try block

} catch(type1 arg) { //

catch block1 }

catch(type2 arg) { //

catch block2 } …

catch(typeN arg) { // catch blockN }

Catch All Exceptions: In some situations we may not be able to anticipate all possible types of exceptions we can force

a catch statement to catch all exceptions instead of a certain type alone. This is achieved as

follows:

catch (…)

{

// statement of processing all exceptions

}

2. Describe the various file modes and its syntax. [CO3 – L2] FILE To handle large volumes of data, we need to use some devices such as floppy disk or hard

disk to store the data. The data is stored in these devices using the concept of files. A file is a

collection of related data stores in a particular area on the disk. Programs can be designed to

perform the read and write operations on these files. A program involves either or both of the following kinds of data communication: 1. Data transfer between the console unit and the program.

2. Data transfer between the program and a disk file. The I/O system of C++ uses file stream as an interface b/n the programs and the files. The

stream that supplies data to the program is known as input stream. The stream that

receives data from the program is known as output stream. In other words, the input

stream reads data from the file and the output stream writes data to the file. Classes for File Stream Operations: The I/O system of C++ contains a set of classes that define the file handling methods. These include

ifstream, ofstream and fstream. These classes are contained in the header file fstream. This file should be included for performing file operations.

The filename is a string of characters that make up a valid filename for the operating system. It

may contain two parts, a primary name and an optional period with extension.

Page 53: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 53 PDS-II

Examples: Input.txt Student For opening a file, we must create a file stream and then link it to the filename. There are two

ways of opening a file:

? Using the constructor function of the class.

? Using the member function open() of the class. The first method is useful when only one file in the stream is used. The second method is

useful when multiple files are managed using one stream.

File Modes:

The two methods that we discussed can also take two arguments instead of one. The second

argument will specify the file-mode. The general form of the function open() with two

arguments is:

Stream-object.open (“filename”, mode); Parameter Meaning ios::app Append to end of file

ios::ate Go to end of file on opening ios::binary Binary file ios::in Open file for reading only

ios::nocreate Open fails if the file does not exist ios::noreplace Open fails if the file already

exists ios::out Open file for writing only

ios::trunc Delete the contents of the file if it exists File

pointers and their manipulations:

Each file has two associated pointers known as the file pointers. They are input pointer and

output pointer. The input pointer is used for reading the contents of a given file location and the

output pointer is used for writing to a given file location. Read only mode:

Input pointer is automatically set at the beginning so that we can read the file from start.

Write only mode:

Existing contents are deleted and the output pointer is set at the beginning.

Append mode:

The output pointer is set to the end of file. Functions for manipulations of file pointers: seekg() – Moves input pointer to a specified location

seekp() – Moves output pointer to a specified location

tellg() – Gives the current position of the input pointer

tellp() – Gives the current position of the output pointer

Example:

infile.seekg(10); moves file pointer to the byte number 10. The bytes are numbered from

Page 54: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 54 PDS-II

zero hence it points to the 11th byte in the file. ofstream out

out.open(“filename”,ios::app);

int p = out.tellp();

The above program will give the number of bytes in the file, since the file is opened in the

append mode.

3. Discuss the need for exception with try, catch and throw keywords. [CO3 – L2] Exceptions are run time 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. When a program

encounters an exceptional condition, it is important that it is identified and dealt with

effectively. Exceptions are of two kinds, namely, synchronous exceptions and asynchronous

exceptions. Errors such as “out-of-range index” and “over flow” belong to the synchronous exceptions. The errors that are caused by events beyond the control of the program are called asynchronous

exceptions. The proposed exception handling mechanism is designed to handle only synchronous

exceptions. The mechanism performs following tasks: ? Find the problem (Hit the exception).

? Inform that an error has occurred (Throw the exception).

? Receive the error information (Catch the expression).

? Take corrective actions (Handle the exceptions).

The error handling code basically consists of two segments one to detect errors and to throw

exceptions, and other to catch the exceptions and to take appropriate actions. Exception Handling Mechanism: It is built upon three keywords, namely, try, throw and catch. The keyword try is used to preface a block of statements which may generate exceptions.

This block of statements is known as try block. When an exception is detected, it is thrown using a throw statement in the try block. A catch block is defined by the keyword catch „catches‟ the exception „thrown‟ by the throw

statement in the try block, and handles it appropriately. If the type of object thrown matches

the arg type in the catch statement, then catch block is executed for handling the exception. If

they do not match the program is aborted with the help of the abort() function is invoked by

default. When no exception is detected and thrown, the control goes to the statement

immediately after the catch block. Most often exceptions are thrown by the functions that are invoked from within the try blocks. The point at which the throw is executed is called the throw point.

Page 55: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 55 PDS-II

The general format of code for this kind of relationship is shown below:

Example: #include void divide(int a, int b)

{

if(b!=0)

cout << “Result = “ << a/b; else throw(b);

} void main()

{ cout << “Enter two numbers “;

int x,y; cin >> x>> y;

try

{ divide(x,y);

} catch(int i)

{

cout << “Error! Dividing by Zero “;

}

Page 56: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 56 PDS-II

UNIT IV ADVANCED NON-LINEAR DATA STRUCTURES

AVL trees – B-Trees – Red-Black trees – Splay trees - Binomial Heaps – Fibonacci Heaps – Disjoint Sets – Amortized Analysis – accounting method – potential method – aggregate analysis.

PART – A

1. Define ADT (Abstract Data Type)? [CO4 – L1] An ADT is a mathematical model with a collection of operations defined on that model.

2. Define linear data structure? [CO4 – L1] Linear data structures are data structures having a linear relationship between its adjacent

elements. Eg: Linked List.

3. Define Non Linear data structure? [CO4 – L1] Non Linear data structures are data structures don‟t have a linear relationship between its adjacent

elements, but had the hierarchical relationship. Eg: Graph, Tree.

4. What are different types of Linked List? [CO4 – L1] Single linked list Double linked list Circular linked list

5. What are different types of Circular Linked List? [CO4 – L1] Circular Single linked list Circular double linked list 6. List the basic operations carried out in a linked list? [CO4 – L1] a. Creation of list b. Insertion of list c. Deletion of list d. Modification of list e.

Traversal of List

7. Define a stack? [CO4 – L1] Stack is an ordered collection of elements in which insertions and deletions are

restricted to one end. The end from which elements are added and /or removed is referred to

as top of the stack. Stacks are also referred as “piles” and “push-down lists”.

8. Define a queue? [CO4 – L1] Queue is an ordered collection of elements in which insertions and deletions are restricted to

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

end and the end from which deletions are made is referred to as front end. 9. Difference between Arrays and Linked List? [CO4 – L2]

Arrays Linked List Size of any array is fixed. Size of list is variable. It is necessary to specify the number of

elements during declaration It is not necessary to specify the elements during declaration

Insertion and deletions are difficult and costly. Insertions and deletions are done in less time. It

occupies less memory than a linked List. It occupies more memory.

Coding is easy. Careful coding is needed to avoid memory errors.

Page 57: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 57 PDS-II

10. What is single linked list? [CO4 – L1] It is a linear data structure which contains a pointer field that points to the address of its next

node (successor) and the data item.

11. Define HEAD pointer and NULL pointer? [CO4 – L1] HEAD - It contains the address of the first node in that list. NULL - It indicates the end of the

list structure. 12 What is meant by dummy header? [CO4 – L1]

It is ahead node in the linked list before the actual data nodes. 13. Define Circular linked list? [CO4 – L1] It is a list structure in which last node points to the first node there is no null value. 14. Write operations that can be done on stack? [CO4 – L1] PUSH and POP 15. Mention applications of stack? [CO4 – L1] a. Expression Parsing b. Evaluation of Postfix c. Balancing parenthesis d. Tower of Hanoi e.

Reversing a string 16. Define Infix, prefix and postfix notations? [CO4 – L1] Infix operators are placed in between the operands Prefix operators are placed before the

operands Postfix Operators are placed after the operands.

17. What are the conditions that followed in the array implementation of queue? [CO4 – L1] Condition Situation

REAR<FRONT EMPTY QUEUE

FRONT==REAR ONE ENTRY QUEUE

REAR==ARRAY SIZE FULL QUEUE 18. What are the conditions that could be followed in a linked list implementations

of queue? [CO4 – L1] Condition Situation

REAR==HEAD EMPTY QUEUE

REAR==LINK (HEAD) ONE ENTRY QUEUE

NO FREE SPACE TO INSERT FULL QUEUE 19. What are the conditions that could be followed in a linked list implementations

of queue? [CO4 – L1] Condition Situation

(REAR MOD ARRAY SIZE +1)==FRONT EMPTY QUEUE

(REAR MOD ARRAY SIZE +2)==FRONT FULL QUEUE

FRONT==REAR ONE ENTRY QUEUE

20. Define Circular queue? [CO4 – L1] A circular queue allows the queue to wrap around upon reaching the end of the array.

Page 58: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 58 PDS-II

PART – B

1. What if the input to binary search tree comes in a sorted (ascending or descending)

manner? [CO4 – L1]

It will then look like this −

It is observed that BST's worst-case performance is closest to linear search algorithms, that is

Ο(n). In real-time data, we cannot predict data pattern and their frequencies. So, a need arises to

balance out the existing BST.

Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary

search tree. AVL tree checks the height of the left and the right sub-trees and assures that the

difference is not more than 1. This difference is called the Balance Factor.

Here we see that the first tree is balanced and the next two trees are not balanced −

Page 59: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 59 PDS-II

In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the

difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it

is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1.

BalanceFactor = height(left-sutree) − height(right-sutree)

If the difference in the height of left and right sub-trees is more than 1, the tree is balanced

using some rotation techniques.

AVL Rotations

To balance itself, an AVL tree may perform the following four kinds of rotations

Left rotation

Right rotation

Left-Right rotation

Right-Left rotation

The first two rotations are single rotations and the next two rotations are double rotations. To

have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's

understand them one by one.

Left Rotation

If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree,

then we perform a single left rotation −

In our example, node A has become unbalanced as a node is inserted in the right subtree of A's

right subtree. We perform the left rotation by making A the left-subtree of B.

Right Rotation

AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree.

The tree then needs a right rotation.

Page 60: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 60 PDS-II

As depicted, the unbalanced node becomes the right child of its left child by performing a right

rotation.

Left-Right Rotation

Double rotations are slightly complex version of already explained versions of rotations. To

understand them better, we should take note of each action performed while rotation. Let's first

check how to perform Left-Right rotation. A left-right rotation is a combination of left rotation

followed by right rotation.

State Action

A node has been inserted into the right subtree of the left

subtree. This makes C an unbalanced node. These scenarios

cause AVL tree to perform left-right rotation.

We first perform the left rotation on the left subtree of C. This

makes A, the left subtree of B.

Node C is still unbalanced, however now, it is because of the

left-subtree of the left-subtree.

We shall now right-rotate the tree, making B the new root node

of this subtree. C now becomes the right subtree of its own left

subtree.

The tree is now balanced.

Page 61: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 61 PDS-II

Right-Left Rotation

The second type of double rotation is Right-Left Rotation. It is a combination of right rotation

followed by left rotation.

State Action

A node has been inserted into the left subtree of the right

subtree. This makes A, an unbalanced node with balance factor

2.

First, we perform the right rotation along C node,

making C the right subtree of its own left subtree B.

Now, B becomes the right subtree of A.

Node A is still unbalanced because of the right subtree of its

right subtree and requires a left rotation.

A left rotation is performed by making B the new root node of

the subtree. A becomes the left subtree of its right subtree B.

The tree is now balanced.

Page 62: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 62 PDS-II

2. Explain B – Tree in detail. [CO4 – L2]

Unlike a binary-tree, each node of a b-tree may have a variable number of keys and children. The

keys are stored in non-decreasing order. Each key has an associated child that is the root of a

subtree containing all nodes with keys less than or equal to the key but greater than the preceeding

key. A node also has an additional rightmost child that is the root for a subtree containing all keys

greater than any keys in the node.

A b-tree has a minumum number of allowable children for each node known as the minimization

factor. If t is this minimization factor, every node must have at least t - 1 keys. Under certain

circumstances, the root node is allowed to violate this property by having fewer than t - 1 keys.

Every node may have at most 2t - 1 keys or, equivalently, 2t children.

Since each node tends to have a large branching factor (a large number of children), it is typically

neccessary to traverse relatively few nodes before locating the desired key. If access to each node

requires a disk access, then a b-tree will minimize the number of disk accesses required. The

minimzation factor is usually chosen so that the total size of each node corresponds to a multiple of

the block size of the underlying storage device. This choice simplifies and optimizes disk access.

Consequently, a b-tree is an ideal data structure for situations where all data cannot reside in

primary storage and accesses to secondary storage are comparatively expensive (or time

consuming).

Height of B-Trees

For n greater than or equal to one, the height of an n-key b-tree T of height h with a minimum

degree t greater than or equal to 2,

For a proof of the above inequality, refer to Cormen, Leiserson, and Rivest pages 383-384.

The worst case height is O(log n). Since the "branchiness" of a b-tree can be large compared to

many other balanced tree structures, the base of the logarithm tends to be large; therefore, the

number of nodes visited during a search tends to be smaller than required by other tree structures.

Although this does not affect the asymptotic worst case height, b-trees tend to have smaller heights

than other trees with the same asymptotic height.

Operations on B-Trees The algorithms for the search, create, and insert operations are shown below. Note that these

algorithms are single pass; in other words, they do not traverse back up the tree. Since b-trees

strive to minimize disk accesses and the nodes are usually stored on disk, this single-pass approach

will reduce the number of node visits and thus the number of disk accesses. Simpler double-pass

approaches that move back up the tree to fix violations are possible.

Since all nodes are assumed to be stored in secondary storage (disk) rather than primary storage

(memory), all references to a given node be be preceeded by a read operation denoted by Disk

Read. Similarly, once a node is modified and it is no longer needed, it must be written out to

secondary storage with a write operation denoted by Disk-Write. The algorithms below assume

that all nodes referenced in parameters have already had a corresponding Disk-Read operation.

Page 63: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 63 PDS-II

New nodes are created and assigned storage with the Allocate-Node call. The implementation

details of the Disk-Read, Disk-Write, and Allocate-Node functions are operating system and

implementation dependent.

B-Tree-Search(x, k) i <- 1

while i <= n[x] and k > keyi[x]

do i <- i + 1

if i <= n[x] and k = keyi[x]

then return (x, i)

if leaf[x]

then return NIL

else Disk-Read(ci[x])

return B-Tree-Search(ci[x], k)

The search operation on a b-tree is analogous to a search on a binary tree. Instead of choosing\

between a left and a right child as in a binary tree, a b-tree search must make an n-way choice. The

correct child is chosen by performing a linear search of the values in the node. After finding the

value greater than or equal to the desired value, the child pointer to the immediate left of that value

is followed. If all values are less than the desired value, the rightmost child pointer is followed. Of

course, the search can be terminated as soon as the desired node is found. Since the running time

of the search operation depends upon the height of the tree, B-Tree-Search is O(logt n).

B-Tree-Create(T)

x <- Allocate-Node()

leaf[x] <- TRUE

n[x] <- 0

Disk-Write(x)

root[T] <- x

The B-Tree-Create operation creates an empty b-tree by allocating a new root node that has no

keys and is a leaf node. Only the root node is permitted to have these properties; all other nodes

must meet the criteria outlined previously. The B-Tree-Create operation runs in time O(1).

B-Tree-Split-Child(x, i, y)

z <- Allocate-Node()

leaf[z] <- leaf[y]

n[z] <- t - 1

for j <- 1 to t - 1

do keyj[z] <- keyj+t[y]

if not leaf[y]

then for j <- 1 to t

do cj[z] <- cj+t[y]

n[y] <- t - 1

for j <- n[x] + 1 downto i + 1

do cj+1[x] <- cj[x]

Page 64: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 64 PDS-II

ci+1 <- z

for j <- n[x] downto i

do keyj+1[x] <- keyj[x]

keyi[x] <- keyt[y]

n[x] <- n[x] + 1

Disk-Write(y)

Disk-Write(z)

Disk-Write(x)

If is node becomes "too full," it is necessary to perform a split operation. The split operation

moves the median key of node x into its parent y where x is the ith

child of y. A new node, z, is

allocated, and all keys in x right of the median key are moved to z. The keys left of the median

key remain in the original node x. The new node, z, becomes the child immediately to the right of

the median key that was moved to the parent y, and the original node, x, becomes the child

immediately to the left of the median key that was moved into the parent y.

The split operation transforms a full node with 2t - 1 keys into two nodes with t - 1 keys each.

Note that one key is moved into the parent node. The B-Tree-Split-Child algorithm will run in

time O(t) where t is constant.

B-Tree-Insert(T, k)

r <- root[T]

if n[r] = 2t - 1

then s <- Allocate-Node()

root[T] <- s

leaf[s] <- FALSE

n[s] <- 0

c1 <- r

B-Tree-Split-Child(s, 1, r)

B-Tree-Insert-Nonfull(s, k)

else B-Tree-Insert-Nonfull(r, k)

B-Tree-Insert-Nonfull(x, k)

i <- n[x]

if leaf[x]

then while i >= 1 and k < keyi[x]

do keyi+1[x] <- keyi[x]

i <- i - 1

keyi+1[x] <- k

n[x] <- n[x] + 1

Disk-Write(x)

else while i >= and k < keyi[x]

do i <- i - 1

i <- i + 1

Page 65: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 65 PDS-II

Disk-Read(ci[x])

if n[ci[x]] = 2t - 1

then B-Tree-Split-Child(x, i, ci[x])

if k > keyi[x]

then i <- i + 1

B-Tree-Insert-Nonfull(ci[x], k)

To perform an insertion on a b-tree, the appropriate node for the key must be located using an

algorithm similiar to B-Tree-Search. Next, the key must be inserted into the node. If the node is

not full prior to the insertion, no special action is required; however, if the node is full, the node

must be split to make room for the new key. Since splitting the node results in moving one key to

the parent node, the parent node must not be full or another split operation is required. This

process may repeat all the way up to the root and may require splitting the root node. This

approach requires two passes. The first pass locates the node where the key should be inserted;

the second pass performs any required splits on the ancestor nodes.

Since each access to a node may correspond to a costly disk access, it is desirable to avoid the

second pass by ensuring that the parent node is never full. To accomplish this, the presented

algorithm splits any full nodes encountered while descending the tree. Although this approach

may result in unecessary split operations, it guarantees that the parent never needs to be split and

eliminates the need for a second pass up the tree. Since a split runs in linear time, it has little

effect on the O(t logt n) running time of B-Tree-Insert.

Splitting the root node is handled as a special case since a new root must be created to contain

the median key of the old root. Observe that a b-tree will grow from the top.

B-Tree-Delete

Deletion of a key from a b-tree is possible; however, special care must be taken to ensure that the

properties of a b-tree are maintained. Several cases must be considered. If the deletion reduces

the number of keys in a node below the minimum degree of the tree, this violation must be

corrected by combining several nodes and possibly reducing the height of the tree. If the key has

children, the children must be rearranged. For a detailed discussion of deleting from a b-tree,

refer to Section 19.3, pages 395-397, of Cormen, Leiserson, and Rivest or to another reference

listed below.

Page 66: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 66 PDS-II

Examples

Sample B-Tree

Searching a B-Tree for Key 21

Page 67: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 67 PDS-II

3. Explain Red-Black Tree. [CO4 – L2]

Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node follows

following rules.

1) Every node has a color either red or black.

2) Root of tree is always black.

3) There are no two adjacent red nodes (A red node cannot have a red parent or red child).

4) Every path from root to a NULL node has same number of black nodes.

Why Red-Black Trees? Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is

the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree.

If we make sure that height of the tree remains O(Logn) after every insertion and deletion, then

we can guarantee an upper bound of O(Logn) for all these operations. The height of a Red Black

tree is always O(Logn) where n is the number of nodes in the tree.

Comparison with AVL Tree

The AVL trees are more balanced compared to Red Black Trees, but they may cause more

rotations during insertion and deletion. So if your application involves many frequent insertions

and deletions, then Red Black trees should be preferred. And if the insertions and deletions are

less frequent and search is more frequent operation, then AVL tree should be preferred over Red

Black Tree.

How does a Red-Black Tree ensure balance? A simple example to understand balancing is, a chain of 3 nodes is not possible in red black tree.

We can try any combination of colors and see all of them violate Red-Black tree property.

A chain of 3 nodes is nodes is not possible in Red-Black Trees.

Following are NOT Red-Black Trees

30 30 30

20 NIL 20 NIL 20 NIL

10 NIL 10 NIL 10 NIL

Violates Violates Violates

Property 4 Property 4 Property 3

Page 68: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 68 PDS-II

Following are different possible Red-Black Trees with above 3 keys

20 20

10 30 10 30

NIL NIL NIL NIL NIL NIL NIL NIL

From the above examples, we get some idea how Red-Black trees ensure balance. Following is

an important fact about balancing in Red-Black Trees.

Every Red Black Tree with n nodes has height <= 2Log2(n+1)

This can be proved using following facts:

1) For a general Binary Tree, let k be the minimum number of nodes on all root to NULL paths,

then n >= 2k – 1 (Ex. If k is 3, then n is atleast 7). This expression can also be written as k <=

2Log2(n+1)

2) From property 4 of Red-Black trees and above claim, we can say in a Red-Black Tree with n

nodes, there is a root to leaf path with at-most Log2(n+1) black nodes.

3) From property 3 of Red-Black trees, we can claim that the number black nodes in a Red-Black

tree is at least ⌊ n/2 ⌋ where n is total number of nodes.

From above 2 points, we can conclude the fact that Red Black Tree with n nodes has height <=

2Log2(n+1)

In this post, we introduced Red-Black trees and discussed how balance is ensured. The hard part

is to maintain balance when keys are added and removed. We will soon be discussing insertion

and deletion operations in coming posts on Red-Black tree.

Insertion and Deletion

In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused

imbalance. In Red-Black tree, we use two tools to do balancing.

1) Recoloring

2) Rotation

We try recoloring first, if recoloring doesn‟t work, then we go for rotation. Following is detailed

algorithm. The algorithms has mainly two cases depending upon the color of uncle. If uncle is

red, we do recoloring. If uncle is black, we do rotations and/or recoloring.

Color of a NULL node is considered as BLACK.

Let x be the newly inserted node.

1) Perform standard BST insertion and make the color of newly inserted nodes as RED.

2) If x is root, change color of x as BLACK (Black height of complete tree increases by 1).

3) Do following if color of x‟s parent is not BLACK or x is not root.

Page 69: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 69 PDS-II

a) If x’s uncle is RED (Grand parent must have been black from property 4)

(i) Change color of parent and uncle as BLACK.

(ii) color of grand parent as RED.

(iii) Change x = x‟s grandparent, repeat steps 2 and 3 for new x.

b) If x’s uncle is BLACK, then there can be four configurations for x, x‟s parent (p) and x‟s

grandparent(g) (This is similar to AVL Tree)

i) Left Left Case (p is left child of g and x is left child of p)

ii) Left Right Case (p is left child of g and x is right child of p)

iii) Right Right Case (Mirror of case a)

iv) Right Left Case (Mirror of case c)

Following are operations to be performed in four subcases when uncle is BLACK.

All four cases when Uncle is BLACK

Left Left Case (See g, p and x)

Left Right Case (See g, p and x)

Page 70: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 70 PDS-II

Right Right Case (See g, p and x)

Right Left Case (See g, p and x)

Examples of Insertion

Page 71: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 71 PDS-II

Insertion Vs Deletion:

Like Insertion, recoloring and rotations are used to maintain the Red-Black properties.

In insert operation, we check color of uncle to decide the appropriate case. In delete

operation, we check color of sibling to decide the appropriate case.

The main property that violates after insertion is two consecutive reds. In delete, the main

violated property is, change of black height in subtrees as deletion of a black node may cause

reduced black height in one root to leaf path.

Deletion is fairly complex process. To understand deletion, notion of double black is used.

When a black node is deleted and replaced by a black child, the child is marked as double black.

The main task now becomes to convert this double black to single black.

Deletion Steps

Following are detailed steps for deletion.

1) Perform standard BST delete. When we perform standard delete operation in BST, we always

end up deleting a node which is either leaf or has only one child (For an internal node, we copy

the successor and then recursively call delete for successor, successor is always a leaf node or a

node with one child). So we only need to handle cases where a node is leaf or has one child. Let

v be the node to be deleted and u be the child that replaces v (Note that u is NULL when v is a

leaf and color of NULL is considered as Black).

2) Simple Case: If either u or v is red, we mark the replaced child as black (No change in black

height). Note that both u and v cannot be red as v is parent of u and two consecutive reds are not

allowed in red-black tree.

Page 72: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 72 PDS-II

3) If Both u and v are Black.

3.1) Color u as double black. Now our task reduces to convert this double black to single black.

Note that If v is leaf, then u is NULL and color of NULL is considered as black. So the deletion

of a black leaf also causes a double black.

3.2) Do following while the current node u is double black or it is not root. Let sibling of node

be s.

(a): If sibling s is black and at least one of sibling’s children is red, perform rotation(s). Let

the red child of s be r. This case can be divided in four subcases depending upon positions of s

and r.

(i) Left Left Case (s is left child of its parent and r is left child of s or both children of s are red).

This is mirror of right right case shown in below diagram.

(ii) Left Right Case (s is left child of its parent and r is right child). This is mirror of right left

case shown in below diagram.

(iii) Right Right Case (s is right child of its parent and r is right child of s or both children of s

are red)

Page 73: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 73 PDS-II

(iv) Right Left Case (s is right child of its parent and r is left child of s)

(b): If sibling is black and its both children are black, perform recoloring, and recur for the

parent if parent is black.

In this case, if parent was red, then we didn‟t need to recur for prent, we can simply make it

black (red + double black = single black)

(c): If sibling is red, perform a rotation to move old sibling up, recolor the old sibling and

parent. The new sibling is always black (See the below diagram). This mainly converts the tree

to black sibling case (by rotation) and leads to case (a) or (b). This case can be divided in two

subcases.

(i) Left Case (s is left child of its parent). This is mirror of right right case shown in below

diagram. We right rotate the parent p.

(ii) Right Case (s is right child of its parent). We left rotate the parent p.

Page 74: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 74 PDS-II

Page 75: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 75 PDS-II

4. Explain Splay Tree. [CO4 – L2 – May/June2015]

The worst case time complexity of Binary Search Tree (BST) operations like search, delete,

insert is O(n). The worst case occurs when the tree is skewed. We can get the worst case time

complexity as O(Logn) with AVL and Red-Black Trees.

Can we do better than AVL or Red-Black trees in practical situations?

Like AVL and Red-Black Trees, Splay tree is also self-balancing BST. The main idea of splay

tree is to bring the recently accessed item to root of the tree, this makes the recently searched

item to be accessible in O(1) time if accessed again. The idea is to use locality of reference (In a

typical application, 80% of the access are to 20% of the items). Imagine a situation where we

have millions or billions of keys and only few of them are accessed frequently, which is very

likely in many practical applications.

All splay tree operations run in O(log n) time on average, where n is the number of entries in the

tree. Any single operation can take Theta(n) time in the worst case.

Search Operation

The search operation in Splay tree does the standard BST search, in addition to search, it also

splays (move a node to the root). If the search is successful, then the node that is found is splayed

and becomes the new root. Else the last node accessed prior to reaching the NULL is splayed and

becomes the new root.

There are following cases for the node being accessed.

1) Node is root We simply return the root, don‟t do anything else as the accessed node is already

root.

2) Zig: Node is child of root (the node has no grandparent). Node is either a left child of root

(we do a right rotation) or node is a right child of its parent (we do a left rotation).

T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side)

y x

/ \ Zig (Right Rotation) / \

x T3 – - – - – - – - - -> T1 y

/ \ < - - - - - - - - - / \

T1 T2 Zag (Left Rotation) T2 T3

3) Node has both parent and grandparent. There can be following subcases.

3.a) Zig-Zig and Zag-Zag Node is left child of parent and parent is also left child of grand

parent (Two right rotations) OR node is right child of its parent and parent is also right child of

grand parent (Two Left Rotations).

Page 76: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 76 PDS-II

Zig-Zig (Left Left Case):

G P X

/ \ / \ / \

P T4 rightRotate(G) X G rightRotate(P) T1 P

/ \ ============>/ \ / \ ============> / \

X T3 T1 T2 T3 T4 T2 G

/ \ / \

T1 T2 T3 T4

Zag-Zag (Right Right Case):

G P X

/ \ / \ / \

T1 P leftRotate(G) G X leftRotate(P) P T4

/ \ ============> / \ / \ ============> / \

T2 X T1 T2 T3 T4 G T3

/ \ / \

T3 T4 T1 T2

3.b) Zig-Zag and Zag-Zig Node is left child of parent and parent is right child of grand parent

(Left Rotation followed by right rotation) OR node is right child of its parent and parent is left

child of grand parent (Right Rotation followed by left rotation).

Zig-Zag (Left Right Case):

G G X

/ \ / \ / \

P T4 leftRotate(P) X T4 rightRotate(G) P G

/ \ ============> / \ ============> / \ / \

T1 X P T3 T1 T2 T3 T4

/ \ / \

T2 T3 T1 T2

Zag-Zig (Right Left Case):

G G X

/ \ / \ / \

T1 P rightRotate(P) T1 X leftRotate(P) G P

/ \ =============> / \ ============> / \ / \

X T4 T2 P T1 T2 T3 T4

/ \ / \

T2 T3 T3 T4

Example:

100 100 [20]

/ \ / \ \

50 200 50 200 50

/ search(20) / search(20) / \

40 ======> [20] ========> 30 100

/ 1. Zig-Zig \ 2. Zig-Zig \ \

30 at 40 30 at 100 40 200

/ \

[20] 40

The important thing to note is, the search or splay operation not only brings the searched key to root, but

also balances the BST. For example in above case, height of BST is reduced by 1.

Page 77: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 77 PDS-II

5. Explain Binomial Heap. [CO4 – L2 – May/June2015]

The main application of Binary Heap is as implement priority queue. Binomial Heap is to

extension of Binary Heap that provides faster union or merge operation together with other

operations provided by Binary Heap.

A Binomial Heap is a collection of Binomial Trees

What is a Binomial Tree?

A Binomial Tree of order 0 has 1 node. A Binomial Tree of order k can be constructed by taking

two binomial trees of order k-1, and making one as leftmost child of other.

A Binomial Tree of order k has following properties.

a) It has exactly 2k nodes.

b) It has depth as k.

c) There are exactly kCi nodes at depth i for i = 0, 1, . . . , k.

d) The root has degree k and children of root are themselves Binomial Trees with order k-1, k-

2,.. 0 from

left to right.

The following diagram is taken from 2nd Edition of CLRS book.

Binomial Heap:

A Binomial Heap is a set of Binomial Trees where each Binomial Tree follows Min Heap

property. And there can be at-most one Binomial Tree of any degree.

Page 78: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 78 PDS-II

Examples Binomial Heap:

12------------10--------------------20

/ \ / | \

15 50 70 50 40

| / | |

30 80 85 65

|

100

A Binomial Heap with 13 nodes. It is a collection of 3

Binomial Trees of orders 0, 2 and 3 from left to right.

10--------------------20

/ \ / | \

15 50 70 50 40

| / | |

30 80 85 65

|

100

A Binomial Heap with 12 nodes. It is a collection of 2

Binomial Trees of orders 2 and 3 from left to right.

Binary Representation of a number and Binomial Heaps

A Binomial Heap with n nodes has number of Binomial Trees equal to the number of set bits in

Binary representation of n. For example let n be 13, there 3 set bits in binary representation of n

(00001101), hence 3 Binomial Trees. We can also relate degree of these Binomial Trees with

positions of set bits. With this relation we can conclude that there are O(Logn) Binomial Trees in

a Binomial Heap with „n‟ nodes.

Operations of Binomial Heap:

The main operation in Binomial Heap is union(), all other operations mainly use this operation.

The union() operation is to combine two Binomial Heaps into one. Let us first discuss other

operations, we will discuss union later.

1) insert(H, k): Inserts a key „k‟ to Binomial Heap „H‟. This operation first creates a Binomial

Heap with single key „k‟, then calls union on H and the new Binomial heap.

2) getMin(H): A simple way to getMin() is to traverse the list of root of Binomial Trees and

return the minimum key. This implementation requires O(Logn) time. It can be optimized to

O(1) by maintaining a pointer to minimum key root.

3) extractMin(H): This operation also uses union(). We first call getMin() to find the minimum

key Binomial Tree, then we remove the node and create a new Binomial Heap by connecting all

Page 79: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 79 PDS-II

subtrees of the removed minimum node. Finally we call union() on H and the newly created

Binomial Heap. This operation requires O(Logn) time.

4) delete(H): Like Binary Heap, delete operation first reduces the key to minus infinite, then calls

extractMin().

5) decreaseKey(H): decreaseKey() is also similar to Binary Heap. We compare the decreases key

with it parent and if parent‟s key is more, we swap keys and recur for parent. We stop when we

either reach a node whose parent has smaller key or we hit the root node. Time complexity of

decreaseKey() is O(Logn).

Union operation in Binomial Heap:

Given two Binomial Heaps H1 and H2, union(H1, H2) creates a single Binomial Heap.

1) The first step is to simply merge the two Heaps in non-decreasing order of degrees. In the

following diagram, figure(b) shows the result after merging.

2) After the simple merge, we need to make sure that there is at-most one Binomial Tree of any

order. To do this, we need to combine Binomial Trees of same order. We traverse the list of

merged roots, we keep track of three pointers, prev, x and next-x. There can be following 4 cases

when we traverse the list of roots.

Case 1: Orders of x and next-x are not same, we simply move ahead.

In following 3 cases orders of x and next-x are same.

Case 2: If order of next-next-x is also same, move ahead.

Case 3: If key of x is smaller than or equal to key of next-x, then make next-x as a child of x by

linking it with x.

Case 4: If key of x is greater, then make x as child of next.

Page 80: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 80 PDS-II

The following diagram is taken from 2nd Edition of CLRS book.

Page 81: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 81 PDS-II

UNIT V GRAPHS

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

Minimum Spanning Trees – Kruskal and Prim algorithm – Shortest path algorithm – Dijkstra‟s

algorithm – Bellman-Ford algorithm – Floyd-Warshall algorithm.

PART –A

1. Define tree. [CO5 – L1] Trees are non-liner data structure, which is used to store data items in a shorted

sequence. It represents any hierarchical relationship between any data Item. It is a

collection of nodes, which has a distinguish node called the root and zero or more

nonempty sub trees T1, T2,….Tk. each of which are connected by a directed edge

from the root. 2. Define Height of tree. [CO5 – L1] The height of n is the length of the longest path from root to a leaf. Thus all leaves

have height zero. The height of a tree is equal to a height of a root. 3. Define Depth of tree. [CO5 – L1] For any node n, the depth of n is the length of the unique path from the root to node n.

Thus for a root the depth is always zero. 4. Define Degree of a node. [CO5 – L1] It is the number of sub trees of a node in a given tree. 5. Define Degree of a tree. [CO5 – L1] It is the maximum degree of a node in a given tree. 6. Define Terminal node or leaf? [CO5 – L1] Nodes with no children are known as leaves. A leaf will always have degree zero and is also

called as terminal node.

7. Define Non-terminal node? [CO5 – L1]

Any node except the root node whose degree is a non-zero value is called as a non-terminal

node. Non-terminal nodes are the intermediate nodes in traversing the given tree from its root

node to the terminal node.

8. Define sibling? [CO5 – L1] Nodes with the same parent are called siblings. 9. Define binary tree? [CO5 – L1]

A Binary tree is a finite set of data items which is either empty or consists of a single item

called root and two disjoin binary trees called left sub tree max degree of any node is two.

10. Define expression tree? [CO5 – L1] Expression tree is also a binary tree in which the leafs terminal nodes or operands and

non-terminal intermediate nodes are operators used for traversal.

Page 82: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 82 PDS-II

11. Define Construction of expression trees [CO5 – L1]

1. Convert the given infix expression into postfix notation

2. Create a stack and read each character of the expression and push into the stack, if

operands are encountered.

3. When an operator is encountered pop 2 values from the stack.

12. Define lazy deletion? [CO5 – L1] When an element is to be deleted it is left in the tree itself and marked as being deleted. This is

called as lazy deletion and is an efficient procedure if duplicate keys are present in the binary

search tree, because the field that keeps count of the frequency of appearance of the element can

be decremented of the element can be decremented. 13. Define AVL tree? [CO5 – L1] AVL tree also called as height balanced tree .It is a height balanced tree in which every

node will have a balancing factor of –1,0,1. Balancing factor of a node is given by the difference between the height of the left sub tree

and the height of the right sub tree.

14. What are the various operation performed in the binary search tree? [CO5 – L1] 1. insertion

2. deletion

3. find

4. find min

5. find max 15. What are the various transformation performed in AVL tree? [CO5 – L1] 1. Single rotation - Single L rotation - Single R rotation

2. Double rotation -LR rotation -RL rotation

16. General idea of hashing and what is the use of hashing function? [CO5 – H1] A hash table similar to an array of some fixes size-containing keys. The keys

specified here might be either integer or strings, the size of the table is taken as table size or the

keys are mapped on to some number on the hash table from a range of 0 to table size 17. What is priority queue? [CO5 – L1]

A priority queue is a data structure that allows at least the following two operations: insert

which does the obvious thing; and Deletemin, which finds, returns, and removes the minimum

element in the priority queue. The Insert operation is the equivalent to enqueue.

18. Application of priority queues? [CO5 – H1] 1. for scheduling purpose in operating system

2. used for external sorting

3. important for the implementation of greedy algorithm, which operates by

repeatedly finding a minimum.

Page 83: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 83 PDS-II

19. What are the main properties of a binary heap? [CO5 – L1] 1. Structure property

2. Heap order property 20. Define tree traversal and mention the type of traversals? [CO5 – L1] Visiting of each and every node in the tree exactly is called as tree traversal

Three types of tree traversal

1. inorder traversal 2. preoder traversal 3. postorder traversal.

21. What is insertion sort? How many passes are required for the elements to be

sorted? [CO5 – L1] One of the simplest sorting algorithms is the insertion sort. Insertion sort consist of N-1 passes.

For pass P=1 through N-1 , insertion sort ensures that the elements in positions 0 through P-1 are in

sorted order .It makes use of the fact that elements in position 0

through P-1 are already known to be in sorted order . 22. Write the function in C for insertion sort? [CO5 – L1] Void insertionsort(elementtype A[ ] , int N)

{

int j, p; elementtype tmp;

for(p=1 ; p <N ;p++ )

{

tmp = a[ p] ;

for ( j=p ; j>0 && a [ j -1 ] >tmp ;j--) a [ j ]=a

[j-1 ] ;

a [ j ] = tmp ;

}

} 23. Who invented shell sort? Define it? [CO5 – L1] Shell sort was invented by Donald Shell. It works by comparing element that are distant. The

distance between the comparisons decreases as the algorithm runs until the last phase in which

adjacent elements are compared. Hence it is referred as diminishing increment sort.

24. Write the function in c for shell sort? [CO5 – L1] Void Shellsort(Elementtype A[ ],int N) { int i , j , increment ;

elementtype tmp ; for(elementtype=N / 2;increment > 0;increment / = 2) For( i=

increment ; i <N ; i ++) {

Page 84: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 84 PDS-II

tmp=A[ ]; for( j=I; j>=increment; j - =increment) if(tmp< A[ ]=A[j – increment]; A[ j ]=A[ j – increment]; Else Break; A[ j ]=tmp; } }

25. What is maxheap? [CO5 – L1]

If we want the elements in the more typical increasing sorted order, we can change the

ordering property so that the parent has a larger key than the child. it is called max heap.

26. What are the two stages for heap sort? [CO5 – L1] Stage 1: Construction of heap

Stage 2: Root deletion N-1 times

27. What is divide and conquer strategy? [CO5 – L1] In divide and conquer strategy the given problem is divided into smaller problems and solved

recursively. The conquering phase consists of patching together the answers. Divide and conquer

is a very powerful use of recursion that we will see many times.

28. Differentiate between merge sort and quick sort? [CO5 – L1] Mergesort Quicksort

1. Divide and conquer strategy Divide and conquer strategy

2. Partition by position Partition by value

29. Mention some methods for choosing the pivot element in quicksort? [CO5 – L1] 1. Choosing first element

2. Generate random number

3. Median of three

30. What are the three cases that arise during the left to right scan in quicksort? [CO5 –

L1] 1. I and j cross each other

2. I and j do not cross each other

3. I and j points the same position 31. What is the need of external sorting? [CO5 – L1] External sorting is required where the input is too large to fit into memory. So

external sorting is necessary where the program is too large.

Page 85: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 85 PDS-II

32. Define two way merge? [CO5 – L1] It is a basic external sorting in which there are two inputs and two outputs tapes. 33. Define multi way merge? [CO5 – L1] If we have extra tapes then we can expect to reduce the number of passes required to sort

our input. We do this by extending two way merge to a k-way merge.

34. Define polyphase merge? [CO5 – L1] The k-way merging strategy requires the use of 2 k tapes. This could be prohibitive for

some applications. It is possible to get by with only k+1 tapes.

35. What is replacement selection? [CO5 – L1] We read as many records as possible and sort them. Writing the result to some tapes. This seems

like the best approach possible until one realizes that as soon as the first record is written to a

output tape the memory it used becomes available for another record. If the next record on the

input tape is larger than the record we have just output then it can be included in the item. Using

this we can give algorithm. This is called replacement selection. 36. What is sorting? [CO5 – L1] Sorting is the process of arranging the given items in a logical order. Sorting is an

example where the analysis can be precisely performed. 37. What is mergesort? [CO5 – L1] The mergesort algorithm is a classic divide and conquer strategy. The problem is divided

into two arrays and merged into single array

38. What are the properties involved in heapsort? [CO5 – L1] 1. Structure property

2. Heap order property 39. Define articulation points. [CO5 – L1] If a graph is not biconnected, the vertices whose removal would disconnect the graph are

known as articulation points.

40. Give some example of NP complete problems. [CO5 – L1] i. Hamiltonian circuit.

ii. Travelling salesmen problems

iii. Longest path problems

iv. Bin packing

v. Knapsack problem

vi. Graph coloring problem \

41. What is a graph? [CO5 – L1] A graph consists of a set of vertices V and set of edges E which is mathematically represented as

G=(V,E).Each edge in a pair(V,W) where V,W, belongs to E ,edges are sometimes referred to as

arcs.

Page 86: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 86 PDS-II

42. What are Directed graphs? [CO5 – L1] If a pair of vertices for any edge is ordered, then that graph is called as Digraph or directed

graph.

43. Define Path. [CO5 – L1]

A path in a graph is a sequence of vertices w1,w2w,3,wN such that Wi,Wi+1 belongs to E for a

value 1<=I<=N. The length of such a path is the number of edges on the path, which is equal to

n-1.

44. Define Cycle. [CO5 – L1] A cycle is a path in which the first and last vertices are the same. 45. Define Acyclic graph. [CO5 – L1]

A graph with no cycles is called Acyclic graph. A directed graph with no Edges is called as a

directed Acyclic graph (or) DAG. DAGS are used for Compiler Optimization process.

46. Define Connected graph. [CO5 – L1] An undirected graph is connected if there is a path from every vertex to every other vertex. A

directed graph with this property is called as strongly connected graph. If a directed graph is

not strongly connected but the underline graph. Without direction is connected it is called as a

weakly connected graph.

47. What are the conditions for a graph to become a tree? [CO5 – L1] A graph is a tree if it has two properties. i. If it is a connected graph.

ii. There should not be any cycles in the graph.

48. Define a Weighted Graph. [CO5 – L1]

A graph is said to be a weighted graph if every edge in the graph is assigned some weight or

value. The weight of the edge is a positive value that represents the cost of moving the edge

or the distance between two vertices.

49. Give the types of representation of graphs. [CO5 – L2] 1. Adjacency matrix

2. Adjacency linked list

50. What is a minimum spanning tree? [CO5 – L1] A minimum spanning tree of an undirected graph G is a tree formed from graph edges

that connect all the vertices of G at lowest total cost.

Page 87: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 87 PDS-II

51. Explain about Adjacency Matrix. [CO5 – L2] Adjacency matrix consists of a n*n matrix where n is the no. of vertices present. In the

graph, which consists of values either 0 or 1.

52. Explain about Adjacency linked list. [CO5 – L2] It consists of a table with the no. of entries for each vertex for each entry a Linked List is

initiated for the vertices adjacent to the corresponding table entry.

53. What is a single source shortest path problem? [CO5 – L1] Given as an input, a weighted graph, G=<V,E> and a distinguished vertex „S‟

as the source vertex. Single source shortest path problem finds the shortest weighted path from s

to every other vertex in G.

54. Explain about Unweighted shortest path. [CO5 – L2] Single source shortest path finds the shortest path from the source to each and

every vertex present in a unweighted graph. Here no cost is associated with the edges

connecting the vertices. Always unit cost is associated with each edge.

55. Explain about Weighted shortest path [CO5 – L2] Single source shortest path finds the shortest path from the source to each and every

vertex present in a weighted graph. In a weighted graph some cost is always associated

with the edges connecting the vertices. 56. What are the methods to solve minimum spanning tree? [CO5 – L1] a) Prim‟s algorithm

b) Kruskal‟s algorithm 57. Explain briefly about Prim‟s algorithm. [CO5 – L2]

Prim‟s algorithm creates the spanning tree in various stages. At each stage, a node

is picked as the root and an edge is added and thus the associated vertex along with it. 58. Define a depth first spanning tree. [CO5 – L1] The tree that is formulated by depth first search on a graph is called as depth first

spanning tree. The depth first spanning tree consists of tree edges and back edges. 59. What is a tree edge? [CO5 – L1] Traversal from one vertex to the next vertex in a graph is called as a tree edge. 60. What is a back edge? [CO5 – L1] The possibility of reaching an already marked vertex is indicated by a dashed line, in a

graph is called as back edge.

61. Define double linked list? [CO5 – L1]

It is linear data structure which consists of two links or pointer fields Next pointer points to the

address of the next (successor) node. Previous pointer points to the address of theprevious

(predecessor) node.

Page 88: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 88 PDS-II

PART B

1. Discuss Prim’s and Kruskal’s algorithm for computing the minimal spanning tree

weighted undirected graph. (16) [CO5 – L3 -Nov/Dec 2009, Nov/ Dec 2011]

Prim‟s Algorithm

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connected

weighted undirected graph. This means it finds a subset of the edges that forms a tree that

includes every vertex, where the total weight of all the edges in the tree is minimized.

Start form any arbitrary vertex

Find the edge that has minimum weight form all known vertices

Stop when the tree covers all vertices

Kruskal‟s algorithm

Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for

a connected weighted graph. This means it finds a subset of the edges that forms a tree that

includes every vertex, where the total weight of all the edges in the tree is minimized.

Arrange all edges in a list (L) in non decreasing order Select edges from L, and include - that in set T, avoid cycle.

Repeat 3 until T becomes a tree that covers all vertices.

2. Describe the shortest path identification using Dijkstra’s algorithm. [CO5 – L2 - Nov/ Dec

2011]

DIJKSTRA (G, w, s)

INITIALIZE SINGLE-SOURCE (G, s)

S ← { } // S will ultimately contains vertices of final shortest-path weights from s

Initialize priority queue Q i.e., Q ← V[G] while priority queue Q is not empty do u ← EXTRACT_MIN(Q) // Pull out new vertex S ←

S È {u}

Perform relaxation for each vertex v adjacent to u fo reach vertex v in Adj[u] do Relax (u, v, w)

Dijkstra's algorithm is one of the most efficient shortest path algorithm. Dijkstra's algorithm is a

label-setting algorithm. Always examines a node with the minimum distance label and no node is examined more than

once. Nodes have distance labels which are either permanent or temporary. Permanent labels are shortest path distances and do not change. Temporary labels are estimates of shortest path distances and may change. In each iteration, the algorithm makes a temporary distance label permanent.

Page 89: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 89 PDS-II

3. What is a graph? Explain the depth first search tree. [CO5 – L1 - Nov/ Dec

2011,May/June 2007] A graph consists of a set of vertices V and set of edges E which is mathematically

represented as G=(V,E). Each edge in a pair(V,W) where V,W, belongs to E ,edges are

sometimes referred to as arcs. Depth first search dfs(G)

{ list L = empty tree T = empty choose a starting vertex x search(x) while(L nonempty)

remove edge (v,w) from end of L if w not yet visited

{ add (v,w) to T

search(w) }

}

search(vertex v) {

visit(v); for each edge (v,w)

add edge (v,w) to end of L }

4. Define spanning tree and minimal spanning tree. Write the Kruskal,s algorithm for finding minimal spanning tree of any graph. [CO5 – L1 - Nov/ Dec 2012] Spanning tree Spanning tree of the graph is a connected sub graph in which there are no cycles Minimal spanning tree A minimum spanning tree of an undirected graph G is a tree formed from graph edges

that connect all the vertices of G at lowest total cost.

Kruskals Algorithm 5. Explain the principle of topological sort. [CO5 – L2 - NOV/DEC 2010]

Find the vertex with no incoming edge.

Print the vertex and remove it along with its edges from the graph. Apply the same strategy to the rest of the graph. Finally all recorded vertices give topological sorted list.

Page 90: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 90 PDS-II

6. Explain in detail about Floyd Warshall Algorithm. [CO5 – L2]

The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. The problem is

to find shortest distances between every pair of vertices in a given edge weighted directed Graph.

Example:

Input: graph[][] = { {0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1}, {INF, INF, INF, 0} }

which represents the following graph 10

(0)------->(3) | /|\

5 | | | | 1 \|/ | (1)------->(2)

3 Note that the value of graph[i][j] is 0 if i is equal to j And graph[i][j] is INF (infinite) if there is no edge from vertex i to j.

Output: Shortest distance matrix

0 5 8 9

INF 0 3 4

INF INF 0 1

INF INF INF 0

Floyd Warshall Algorithm

We initialize the solution matrix same as the input graph matrix as a first step. Then we update

the solution matrix by considering all vertices as an intermediate vertex. The idea is to one by

one pick all vertices and update all shortest paths which include the picked vertex as an

intermediate vertex in the shortest path. When we pick vertex number k as an intermediate

vertex, we already have considered vertices {0, 1, 2, .. k-1} as intermediate vertices. For every

pair (i, j) of source and destination vertices respectively, there are two possible cases. 1) k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]

as it is.

2) k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as

dist[i][k] + dist[k][j]. The following figure is taken from the Cormen book. It shows the above optimal substructure

property in the all-pairs shortest path problem.

Page 91: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 91 PDS-II

7. Explain in detail about Breadth-first search: the basic algorithm. [CO5 – L2 - Nov/Dec

2010] Given a graph with N vertices and a selected vertex A:

for(i = 1; there are unvisited vertices ; i++) Visit all unvisited vertices at distance i (i is the length of the shortest path between A and

currently processed vertices) algorithm for single source shortest path uses breadth-first search

For a graph with N vertices the shortest path between two vertices can be at most N-1. The

search is implemented by storing the neighbors in a queue. BFS algorithm Store source vertex S in a queue and mark as processed

While queue is not empty Read vertex v from the queue For all neighbors w: If w is not processed Mark as processed Append in the queue Record the parent of w to be v (parent is necessary only if we need the shortest path tree) Use a distance table to mark vertices as processed by storing the distance to the source vertex.

Adjacency lists A: B, C, E

B: A, C, E C: A, B, D D: C, E

Page 92: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 92 PDS-II

E: A, E Let's select A as the starting node. Distance table:

Nodes A B C D E

Distance 0 to A

Parent 0

Queue: A 1. After reading A from the queue and processing its neighbors: Distance table:

Nodes A B C D E

Distance 0 1 1 1

to A

Parent 0 A A A Queue: B, C, E Read B. Its neighbors are A, C and E. All are processed.

Queue: C, E Read C. Its neighbors are A, B and D. A and B are processed. D is not. After processing D;

Distance table Nodes A B C D E

Distance 0 1 1 2 1 to A Parent 0 A A C A Queue: E, D

Read E. Its neighbors are processed

Read D. Its neighbors are processed The queue is empty and the algorithm ends.

Question: Is there a more efficient way to organize the „while‟ loop above? Shortest Path Tree Consider the distance table: Nodes A B C D E

Distance 0 1 1 2 1

to A

Parent 0 A A C A

Page 93: SKP Engineering College - it.skpec.edu.init.skpec.edu.in/wp-content/uploads/sites/7/2017/11/Programming-and...SKP Engineering College Tiruvannamalai – 606611 A Course Material on

S.K.P. Engineering College, Tiruvannamalai III SEM

Computer Science Engineering Department 93 PDS-II

The table defines the shortest path tree, rooted at A.

Complexity of the BFS algorithm Consider the algorithm‟s basic loop:

While queue is not empty: 1. Read vertex v from the queue 2. For all neighbors w:

If w is not processed Mark w as processed

Append w in the queue In step 1 read a node from the queue. The question to be answered is: how many nodes are stored in the queue? The answer is: each node is stored only once – if it is not processed. Thus the

reading step will be performed O(V) times, where V is the number of the nodes in the graph. In step 2 examine all neighbors, i.e. examine all edges of the currently read node. Since the

graph is not oriented, examine 2*E edges, where E is the number of the edges in the graph. Hence the complexity of BFS is O(V + 2*E)

If we use adjacency matrix instead of adjacency lists, the complexity will be O(V2)