Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
in
ANNA UNIVERSITY
SYLLABUS COPY (REGULATION 2013)
EC6301 OBJECTPROGRAMMING AND DATA STRUCTURES L T P C
3 0 0 3
TABLE OF CONTENTS
Sl.No Topic Page No.
a Aim and Objective of the Subject 5
b Detailed Lesson Plan 6
UNIT I DATA ABSTRACTION & OVERLOADING
I PART A 9
II PART B 14
1 Parameterized Constructor and Copy Constructor 14
2a Function overloading 17
2b Binary overloading 19
3 Friend Function 24
4 Operator overloading 25
5 Constructor and Destructor 28
III PART C 30
6 Object oriented Programming Concepts 30
7 Call By Value Call By Reference 34
REFERENCES:
1. Bhushan Trivedi, “Programming with ANSI C++, A Step-By-Step approach”, Oxford University
Press, 2010.
2. Goodrich, Michael T., Roberto Tamassia, David Mount, “Data Structures and Algorithms in
C++”, 7th Edition, Wiley. 2004.
3. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, “Introduction to
Algorithms”, Second Edition, Mc Graw Hill, 2002.
4. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson Education, 2007.
5. Ellis Horowitz, Sartaj Sahni and Dinesh Mehta, “Fundamentals of Data Structures in C++”,
Galgotia Publications, 2007.
Hours Cumu
Sl. Books
Unit Topic / Portions to be Covered Required lative
No Referred
/ Planned Hrs
UNIT I DATA ABSTRACTION & OVERLOADING
Overview of C++- Concepts of OOPS,
1 1 1 1 TB1,RB1,RB4
Applications
2 1 Structures , Definition, Usage 1 2 TB1,RB1,RB4
UNIT I
PART-A
1. What is a destructor? Nov/Dec 2015
Destructor
It is used to destroy the objects that have been created by constructor. Destructor name
is same as class name preceded by tilde symbol (~)
Eg:
~ integer()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler
upon exit from the program will invoke it.
A friend function that is a "friend" of a given class is allowed access to private and
protected data in that class that it would not normally be able to as if the data was public .
Normally, a function that is defined outside of a class cannot access such information.
References are often confused with pointers but three major differences between
references and pointers are:
• You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
• Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
• A reference must be initialized when it is created. Pointers can be initialized at any
time.
For example, suppose we have the following example:
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
4. Write a C++ code to swap values of two variable using reference variables in
function. Nov/Dec 2014
#include <iostream.h>
// function declaration
void swap(int &x, int &y);
int main (void)
{
int a = 100; // local variable declaration:
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;
return 0;
}
10
Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight, and cost and uses functions to operate on these attributes. The
attributes are sometimes called as data members because they hold information. The
functions that operate on these data are called as methods or member functions.
Eg:
Class A
{
int a,b; // a,b are data members
void getdata ( ) ; // member function
};
Reference variables provide a kind of link to the original variable and becomes alias
for the original variable.
syntax for defining a variable is
<data type>& ref variable = original variable;
e.g int &a =b;
11
New -used to dynamically allocate memory for built in data type or user define
data types.
Example:
int *p=new int[15];
delete-to de-allocate the memory allocated
example: delete []p;
They are collection classes which are designed to hold collections of objects. They
provide services such as insertion, deletion, searching, sorting, testing an item to determine
whether it is a member of the collection. Arrays, Stacks, Queues, Trees and Linked lists are
examples.
12
An iterator is an object that returns the next item of a collection. It is associated with
container classes. Iterators hold state information sensitive to the particular containers on
which they operate.
13. Write a C++ code to display “pen object instantiated” and “pen object
destroyed”when class for pen constructor and destructor are called. Nov/dec 2014
class pen
{
int m,n;
public:
pen( ); .
~pen()
{
cout<<”pen object destroyed”;
}
};
pen::pen( )
{
void display()
{
cout<<”pen object instantiated”;
}
}
void main()
{
Pen p;
}
13
Proxy class in C++ is used to implement the Proxy Pattern in which an object is an
interface or a mediator for some other object. A typical use of a proxy class in C++ is
implementing the [ ] operator since the [ ] operator may be used to get data or to set data
within an object
Dynamic memory is allocated using operator new. new is followed by a data type
specifier and, if a sequence of more than one element is required, the number of these
within brackets []. It returns a pointer to the beginning of the new block of memory
allocated.
Its syntax is:
pointer = new type
pointer = new type [number_of_elements]
PART-B
Constructor
It is a special member function whose task is to initialize the objects of its class. It is
special because its name is the name as the class name. It is invoked when an object is
created.
Eg:
class sample
14
{
int m,n;
public:
sample()
{
m=0;
n=0;
}
};
The rules to be followed
• It should be in public section
• It should have the same name as that of the class name
• It has no return type
• It cannot be virtual
• It cannot be inherited
Parameterized Constructor
A constructor with arguments is called as parameterized constructor. It is invoked
when an object is created with matching arguments.
Eg:
class sample
{
int a,b;
public:
sample()
{
a=0;
b=0;
}
sample(int d,int e)
{
a=d;
15
b=e;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj(10,5);
obj.display();
}
Output:
10 5
Copy Constructor
It is used to declare and initialize objects from another object.
Eg:
class sample
{
int a,b;
public:
sample()
{
a=0;
b=0;
}
sample(int d,int e)
{
a=d;
b=e;
}
16
sample(sample &obj)
{
a=obj.a;
b=obj.b;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj(10,5);
sample obj1(obj)
obj1.display();
}
Output:
10 5
FUNCTION OVERLOADING
It is a compile time polymorphism where more than one function have the same name but
differ either in the number of arguments or the type of arguments.
Eg:
void area(float r)
{
17
float a;
a=3.14*r*r;
cout<<"\nArea of the circle is:"<<a;
}
void area(int l,int b)
{
int area;
area=l*b;
cout<<"\nArea of rectangle is:"<<area;
}
void main()
{
int a,b;
float c;
cout<<"\nEnter length and breadth:";
cin>>a>>b;
area(a,b);
cout<<"\nEnter the radius:"
cin>>c;
area(c);
}
Output:
Enter length and breadth:
10
20
Area of Rectangle is 200
Enter the radius: 10
Area of Circle is 314.0000
18
BINARY OVERLOADING
19
{
x=-x;
y=-y;
z=-z;
}
void main()
{
sample obj;
obj.getdata(10,20,-30);
-obj; //Overloaded Operator is called
obj.display();
}
Output:
X=-10 Y=-20 Z=30
Binary Operator Overloading
It can be done in two ways
• Without using friend function
• Using Friend Function
Without Using Friend Function
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
complex()
{
}
complex (float real,float img)
{
20
x=real;
y=img;
}
void display()
{
cout<<x<<”+i”<<y;
}
complex operator +(complex);
};
complex complex::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return temp;
}
void main()
{
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;
c1.display();
cout<<”\nC2\n”;
c2.display();
c3=c1+c2;
cout<<”\nC3\n”;
c3.display();
getch();
}
21
Output:
C1
5.0+i6.0
C2
4.4+i3.3
C3
9.4+i9.9
22
complex temp;
temp.x=c1.x+c2.x;
temp.y=c1.y+c2.y;
return temp;
}
void main()
{
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;
c1.display();
cout<<”\nC2\n”;
c2.display();
c3=c1+c2;
cout<<”\nC3\n”;
c3.display();
getch();
}
Output:
C1
5.0+i6.0
C2
4.4+i3.3
C3
9.4+i9.9
23
FRIEND FUNCTION
3. Write a member function and friend function to subtract two complex numbers in
C++. Nov/Dec 2015
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
complex()
{
}
complex(float real,float img)
{
x=real;
y=img;
}
void display()
{
cout<<x<<”+i”<<y;
}
friend complex operator -(complex, complex);
};
complex operator-(complex c1,complex c2)
{
complex temp;
temp.x=c1.x+c2.x;
temp.y=c1.y+c2.y;
return temp;
24
}
void main()
{
complex c1(5.0,6.0),c2(4.4,3.3),c3;
cout<<”\nC1\n”;
c1.display();
cout<<”\nC2\n”;
c2.display();
c3=c1-c2;
cout<<”\nC3\n”;
c3.display();
getch();
}
Output:
C1
5.0+i6.0
C2
4.4+i3.3
C3
0.6+i2.7
OPERATOR OVERLOADING
#include<iostream.h>
#include<math.h>
#include<conio.h>
#include<string.h>
25
#define SIZE 3
class Addition
{
public:
char name[10];
int num;
int a[SIZE][SIZE];
Addition()
{
Strcpy(name,””);
Num=0;
}
Addition (char n[10],int val,int x[SIZE][SIZE]);
Addition operator + (Addition obj);
};
Addition::Addition (char n[10],int val,int x[SIZE][SIZ])
{
strcpy(name,n);
num=val;
for(int i=0;i<SIZE;i++)
for(int j=0;j<SIZE;J++)
a[i][j]=x[i][j];
}
Addition Addition::operator +(Addition obj)
{
Addition temp;
strcat(name,obj.name);strcpy(temp.name,name);
temp.num=num+obj.num;
for(int i=0;i<SIZE;i++)
for(int j=0;j<SIZE;j++)
temp.a[i][j]=a[i][j]+obj.a[i][j];
26
return temp;
}
void main()
{
int mat1[SIZE][SIZE]={{1,2,3},{4,5,6},{7,8,9}};
int mat1[SIZE][SIZE]={{1,1,1},{2,2,2},{3,3,3}};
Addition obj1(“Hello”,10,mat1);
Addition obj2(“Friend”,20,mat2);
Addition obj3;
obj3=obj1+obj2;
cout<<”\n concatenated string is”<<obj3.name;
cout<<”addition of two numbers is”<<obj3.num;
cout<<”addition of two numbers is”;
for(int =0;i<SIZE;i++)
for(int j=0;j<SIZE;j++)
cout<<””<<obj3.a[i][j];
cout<<”\n”;
}
OUTPUT
concatenated string is: HelloFriend
addition of two numbers is 30
addition of two matrices is 2 3 4 6 7 8 10 11 12
27
5. What is the purpose constructor and destructor? Explain with suitable example the
different types of constructors in C++. Apr/May 2015
It is a special member function whose task is to initialize the objects of its class. It is
special because its name is the name as the class name. It is invoked when an object is
created.
Eg:
class sample
{
int m,n;
public:
sample()
{
m=0;
n=0;
}
};
The rules to be followed
• It should be in public section
• It should have the same name as that of the class name
• It has no return type
• It cannot be virtual
• It cannot be inherited
Default Constructor
A constructor with no arguments is called as default constructor. It is mainly used to
initialize the variables to a default value. It is called when an object is created with no
arguments.
Eg:
class sample
28
{
int a,b;
public:
sample()
{
a=5;
b=10;
}
void display()
{
cout<<a<<b;
}
};
void main()
{
sample obj;
obj.display();
}
Output:
5 10
Destructor
A destructor is used to destroy the objects that have been created by a constructor. It is also
a member function whose name is the same as the class name but is preceded by a tilde(~)
operator.
Eg: ~sample()
It is invoked when an object is destroyed. It cannot be overloaded. It has no return
type and no arguments
Eg:
class sample
29
{
int id;
public:
sample()
{
id=5;
}
~sample()
{
cout<<id;
}
};
void main()
{
sample obj;
}
Output:
5
PART – C
• Dynamic Binding
• Message Passing
• Persistance and Delegation
• Genericity
Classes
The entire set of data and code of an object can be made a user defined data type
with the help of a class. Objects are variables of the type class. Once a class has been
created any number of objects can be created belonging to that class. Thus a class is a
collection of objects of similar type.
Eg: fruit mango;
Where fruit is the class name and mango is the object name
Objects
Objects are the basic run time entities in an object oriented system. They may
represent a person, a place or any item. A program object should be selected such that they
match closely with the real world objects. Objects communicate with each other by passing
message.
Each object contains data and code to manipulate the data.
Object : Student
STUDENT
DATA
TOTAL
Name
DOB
Marks AVG
..........
FUNCTIONS DISPLAY
TOTAL
AVG
DISPLAY
31
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. It is the most striking feature of a class. The data is not accessible to the
outside world and those functions which are wrapped in the class only can access it. This
separation of the data from direct access is called data hiding.
Abstraction refers to the act of representing the essential features without including
the background details such as size, weight and cost. The variables are called as data
members and the function is called as methods or member function.
Inheritance
It is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. It provides the idea of
reusability which means that we can add additional features to an existing class without
modifying it. The newly created class is called as derived class and the old class is called as
base class. BIRD
FLYING
BIRD
NON-FLYING
BIRD
Polymorphism
It is derived from a Greek word which means the ability to take more than one form.
It is classified into two types. They are
• Compile Time Polymorphism
❖ Operator Overloading
❖ Function Overloading
• Runtime Polymorphism
An operation may exhibit different behaviours in different instances. The behaviour
depends on the type of data used in the operation. That is, the process of making an operator
to exhibit different behaviours in different instances. It is called as operator overloading.
32
Draw()
Draw() Draw()
Triangle
Circle Rectangle
Draw()
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the function call. Dynamic Binding means that the code to be used for a
function call is not known until the time of the call at run time. It is related to inheritance
and polymorphism.
Message Passing
An object oriented programming consists of a set of objects that communicate with
each other. The steps for communicating are
❖ Create class with data and code
❖ Create objects for that class
❖ Establish communication
employee . salary(name)
Object Information
Message
Persistance
This is the process in which the object(data) outlives the program execution time and
exist between the execution of the program. In C++, this can be achieved by explicitly using
the file streams.
33
Delegation
Delegation is a way of making object composition as powerful as inheritance. In
delegation two objects are involved in handling a request receiving object delegates
operations to its delegate. This is analogous to child class sending requests to the parent
class.
Genericity
This is the technique for defining the generic software components(having more than
one interpretation depending on the data type of the parameter) where the declaration of
data items does not have the data type and the unknown data type is called as generic data
type.
Call by Value
Here the copy of the actual arguments is passed to the formal arguments.
Hence any change in formal arguments is not affected in actual argument.
Eg:
34
20
Value of a and b before swapping: 10 20
After swapping in Swap Function a and b are: 20 10
After swapping in Main Function a and b are: 10 20
Call by Reference
Here the reference of the actual arguments is passed to the formal arguments.
Hence any change in formal arguments is affected in the actual argument.
Eg:
void swap(int *a,int *b)
{
int t=*a;
*a=*b;
*b=t;
35
UNIT-II
INHERITANCE & POLYMORPHISM
Base Classes and Derived Classes – Protected Members – Casting Class pointers
and Member Functions – Overriding – Public, Protected and Private Inheritance –
Constructors and Destructors in derived Classes – Implicit Derived – Class Object
To Base – Class Object Conversion – Composition Vs. Inheritance – Virtual
functions – This Pointer – Abstract Base Classes and Concrete Classes – Virtual
Destructors – Dynamic Binding
PART-A
1. Define polymorphism.
• It refers to the linking of a procedure call to the code to be executed in response to the call.
• Dynamic binging means that the code associated with a given procedure call is not
known until the time of the call at run time.
• It is associated with polymorphism and inheritance.
36
• C++ uses the unique keyword called this to represent an object that invokes a member function.
• this is a pointer that points to the object for which this function was called.
• This unique pointer is automatically passed to a member function when it is called.
The pointer this acts as an implicit argument to all the member functions.
• One important application of the this pointer this is to return the object it points to.
A virtual function that is declared in a base class but not defined there.The responsibility
for defining the function falls on the derived classes, each of which generally provides different
definitions.
It is illegal to create instances of a class that declares a pure virtual function. So such a
class is necessarily an abstract base class.
Abstract class is one that is not used to create objects. An abstract class is
designed only to act as a base class. It is a design concept in program development
and provides a base upon which other classes may be built.
37
38
Conversion from one class type to another is the combination of class to basic and
basic to class type conversion. Here constructor is used in destination class and casting
operator function is used in source class.
Eg:objX=objY
objX is the object of class X and objY is an object of class Y. The class Y type data is
converted into class X type data and the converted value is assigned to the obj X. Here
class Y is the source class and class X is the destination class.
.
11. Why there is need for operator overloading?April/May 2015
12. Write a C++ code to display as area of square or rectangle using function
overriding.Nov/dec 2014
#include<iostream.h>
Class rectangle
{
private:
Double len,breadth:
public:
void setlengthbreadth(double l,double b);
void computeArea();
void Rectangle::setlengthbreadth(double l,double b)
{
len=l;
breadth=b;
}
39
void Rectangle::computeArea()
{
double area;
Area=len*breadth;
cout<<”\n Area of Recangle =”<<area;
}
class square:public Rectangle
{
private:
Double len;
public:
void setlength(double l);
void computeArea();
void square::setlength(double l)
{
len=l;
}
void square::computeArea()
{
double area;
Are=len*len;
cout<<”\narea of Square=”<<area;
}
int main()
{
Rectangle obj1;
Square obj2;
obj1.setlengthBreadth(10,20);
obj1.computeArea();
obj2.setlength(10);
obj2.ComputeArea();// function overriding
40
return 0;
}
Output
Area of the Rectangle =200
Area of square=100
13. Write a sample to code to show the usage of this pointer in C++.
Nov/ Dec 2014
#include<iostream.h>
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main(void)
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
41
Private - only available to be accessed within the class that defines them.
protected - accessible in the class that defines them and in other classes which inherit
from that class.
15. What is dynamic binding?Nov/Dec 2015
Dynamic binding also called dynamic dispatch is the process of linking procedure
call to a specific sequence of code (method) at run-time. It means that the code to be
executed for a specific procedure call is not known until run-time. Dynamic binding is also
known as late binding or run-time binding.
PART – B
BASED AND DERIVED CLASS
1. a Explain based and derived class with examples. Nov/ Dec 2015
42
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
43
ACCESS MODIFIERS
Data hiding is one of the important features of Object Oriented Programming which
allows preventing the functions of a program to access directly the internal representation of
a class type. The access restriction to the class members is specified by the labeled public,
private, and protected sections within the class body. The keywords public, private, and
A class can have multiple public, protected, or private labeled sections. Each section
remains in effect until either another section label or the closing right brace of the class
body is seen. The default access for members and classes is private.
class Base
public:
protected:
private:
};
Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,
44
• Public
• private
• protected
These access specifiers are used to set boundaries for availability of members of
followed by a colon. You can use either one, two or all 3 specifiers in the same class to set
different boundaries for different class members. They change the boundary for all the
Public:
Public, means all the class members declared under public will be available to everyone.
The data members and member functions declared public can be accessed by other classes
too. Hence there are chances that they might change them. So the key members must not be
declared public.
class PublicAccess
45
Private:
Private keyword, means that no one can access the class members declared private outside
that class. If someone tries to access the private member, they will get a compile time error.
class PrivateAccess
Protected:
Protected, is the last access specifier, and it is similar to private, it makes class member
inaccessible outside the class. But they can be accessed by any subclass of that class. (If
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
46
2. Explain about class object to base and base to class object conversion using
C++ with suitable example. Nov/Dec14
• The class pointer can be cast by the base or by the derived class
• If the base class pointer is cast by the derived class then it is called upcasting
• If the derived class pointer is cast by the base class then it is called d owncasting
• The member function can then be accessed using these pointers
Upcasting:
#include<iostream.h>
class mother
{
public:
void cooks()
{
cout<<”mother coks food”;
}
};
class child:public mother
{
public:
void studies()
{
cout<<”child studies”;
}
};
int main()
{
child child;mother *pmother=&child;
47
pmother->cooks
return 0;
}
Downcasting:
A downcast is the cast frm a base class to a class derived from that base class.The
upcast is a cast form derived class t the baese class.The upcast is safe and implicit but the
downcast needs to be dne carefully .In the following program we are performing
downcasting and then invoking the methods of corresponding classes
. #include<iostream.h>
class mother
{
public:
void cooks()’
{
cout<<”mother coks food”;
}
};
class child1:public mother
{
public:
void studies()
{
cout<<”child1 studies”;
}
};
class child2:public mother
{
public:
void studies()
{
48
cout<<”child2 studies”;
}
};
int main()
{
mother *mother=new child1;
child1 *pchild1=(child1*)(pmother);
child2 *pchild1=(child2*)(pmother);
cout<<”using object of mother class”;
pmother->cooks();
cout<<”using object of child1 class”;
pchild1->studies();
cout<<”using object of child2 class”;
pchild1->studies();
}
VIRTUAL FUNCTIONS
49
class shape
{
public:
virtual void draw()
{
cout<<"shape is drawn";
cout<<endl;
}
};
class circle:public shape
{
public:
void draw()
{
cout<<"circle is drawn";
cout<<endl;
}
};
void main()
{
clrscr();
shape s;
shape *ps;
ps=&s;
cout<<"s.draw(): ";
s.draw();
cout<<"ps->draw(): ";
ps->draw();
circle c;
ps=&c;
cout<<"\n";
50
Output:
s.draw():shape is drawn
ps->draw():shape is drawn
After pointer ps is set to hold the address of object c
c.draw():circle is drawn
ps->draw():circle is drawn
Explanation:
Initially the pointer to object 'ps' is made to point the shape object. Hence when ps->draw()
is called shape draw function is executed. When the pointer to object ps is made to point
circle object. When ps->draw() is called the circle draw function is called because the circle
function in shape is made virtual.
THIS POINTER
This Pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.
51
Let us try the following example to understand the concept of this pointer:
#include <iostream.h>
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
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))
52
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
StaticBinding
By default, matching of function call with the correct function definition happens
at compile time. This is called static binding or early binding or compile-time binding.
Static binding is achieved using function overloading and operator overloading.
Dynamic Binding
C++ provides facility to specify that the compiler should match function calls
with the correct definition at the run time; this is called dynamic binding or late binding
or run-time binding. Dynamic binding is achieved using virtual functions. Base class
pointer points to derived class object. And a function is declared virtual in base class,
then the matching function is identified at run-time using virtual table entry.
53
INHERITANCE
It is a process by which the object of one class acquire the properties of objects of
another class. The new class is called as derived class whereas the already existing
one is called as base class.
The various types of inheritance are
❖ Single Inheritance
❖ Multilevel Inheritance
❖ Multiple Inheritance
❖ Hierarchical Inheritance
❖ Hybrid Inheritance
The syntax is
class derivedclassname : visibilitymode baseclassname
{
//STS;
};
Base Class Derived Class Visibility
Visibility Public Private Protected
Private Not Inherited Not Inherited Not
Inherited
Public Public Private Protected
Protected Protected Private Protected
Single Inheritance
It is an inheritance where a derived class has only one base class.
BASE CLASS
A
DERIVED CLASS
54
Eg:
class A
{
public:
int a;
void puta()
{
cout<<a;
}
};
class B:public A
{
public:
int b;
void putb()
{
cout<<b;
}
};
void main()
{
B obj;
obj.a=10;
obj.b=15;
obj.puta();
obj.putb();
}
Output
10 15
55
Explanation
Here the variable 'a' and puta() in class A are inherited to class B with public visibility
mode.
Multiple Inheritance
It is an inheritance where the derived class has more than one base class
A B
Eg: C
class A
{
public:
int a;
void puta()
{
cout<<a;
}
};
class B
{
public:
int b;
void putb()
{
cout<<b;
}
};
class C:public A,public B
56
{
public:
int c;
void putc()
{
cout<<c;
}
};
void main()
{
C obj;
obj.a=10;
obj.b=15;
obj.c=20;
obj.puta();
obj.putb();
obj.putc();
}
Output:
10 15 20
Explanation:
Here the variables 'a' from class A and 'b' from class B are inherited to class C with
public visibility mode.
Multilevel Inheritance
The derived class is derived from intermediate base class which is already derived from
a base class. A
57
Example program:
class A
{
public:
int a;
void puta()
{
cout<<a;
}
};
class B : public A
{
public:
int b;
void putb()
{
cout<<b;
}
};
class C:public B
{
public:
int c;
void putc()
{
cout<<c;
}
};
void main()
{
58
C obj;
obj.a=10;
obj.b=15;
obj.c=20;
obj.puta();
obj.putb();
obj.putc();
}
Output:
10 15 20
Explanation:
The variables 'a' from class A is inherited to class B. Then variable 'a' and 'b' from class
B are inherited to class C with public visibility mode.
Hierarchical Inheritance
In this more than one derived class have the same base class
Eg: B C
class A
{
public:
int a;
void puta()
{
cout<<a;
}
};
class B : public A
{
public:
59
int b;
void putb()
{
cout<<b;
}
};
class C:public A
{
public:
int c;
void putc()
{
cout<<c;
}
};
void main()
{
B obj;
obj.a=5;
obj.b=10;
obj.puta();
obj.putb();
C obj;
obj.a=10;
obj.c=20;
obj.puta();
obj.putc();
}
Explanation:
The variables 'a' from class A is inherited to class B. Also variable 'a' from class A are
inherited to class C with public visibility mode.
60
Hybrid Inheritance
It is a combination of two or more inheritance.
B C
Eg:
class A
{
public:
int a;
void puta()
{
cout<<a;
}
};
class B : public A
{
public:
int b;
void putb()
{
cout<<b;
}
};
class C:public A
{
61
public:
int c;
void putc()
{
cout<<c;
}
};
class D: public B, public C
{
public:
int d;
void putd()
{
cout<<d;
}
};
void main()
{
D obj;
obj.a=5;
obj.b=10;
obj.c=20;
obj.d=20;
obj.puta();
obj.putb();
obj.putc();
obj.putd();
}
62
PART - C
EXAMPLE PROGRAM
6. Write a C++ code to construct classes of a person with name and age as public
properties, account details as private properties and percentage of mark as protected
property. Construct a class with sports details of person. Construct a class to rank
person based on the equal weightage to academic and sports details. Use inheritance
concept. Nov/Dec 14
#include<iostream.h>
Class Person
{
private:
int accno;
public:
char name[10];
int age;
void PersonDetails()
{
cout<<” Enter your name”;
cin>> name;
cout<<”\n Enter your age:”;
cin>>age;
cout<<”\n Enter Account Number:”;
cin>> accno;
}
void displayPersonDetails()
{
cout<<”\n Name:”<< name;
cout<< “\n Age:”<<age;
cout<<”\n Account Number:”<<accno;
63
}
};
class Academic:public Person
{
protected:
double marks;
public:
void AcademicMarks()
{
cout<<”\n Enter Academic marks”;
cin>>marks;
}
void displayAcademicMarks()
{
Cout<<”\n Academic Marks:”;<<marks;
}
};
class Sports
{
protected:
double score;
public:
void SportsScore()
{
cout<<”\n Enter Sports Score:”;
cin>>score;
}
void displaySportsScore()
{
cout<<”\n Sports Marks:”<<score;
}
64
}
class Rank:public Academic, public Sports
{
double totalMarks;
double m,s;
public:
void display()
{
m=marks/2;
s=score/2;
totalMarks=m+s;
displayPersonalDetails();
displayAcademicMarks();
displaySportsScore();
cout<<”\n Total Marks:”<<totalMarks;
}
};
void main()
{
Rank obj;
obj.PersonalDetails();
obj.AcademicMarks();
obj.SportsScore();
obj.display();
}
Input:
Enter your name : AAA
Enter your age : 22
Enter Account Number : 1234
Enter Academic marks : 64
Enter Sports Score : 46
65
Output:
Name : AAA
Age : 22
Account Number : 1234
Academic Marks : 64
Sports Marks : 46
Total Marks : 55
66
IMPLEMENTATION OF CONSTRUCTORS
7. Write a program to illustrate how constructors are implemented when the classes
are inherited. Nov/Dec 2015
#include<iostream.h>
class Base
{
public:
Base()
{
Cout<<"Base Class Constructor Called ";
}
};
void main()
{
Derived obj;
}
Output:
Base Class Constructor Called
Derived Class Constructor Called
67
UNIT – III
LINEAR DATA STRUCTURES
Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list
implementation –– singly linked lists –Polynomial Manipulation – Stack ADT – Queue
ADT – Evaluating arithmetic expressions.
PART A
Abstract Data type is defined by the set of operations that may be performed on it
and by mathematical constraints on the effects of those operations.
Abstract Data type is an extension of modular design.
• An abstract data type is a set of operations such as Union, Intersection, Complement,
Find etc.,
• The basic idea of implementing ADT is that the operations are written once in
program and can be called by any part of the program
The queue abstract data type is defined by the following structure and operations. A
queue is structured, as an ordered collection of items which are added at one end, called the
“rear”, and removed from the other end, called the “front”. Queues maintain a FIFO
ordering property.
68
The implementation we will use is known as a binary heap. Its use is so common for
priority queue implementations that when the word heap is used without a qualifier
Structure Property A heap is a binary tree that is completely filled, with the possible
exception of the bottom level, which is filled from left to right. Such a tree is known as a
complete binary tree.
6. What are the operations of ADT?
Union, Intersection, size, complement and find are the various operations of ADT.
• Value definition
• Operator definition
8. Define len(S),first(S),last(S),nilseq.
A Structure is a group of items in which each item is identified by its own identifier,
each of which is known as a member of the structure.
Union is collection of Structures , which permits a variable to be interpreted in
several different ways.
69
A Stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at one end, called the top of the stack. The other name of
stack is Last-in - First-out list.
A Queue is an ordered collection of items from which items may be deleted one end
called the front of the queue and into which tems may be inserted at the other end called
rear of the queue.Queue is called as First–in-First- Out(FIFO).
Priority queue is a data structure in which the intrinsic ordering of the elements does
determine the results of its basic operations. Ascending and Descending priority queue are
the two types of Priority queue.
13. What is a linked list?
Linked list is a kind of series of data structures, which are not necessarily adjacent in
memory. Each structure contain the element and a pointer to a record containing its
successor.
In a simple linked list, there will be one pointer named as 'NEXT POINTER' to point
the next element, where as in a doubly linked list, there will be two pointers one to point the
next element and the other to point the previous element location.
70
PART B
Linked list consists of series of nodes. Each node contains the element and a pointer to
its successor node. The pointer of the last node points to NULL.
Insertion and deletion operations are easily performed using linked list. A single node
is represented as follows
71
Node* next;
public:
Node() {};
void SetData(int aData) { data = aData; };
void SetNext(Node* aNext) { next = aNext; }; int Data() { return data; };
Node* Next() { return next; };
};
Example: Insert the element ‘5’ in the beginning of the list temp.
Before insertion
After Insertion :
72
Before deletion
After deletion
73
{
// Create a temp pointer Node *tmp = head;
// No nodes
LIST ADT
74
75
• And we usually have to delete more than once – five, twelve, N times.
2. Linked List Implementation
• A linked list is a series of connected NODES, where each node is a data structure.
• A linked list can grow or shrink in size as the program runs
The composition of a Linked List
• Each node in a linked list contains one or more members that represent data.
• In addition to the data, each node contains a pointer, which can point to another
node.
• A linked list is called "linked" because each node in the series has a pointer that
points to the next node in the list.
APPLICATIONS OF STACK
76
INFIX
In Infix notation, The arithmetic operator appears between the two operands to which
it is being applied. For example : - A / B + C
POSTFIX
The arithmetic operator appears directly after the two operands to which it applies.
Also called as reverse polish notation. ((A/B) + C). For example : - AB / C +
PREFIX
The arithmetic operator is placed before the two operands to which it applies. Also
called as polish notation. ((A/B) + C). For example : - +/ABC
INFIX PREFIX (or) POLISH POSTFIX (or) REVERSE POLISH
1. (A + B) / (C - D) /+AB - CD AB + CD - /
2. A + B*(C - D) +A*B - CD ABCD - * +
3. X * A / B - D - / * XABD X A*B/D-
4. A * B/C + D +/ * ABCD AB * C / D +
Read the postfix expression one character at a time until it encounters the delimiter `#'.
Step 1 : - If the character is an operand, push its associated value onto the stack.
77
Step 2 : - If the character is an operator, POP two values from the stack, apply the operator
to them and push the result onto the stack.
Infix Expression : A * B #
A A
* * A
B * AB
# AB*
Symbol Value
A 4
B 5
EVALUATION OF A B *
78
A 4
-
5
B
4
* 20 result=20
( (
79
a (
+ (
b (
3. Towers of Hanoi
The problem is moving a collection of N disks of decreasing size from one pillar to
another pillar. The movement of the disk is restricted by the following rules.
Rule 1: Only one disk could be moved at a time.
Rule 2: No larger disk could ever reside on a pillar on top of a smaller disk.
Rule 3: A 3rd pillar could be used as an intermediate to store one or more disks, while they
werebeing moved from sourced to destination.
Recursive Solution
N - represents the number of disks.
Step 1. If N = 1, move the disk from A to C.
Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C, Then
move the 1st disk from B to C.
Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as
intermediate.
Then the 3rd disk is moved from A to C. Then repeat the step (2) to move 2 disks
from B to C using A as intermediate.
80
In general, to move N disks. Apply the recursive technique to move N - 1 disks from
A to B using C as an intermediate. Then move the Nth disk from A to C. Then again apply
the recursive technique to move N - 1 disks from B to C using A as an intermediate.
RECURSIVE ROUTINE FOR TOWERS OF HANOI
void hanoi (int n, char s, char d, char i)
{
/* n no. of disks, s source, d destination i intermediate */
if (n = = 1)
{
print (s, d);
return;
}
else
{
hanoi (n - 1, s, i, d);
print (s, d)
hanoi (n-1, i, d, s);
return;
}
}
4.Function Calls
When a call is made to a new function all the variables local to the calling routine
need to be saved, otherwise the new function will overwrite the calling routine variables.
Similarly the current location address in the routine must be saved so that the new function
knows where to go after it is completed.
Main( ) Balance ( ) Push ( )
Return Return
81
3. Write a set of routines for implementing two stacks within a single array.
April/May 2015
Implementation of stack
Array Implementation
In this implementation each stack is associated with a Top pointer,which is -1 for an
empty stack.
• To push an element x on to the stack,Top pointer is incremented and then set
Stack[Top]=x
• To pop an element,the stack[Top] value is returned and the top pointer is
decremented,.
• Pop on an empty stack or push on a full stack will exceed the array bounds.
82
{
Top = Top + 1;
S[Top] = x;
}
}
int IsFull (Stack S)
{
if (Top = = Arraysize)
return (1);
}
pointers.
83
X=S[Top];
Top=Top-1;
}
}
int IsEmpty(stack S)
{
if(Top==-1)
return(1);
}
Routine to return top element of the stack
int TopElement(stack S)
{
if(!IsEmpty(s))
return s[Top];
else
Error(“Empty stack”);
return 0;
}
Linked List Implementation of Stack
Push operation is performed by inserting an element at the front of the list.
Pop operation is performed by deleting at the front of the list.
Top operation returns the element at the front of the list.
Declaration for linked list Implementation
struct Node;
typedef struct Node *stack;
int IsEmpty(stack S);
stack Createstack(void);
void MakeEmpty(stack S);
void push(int X,stack S);
int Top(stack S);
void Top(stack S);
84
struct Node
{
int Element;
struct Node *Next;
}
Routine to check whether the stack is Empty.
int IsEmpty(stack S)
{
if(S-> Next==NULL)
return(1);
}
Routine to create an Empty stack
stack CreateStack()
{
stack S;
S=malloc(sizeof(struct Node));
if(s==NULL)
Error(“Out of space”);
Make Empty(S);
return S;
}
void MakeEmpty(stack S)
{
if(S==NULL)
Error(“Create stack First”);
else
while(!IsEmpty(S))
pop(S);
}
85
86
S ->Next=S->Next-> Next;
Free(Tempcell);
}
}
QUEUE
OPERATIONS ON QUEUE
The fundamental operations performed on queue are: Enqueue and Dequeue.
Enqueue : The process of inserting an element in the queue.
Dequeue : The process of deleting an element from the queue.
EXCEPTIONAL CONDITIONS
Oveflow: Attempt to insert an element into the queue, when the queue is full is said to
be overflow.
Underflow: Attempt to delete an element from the queue, when the queue is empty is
said to be underflow.
IMPLEMENTATION OF QUEUE
Queue can be implemented in 2 ways.
1. Array Implementation
2. Linked List Implementation
87
ARRAY IMPLEMENTATION
o In order to create a queue we require a one dimensional array Q(1:n) and two
variables front and rear. The conventions we shall adopt for these two
variables are that front is always 1 less than the actual front of the queue and
rear always points to the last element in the queue.
• Thus, front = rear if and only if there are no elements in the queue.
• The initial condition is front = rear = -1.
• The various queue operations to perform creation, deletion and display the elements
in a queue are as follows:
• In this implementation queue Q is associated with two pointers namely rear pointer
and front pointer.
• To insert an element X onto the Queue Q, the rear pointer is incremented by 1 and
then set Queue [Rear] = X
• To delete an element, the Queue [Front] is returned and the Front Pointer is
incremented by 1.
ROUTINE TO ENQUEUE
void Enqueue (int X)
{
if (rear = = max _ Arraysize-1)
print (" Queue overflow");
else
{
rear = rear + 1;
Queue [rear] = X;
if(front==-1)
88
front=0;
}
}
89
Front rear
100 400
30 400 40 X
10 200 20 300
90
return (1);
}
ROUTINE TO CHECK AN EMPTY QUEUE
Struct CreateQueue ( )
{
Queue Q;
Q = malloc (Sizeof (Struct Node));
if (Q = = NULL)
printf ("Out of Space");
MakeEmpty (Q);
return Q;
}
void MakeEmpty (Queue Q)
{
if (Q = = NULL)
printf ("Create Queue First");
else
while (! IsEmpty (Q)
Dequeue (Q);
}
ROUTINE TO ENQUEUE AN ELEMENT IN QUEUE
void Enqueue (int X)
{
Struct node *newnode;
newnode = malloc (sizeof (Struct node));
if (Rear = = NULL)
{
newnode →data = X;
newnode →Next = NULL;
Front = newnode;
Rear = newnode;
91
}
else
{
newnode → data = X;
newnode → Next = NULL;
Rear →next = newnode;
Rear = newnode;
}
}
92
5. Write a C++ code to perform addition of two polynomials using link list form of
queue. Nov/Dec 2014
#include <iostream.h>
class poly
{
private :
struct polynode
{
float coeff ;
int exp ;
polynode *link ;
} *p ;
public :
poly( ) ;
void poly_append ( float c, int e ) ;
void display_poly( ) ;
void poly_add( poly &l1, poly &l2 ) ;
~poly( ) ;
};
poly :: poly( )
{
p = NULL ;
}
void poly :: poly_append ( float c, int e )
{
polynode *temp = p ;
if ( temp == NULL )
{
93
94
95
else
{
if ( temp1 -> exp > temp2 -> exp )
{
z -> coeff = temp1 -> coeff ;
z -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
else
{
if ( temp1 -> exp == temp2 -> exp )
{
z -> coeff = temp1 -> coeff + temp2 -> coeff ;
z -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
temp2 = temp2 -> link ;
}
}
}
}
while ( temp1 != NULL )
{
if ( p == NULL )
{
p = new polynode ;
z=p;
}
else
{
z -> link = new polynode ;
z = z -> link ;
96
}
z -> coeff = temp1 -> coeff ;
z -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
while ( temp2 != NULL )
{
if ( p == NULL )
{
p = new polynode ;
z=p;
}
else
{
z -> link = new polynode ;
z = z -> link ;
}
z -> coeff = temp2 -> coeff ;
z -> exp = temp2 -> exp ;
temp2 = temp2 -> link ;
}
z -> link = NULL ;
}
poly :: ~poly( )
{
polynode *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q;
97
}
}
void main( )
{
poly p1 ;
p1.poly_append ( 1.4, 5 ) ;
p1.poly_append ( 1.5, 4 ) ;
p1.poly_append ( 1.7, 2 ) ;
p1.poly_append ( 1.8, 1 ) ;
p1.poly_append ( 1.9, 0 ) ;
cout << "\nFirst polynomial:" ;
p1.display_poly( ) ;
poly p2 ;
p2.poly_append ( 1.5, 6 ) ;
p2.poly_append ( 2.5, 5 ) ;
p2.poly_append ( -3.5, 4 ) ;
p2.poly_append ( 4.5, 3 ) ;
p2.poly_append ( 6.5, 1 ) ;
cout << "\nSecond polynomial:" ;
p2.display_poly( ) ;
poly p3 ;
p3.poly_add ( p1, p2 ) ;
cout << "\nResultant polynomial: " ;
p3.display_poly( ) ;
}
98
PART - C
SUM OF ODD NUMBERS USING SINGLY LINKED LIST
6. Write a C++ program to sum up all odd numbers using singly linked list.
Nov/Dec 2014
#include<iostream.h>
#include<conio.h>
class sll
{
public:
struct node
{
int data;
struct node *next;
}*temp,*first,*nnode;
sll()
{
first=NULL;
}
void create(int);
void addodd();
void display();
};
//function for creating a sll
void sll::create(int element)
{
nnode=newnode;
nnode->data=element;
nnode->next= NULL;
if(first== NULL)
{
99
first=nnode;
temp=nnode;
}
else
{
temp->next=nnode;
temp=nnode;
}
}
void sll::addodd()
{
int sum=0,odd,res;
temp=first;
while(temp!= NULL)
{
res=(temp->data)%2;
if(res!=0)
{
add=temp->data;
sum+=odd;
}
temp=temp->next;
}
cout<<”displaying elements”<<display();
cout<<”result “<<sum;
}
//func tion that display the elements of the singly linked list
void sll::display()
{
temp=first;
while(temp!= NULL)
100
{
cout<<temp->data;
temp=temp->next
}
int main()
{
clrscr();
int ch,n,i,element1[10];
sll obj;
cout<<”addition of add n umbers in a singly linked list”;
while(1)
{
cout<<”\n 1.create 2.addodd numbers 3.display 4.exit”;
cout<<”enter your choice”;
cin>>ch;
switch(ch)
{
case 1:
cout<<”enter the number of elements”;
cin>>n;
cout<<”enter the elements”;
for(i=0;i<n;i++)
{
cin>>element1[i];
obj.create(element1[i]);
}
break;
case 2:
cout<<”\n adding odd numbers”;
obj.addodd();
break;
101
case 3:
cout<<”\n displaying elements in list”;
obj.display();
break;
case 4:
cout<<”\n program ends”;
exit(0);
}}}
POLYNOMIAL MANIPULATION
linked list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 + 9x0 illustrates in
figure 3.10.1
struct poly{
{
int coeff;
int power;
struct poly *next;
102
Creation of Polynomial:
poly create(poly *head, poly *newnode)
{
poly*ptr;
if(head==NULL)
{
head=newnode;
return(head);
}
else
{
ptr=head;
while(ptr-> next!=NULL)
ptr=ptr->next;
ptr->next=newnode;
}
return(head);
}
Addition of Polynomials:
To add two polynomials we need to scan them once. If we find terms with the same
exponent in the two polynomials, then we add the coefficients; otherwise, we copy the term
of larger exponent into the sum and go on. When we reach at the end of one of the
polynomial, then remaining part of the other is copied into the sum.
To add two polynomials follow the following steps:
• Read two polynomials.
• Add them.
• Display the resultant polynomial.
Addition of Polynomials:
void add()
{
103
104
} ptr2=list2;
ptr1=ptr1->next; } }}}
106
UNIT IV
PART A
1. What is tree? April/May 2015
A tree is a nonlinear data structure. It is mainly used to represent data containing a
hierarchical relationship between elements. Example: records, family trees and tables of
contents. A tree is a finite set of one or more nodes such that there is a specially designated
node called the Root, and zero or more non empty sub trees T1, T2....Tk, each of whose roots
are connected by a directed edge from Root R.
107
3. Find the maximum number of nodes in complete binary tree if d is the depth.
(Nov/Dec 2014)
The maximum number of nodes in a binary tree of depth d is 2d−1 ie)d >=1
A full binary tree is a tree in which all the leaves are on the same level and every
non-leaf node has exactly two children.
A complete binary tree is a tree in which every non-leaf node has exactly two
children not necessarily to be on the same level.
5. Give the representation of network of cities (Chennai, Delhi, Kolkata and Mumbai)
as weighted graph. (Nov/Dec 2014)
108
109
An undirected graph is connected, if there is a path from every vertex to every other
vertex. A directed graph with this property is called strongly connected.
When a directed graph is not strongly connected but the underlying graph is
connected, then the graph is said to be weakly connected.
If a graph is not biconnected, the vertices whose removal would disconnect the graph
are known as articulation points.
If w is the ancestor of v, then vw is called a back edge. When process (v,w), find that
w is aready marked and when processing(w,v), find that v is already marked. Then draw a
dashed line, it called as back edge to indicate that this edge is not really part of the tree.
110
The union operation is a operation in which the elements from one set are combined
with a element of the another set.The repetition of element is avoided.
PART B
111
Routine
void preorder (Tree T)
{
if (T!= NULL) /* Base case, if t is null, do nothing */
{
printf(“%c”, T → Element); /* Print the value of the root */
preorder (T → Left); /* Traverse the left sub tree in in-order */
preorder (T → Right); /* Traverse the right sub tree in in-order */
}}
}
Inorder: (also called Left-Element-Right Traversal)
1. Traverse the left subtree of R in inorder.
2. Process the root R
3. Traverse the right subtree of R in inorder.
EXAMPLE
Consider the binary tree T.
Observe that A is the root, that its left subtree consists of nodes B, D and E and that its right
sub tree consists of nodes C and F.
The inorder traversal of T traverses left subtree, processes A and traverses right
subtree. However, the in order traversal of left subtree processes D, B and then E, and the
inorder traversal of right subtree processes C and then F. Hence DBEACF is the inorder
traversal of T.
112
Routine
void inorder (Tree T)
{
if (T!= NULL) /* Base case, if p is null, do nothing */
{
inorder (T→ Left); /* Traverse the left sub tree in in-order */
printf(“%c”, T →Element); /* Print the value of the root */
inorder (T → Right); /* Traverse the right sub tree in in-order */
}
}
113
Observe that A is the root, that its left subtree consists of nodes B, D and E and that
its right sub tree consists of nodes C and F.The postorder traversal of T traverses left
subtree, traverses right subtree, and processes A. However, the postorder traversal of left
subtree processes D, E and then B, and the postorder traversal of right subtree processes F
and then C. Hence, DEBFCA is the postorder traversal of T.
Routine
void postorder (Tree T)
{
if (T!= NULL) /* Base case, if p is null, do nothing */
{
postorder (T → Left); /* Traverse the left sub tree in in-order */
postorder (T→ Right); /* Traverse the right sub tree in in-order */
printf(“%c”, T→ Element); /* Print the value of the root */
}
}
114
Example:
2. Explain DFS and BFS with suitable example. Nov/Dec 2014, Nov/Dec 2015
(or)
Illustrate the Depth First Search algorithm with a graph. April/May 2015
GRAPH TRAVERSAL
A graph traversal is a systematic way of visiting the nodes in a specific order. There
are two types namely,
1) Breadth first traversal
2) Depth first traversal
Breadth first traversal
Breadth first search (BFS) of a graph G starts from an unvisited vertex u. then all the
unvisited vertices vi adjacent to u are visited and then all unvisited vertices wj adjacent to vi
are visited and so on. The traversal terminates when there are no more nodes tp visit. BFS
uses a queue data structure to keep track of the order of nodes whose adjacent nodes are to
be visited.
115
C D
Adjacency matrix:
A B C D
A 0 1 1 0
B 1 0 1 1
C 1 1 0 1
D 0 1 1 0
Implementation
116
3. Then vertex ‘B’ is dequeued and its adjacent vertices C and D are taken from the
adjacency matrix for enqueuing. Since vertex C is already in the queue, vertex D alone is
enqueued. Here B is dequeued, D is enqueued.
C D
4. Then vertex ‘C’ is dequeued and its adjacent vertices A,B and D are found. Since vertices
A and B are already visited and vertex D is also in the queue, no enqueue operation takes
place. Here C is dequeued.
D
5. Then vertex ‘D’ is dequeued. This process terminates as all the vertices are visited and
the queue is empty.
A
Example:
B
C
117
{
Enqueue(v,Q)
Visited[v]=1;}}}
Depth first search
Depth first works by selecting one vertex V of G as a start vertex ; V is marked
visited. Then each unvisited vertex adjacent to V is searched in turn using depth first search
recursively. This process continues until a dead end (i.e.) a vertex with no adjacent
unvisited vertices is encountered. At a dead end, the algorithm backs up one edge to the
vertex it came from and tries to continue visiting unvisited vertices from there.The
algorithm eventually halts after backing up to the starting vertex, with the latter being a
dead end. By then, all the vertices in the same connected component as the starting vertex
have been visited. If unvisited vertices still remain, the depth first search must be restarted
at any one of them.
Routine for depth first search:
Void DFS(Vertex V)
{
Visited[V]=True;
For each W adjacent to V
If(!visited[W]
DFS(W);
}
To implement the Depth first Search performs the following Steps:
Step 1: Choose any node in the graph. Designate it as the search node and mark it as
visited. Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search
node that has not been visited yet. Designate this as the new search node and mark it as
visited.
Step 3: Repeat step 2 using the new search node. If no nodes satisfying (2) can be found,
return to the previous search node and continue from there.
Step 4: When a return to the previous search node in (3) is impossible, the search from the
originally choosen search node is complete.
118
Step 5: If the graph still contains unvisited nodes, choose any node that has not been visited
and repeat step (1) through (4).
Example:
A B
C D
Adjacency matrix
A B C D
A 0 1 1 1
B 1 0 0 1
C 1 0 0 1
D 1 1 1 0
Implementation
1. Let `A' be the source vertex. Mark it to be visited.
2. Find the immediate adjacent unvisited vertex `B' of `A' Mark it to be visited.
3. From `B' the next adjacent vertex is `d' Mark it has visited.
4. From `D' the next unvisited vertex is `C' Mark it to be visited.
A
119
UNDIRECTED GRAPHS
A undirected graph is `connected' if and only if a depth first search starting from any node
visits every node.
A
Example:
B D E
Adjacency matrix
A B C D E
A 0 1 0 1 1
B 1 0 1 1 0
C 0 1 0 1 1
D 1 1 1 0 0
E 1 0 1 0 0
Implementation
We start at vertex `A'. Then Mark A as visited and call DFS (B) recursively, Dfs (B) Marks
B as visited and calls Dfs(c) recursively.
A
Dfs (c) marks C as visited and calls Dfs (D) recursively. No recursive calls are made
to Dfs (B) since B is already visited. A
120
C
Visit & Downloaded from : www.LearnEngineering.in
Visit & Downloaded from : www.LearnEngineering.in
Dfs(D) marks D as visited. Dfs(D) sees A,B,C as marked so no recursive call is made there,
and Dfs(D) returns back to Dfs(C). A
D
E
Since all the vertices starting from ‘A’ are visited, so the above graph is said to be visited.
121
3. Write C++ code for the implementation of different types of tree traversals. State
few tree applications. Nov/Dec 2014
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct btree
{
struct btree *left;
struct btree *right;
int no;
};
void postorder(struct btree *trav);
void inorder(struct btree *trav);
void preorder(struct btree *trav);
struct btree * create(struct btree *trav);
void main()
{
struct btree *root=NULL;
char c;
clrscr();
while(1)
{
root=create(root);
cout<<"Do you want to continue : ";
cin>>c;
if(c=='n' ||c=='N')
break;
}
cout<<endl<<"Inoder is : ";inorder(root);
122
cout<<endl<<"Preorder is : ";preorder(root);
cout<<endl<<"Postorder is : ";postorder(root);
getch();
}
struct btree * create(struct btree *trav)
{
if(trav==NULL)
{
trav=new btree;
trav->right=NULL;
trav->left=NULL;
cout<<"Enter the no : ";
cin>>trav->no;
return(trav);
}
char choice;
cout<<"Enter the left or right child : ";
cin>>choice;
if(choice == 'r' || choice == 'R')
{
trav->right=create(trav->right);
}
if(choice=='l' || choice=='L')
{
trav->left=create(trav->left);
}
return(trav);
}
void inorder(struct btree *trav)
{
if(trav==NULL)
123
return ;
inorder(trav->left);
cout<<" "<<trav->no;
inorder(trav->right);
}
void preorder(struct btree *trav)
{
if(trav==NULL)
return;
cout<<" "<<trav->no;
preorder(trav->left);
preorder(trav->right);
}
void postorder(struct btree *trav)
{
if(trav==NULL)
return;
postorder(trav->left);
postorder(trav->right);
cout<<" "<<trav->no;
}
Tree Applications:
• Binary search tree
• AVL tree, Decision tree
• Splay trees etc.
124
4.(i) How can you construct an expression tree? Describe your answer with an
example. Nov/Dec 2015
Expression Tree is a binary tree in which the leaf nodes are operands and the interior
nodes are operators. Like binary tree, expression tree can also be travesed by inorder,
preorder and postorder traversal.
Example
Constructing an Expression Tree
This algorithm is used to construct the expression tree from the given infix
expression.
1. Convert the infix expression to postfix expression.
2. Create an Empty stack.
3. Read one symbol at a time from the postfix expression.
4. If the symbol is an operand
i) create a one – node tree
ii) Push the tree pointer on to the stack.
5. If the symbol is an operator
i) pop two pointers from the stack namely T1 and T2
ii) Form a new tree with root as the operator and T2 as a left child and T1
as a right child.
iii) A pointer to this new tree is then pushed onto the stack.
6. Repeat steps 3 to 5 until the end of input is reached
Example : -
Consider an example, suppose the input is (a + b ) * c * (d + e )
First we have to convert it into Postfix Expression. The Postfix Expression as a b + c d e + *
*
The first two symbols are operands, so we create one-node trees and push pointers to them
onto a stack.*
125
Next `+’ symbol is read, so two pointers are popped, a new tree is formed and a pointer to
this is pushed on to the stack.
Next, c, d, and e are read, and for each a one-node tree is created and a pointer to the
corresponding tree is pushed onto the stack.
126
127
Next ‘*’ is read, so we pop two tree pointers and form a new tree with a ‘*’ as root.
Finally, the last symbol ‘*’ is read, two trees are merged, and a pointer to the final tree is
left on the stack.
128
SET REPRESENTATION
A set can be represented by a linked list. In this representation, each node has a
pointer to the next node and a pointer to the first node.
129
Union(2,3)
Represented as {1,2,3}
Union(4,5)
Represented as {4,5}
130
Union(6,7)
Represented as {6,7}
Union(5,6)
Represented as {4,5,6,7}
Union(3,7)
Represented as {4,5,6,7,1,2,3}
A union-find data structure that keeps track of a set of elements partitioned into a
number of disjoint (non-overlapping) subsets. A Disjoint-set is an algorithm that performs
two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if
two elements are in the same subset.
131
132
union(6,7) union(5,6)
133
union(3,7)
134
PART - C
MINIMUM SPANNING TREE
6. Discuss about Minimum spanning tree
a b
3
5
1
1
c d
a b
c d Cost = 5
2 2
a b
1
Cost = 5
c d
2
135
Example
Undirected Graph
Spanning Tree
Prim's Algorithm
Prim's algorithm is used compute a minimum spanning tree. It uses a greedy
technique. This algorithm begins with a set U initialized to {1}. It this grows a spanning
tree, one edge at a time. At each step, it finds a shortest edge (u,v) such that the cost of (u,
v) is the smallest among all edges, where u is in Minimum Spanning Tree and V is not in
Minimum Spanning Tree.
void Prims (Table T)
{
vertex V, W;
/* Table initialization */
for (i = 0; i < Numvertex ; i++)
{
T[i]. known = False;
T[i]. Dist = Infinity;
T[i]. path = 0;
}
for (; ;)
{
Let V be the start vertex with the smallest distance
T[V]. dist = 0;
T[V]. known = True;
for each W adjacent to V
136
If (! T[W] . Known)
{
T[W].Dist = Min(T[W]. Dist, CVW);
T[W].path = V;
}
}
}
Kruskal's algorithm
Void kruskal(Graph G)
{
Int EdgesAccepted;
Disjset S;
PriorityQueue H;
Vertex U,V;
SetType Uset,Vset;
Edge E;
Initialize(s);
ReadGraphIntoHeapArray(G,H);
BuildHeap(H);
EdgesAccepted=0;
While(EdgesAccepted < NumVertex-1)
{
E=DeleteMin(H);
Uset=Find(U,S);
Visit=find(V,S);
137
If(Uset != Vest){
EdgesAccepted++;
SetUnion(S,Uset,Vset);
}}}
CONNECTED COMPONENTS
B A
C D F
E
G
Figure shows A graph with articulation points C and D.If a graph is not biconnected, the
vertices whose removal would disconnect the graph are known as articulation points.
These nodes are critical in many applications. The graph in Figure 9.64 is not biconnected:
C and D are articulation points. The removal of C would disconnect G, and the removal of
D would disconnect E and F, from the rest of the graph.The figure is not biconnected : C
and D are articulation points.
B A Fig(1) B A Fig(2)
D F C F
E
G E
138 G
1.Starting at any vertex, we perform a depth-first search and number the nodes as they are
visited. For each vertex, v, we call this preorder number Num(v).
2. compute the lowest numbered vertex, which we call Low(v), that is reachable from v by
taking zero or more tree edges and then possibly one back edge (in that order).
By the definition of Low, Low(v) is the minimum of
1. Num(v)
2. the lowest Num(w) among all back edges (v, w)
3. the lowest Low(w) among all tree edges (v, w)
The first condition is the option of taking no edges
the second way is to choose no tree edges and a back edge
the third way is to choose some tree edges and possibly a back edge
It is easy to compute Low(v)
• The root is an articulation point if and only if it has more than one child, because if it has
two children, removing the root disconnects nodes in different subtrees, and if it has only
one child,removing the root merely disconnects the root.
Any other vertex v is an articulation point if and only if v has some child w such that
Low(w) ≥ Num(v). The time taken to compute this aglorithm O(|E| + |V|) .
Routine to assign Num to vertices (pseudocode)
139
140
UNIT-V
SORTING, SEARCHING
Sorting algorithms: Insertion sort – Quick sort – Merge sort – Searching: Linear
search –Binary Search
PART A
Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime.
However, it’s superior to merge sort in many scenarios because many factors influence an
algorithm’s runtime. In particular, the often-quoted runtime of sorting algorithms refers to
the number of comparisons or the number of swaps necessary to perform to sort the data.
Quicksort in particular requires little additional space and exhibits good cache locality, and
this makes it faster than merge sort in many cases.
It is a partition method using the particular key the given array is partitioned
into 2 subarrays so that first, the original key will be in proper position in the sorted
sequence and secondly all the keys to the left of this pivot will be less in value and all keys
to the right of it will be greater in value.
3. How many passes does the insertion sort algorithm do to sort a list of 5 elements?
What happens in its ith pass?
Number of passes: Total number of elements =5. So insertion sort requires 4 passes.
ith pass: in ith pass of insertion sort will insert ithelement A[i] into its right place among
A[i],A[2]….A[i-1] elements.
141
Merge sort algorithm passes over the entire list and requires atmost log n
passes and merges n elements in each pass. The total number of comparisons required by
the merge sort is given by O(nlogn).
7. Define Efficiency, worst case, best case and average class of an algorithm?
8. What is searching?
Searching is used to find the position of a given number (or) any value in the
given list. If element is not found search is unsuccessful.
142
Sorting is the process of arranging the given items in a logical order. Sorting is
an example where the analysis can be precisely performed.
The main idea of insertion sort is to consider each element at a time, into the
appropriate position relative to the sequence of previously ordered elements, such that the
resulting sequence is also ordered
12. How many passes does the insertion sort algorithm do to sort a list of 5 elements?
What happens in its ith pass?
13. What is the time complexity of quick sort and binary search? Nov/Dec 2014
• The worst-case and average-case time complexity for binary search is O(log n). The best-
case is O(1).
• The worst-case time complexity is O(n2). The average-case (typical) and best-case is O(n
log n)
143
14. How an array element is sorted using merge sort? Nov/Dec 2015
Merge sort is based on divide and conquer strategy the problem is divided into
smaller problems and solved recursively.Finally it merges to sorted list.
Example:
0 1 2 3 4 5 6 7
-40 11 33 37 42 45 99 100
Find the middle element of the array.Compare it with the key.The element to be
searched is 99. i.e Key=99 divide the list into two sublists.
Sublist1
-40 11 33 37
Middle element is 42
Sublist2
45 99 100
So the match is found at 7th position of array i.e array[6].Thus we can find the
element 99 present in the given list at array [6]th location.
144
PART-B
QUICK SORT
1. Write routines for quick sort and explain in detail. Nov/Dec 2014,2015
Or
Illustrate the quick sort working to sort the list {88,11,22,44,66,99,32,67,54,10}
[April/May 2015]
A sorting technique that sequences a list by continuously dividing the list into two
parts andmoving the lower items to one side and the higher items to the other. It starts by
picking one item in the entire list to serve as a pivot point.The pivot could be the first item
or a randomly chosen one. All items that compare lower than the pivot are moved to the left
of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left
side and moves those items to left and right of the pivot and continues the pivot picking and
dividing until there is only one item left in the group. It then proceeds to the right side and
performs the same operation again. Also known as Partition Exchange Sort.
Quick sort algorithm applies a special designing technique called Divide and
Conquer, The divide-and-conquer strategy solves a problem by:
1. Breaking it into sub problems that are themselves smaller instances of the same type of
problem
2. Recursively solving these sub problems
3. Appropriately combining their answers
145
3) Conquer: Finally, to put elements back into S in order, first inserts the elements of L,
then those of E, and those of G.
88 11 22 44 66 99 32 67 54 10
Given the input the array has to be sorted using quick sort
Steps:
1. Increment i till the element in the position is greater than pivot
88 11 22 44 66 99 32 67 54 10
Pivot i=1 i=2 i=3 i=4 i=5
11<88 22<88 44<88 66<88 99>88
146
7. Now 88 is placed in its position and the same procedure is continued in the left and right
sublists of 88.
Left sublist of 88
11. Increment i till the element in the position is greater than pivot
54 11 22 44 32 10 66 67
Pivot i=4 i=5 i=6,j=6
32<54 10<54 66>54
Pivot
147
44 32
Pivot i=4
j=4
32<44
11 22 44 32
Pivot
32 44
10 11 22 32 44 54 66 67 88 99
Code:
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int left, int right);
int main()
{
int arr[30];
int i,n;
printf("Enter total no. of the elements : ");
148
scanf("%d",&n);
printf("Enter total %d elements : \n",size);
for(i=0; i<n; i++)
scanf("%d",&arr[i]);
qsort(arr,0,n-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<n; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
void qsort(int arr[20], int left, int right)
{
int i,j,pivot,tmp;
if(left<right)
{
pivot=left;
i=left+1;
j=right;
while(i<j)
{
while(arr[i]<=arr[pivot] && i<right)
i++;
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
149
}
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
qsort(arr,left,j-1);
qsort(arr,j+1,right);
}
}
INSERTION SORT
2. Explain Insertion sort algorithm and Illustrate its working to perform the list
{35,12,14,9,15,45,32,95,40,5}
The insertion sort, although still O(n2), works in a slightly different way. It always
maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted”
back into the previous sublist such that the sorted sublist is one item larger. The shaded
items represent the ordered sublists as the algorithm makes each pass.
Routine
void insertionsort(int a[],int n)
{
int j,t;
for(int i=1;i<n;i++)
{
t=a[i];
for (int j=i; j>0 && t<a[j-1]; j--)
a[j]=a[j-1];
a[j]=t;
}
}
• It requires two steps:
1. Scan the sorted part to find the place where the element from unsorted part can be
inserted. While scanning shift the elements towards right to create space
150
12 14 35 9 15 45 32 95 40 5
7. Remaining elements are in their position except 5. Take 5 & place it in the correct
position
5 9 12 14 15 32 35 40 45 95
151
bool linear_search ( int *list, int size, int key, int* rec )
{
// Basic Linear search
bool found = false;
int i;
for ( i = 0; i < size; i++ )
152
{
if ( key == list[i] )
break;
}
if ( i < size )
{
found = true;
rec = &list[i];
}
return found;
}
The code searches for the element through a loop starting form 0 to n. The loop can
terminate in one of two ways. If the index variable i reach the end of the list, the loop
condition fails. If the current item in the list matches the key, the loop is terminated early
with a break statement. Then the algorithm tests the index variable to see if it is less than
that size (thus the loop was terminated early and the item was found), or not (and the item
was not found).
Example
Assume the element 45 is searched from a sequence of sorted elements 12, 18, 25,
36, 45, 48, 50. The Linear search starts from the first element 12, since the value to be
searched is not 12 (value 45), the next element 18 is compared and is also not 45, by this
way all the elements before 45 are compared and when the index is 5, the element 45 is
compared with the search value and is equal, hence the element is found and the element
position is 5.
153
BINARY SEARCH
Consider a list in ascending sorted order. It would work to search from the beginning
until an item is found or the end is reached, but it makes more sense to remove as much of
the working data set as possible so that the item is found more quickly. If we started at the
middle of the list we could determine which half the item is in (because the list is sorted).
This effectively divides the working range in half with a single test. By repeating the
procedure, the result is a highly efficient search algorithm called binary search. the time
complexity of binary search is O(log n).the Disadvantage of binary search is all the
elements should be in sorted form.
Routine
int binarysearch(int a[],int n)
{ int m,e;
int i=0,j=n-1;
cout<<”enter the element to be searched”;
cin>>e;
while(i<=j)
{
m=(i+j)/2;
if(a[m]==e)
return m;
else if (a[m]<e)
i=m+1;
else
j=m-1;}
A dichotomizing search in which the set of items to be searched is divided at each
step into two equal, or nearly equal, parts, Also known as binary chop. The most efficient
method used for searching a sequential table is binary search. It doesn’t need any primary or
secondary index.
154
0 1 2 3 4 5 6
Following steps are generated if we binary search a data =45 from the above array
Step 1: LB UB
9 10 25 30 40 45 70
0 1 2 3 4 5 6
LB=0; UB=6 Mid=(0+6)/2 = 3 A[3] = 30
Step 2:
Since A[3] < ITEM ie., 30 <45 reinitalise LB, UB and mid
LB UB
9 10 25 30 40 45 70
0 1 2 3 4 5 6
LB=3; UB=6 Mid=(3+6)/2 = 4 A[3] = 40
Step3:
Since A[4] < ITEM ie., 40 <45 reinitalise LB, UB and mid
LB UB
155
9 10 25 30 40 45 70
0 1 2 3 4 5 6
LB=4; UB=6 Mid=(4+6)/2 = 5 A[5] = 45
Step 4:
Since A[5] == ITEM 45 = 45 , search is successful.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
156
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is present in location %d\n.",mid+1);
getch();
}
Output:
Enter the size of an array
5
Enter the elements in ascending order
12
13
16
20
32
Enter the number to search
20
The number is present in location 4
MERGE SORT
157
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
The following diagram shows the complete merge sort process for an example array
{38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the
array is recursively divided in two halves till the size becomes 1. Once the size becomes
1, the merge processes comes into action and starts merging arrays back till the complete
array is merged.
Routine
void mergesort( int a[],int l,int r)
{
158
if(l<r)
{
c=(l+r)/2;
mergesort(a,i,c);
mergesort(a,c+1,r);
mergesort(a,i,c+1,r);
}
}
void merge(int a[],int l,int r,int rend)
{
int temp[20];
int lend=r-1;
int t=l;
int noe=rend-l+1;
while(l<=lend && r<=rend)
{
if(a[l]<=a[r])
temp[t++]=a[l++];
else
temp[t++]=a[r++];
}
while(l<=lend)
temp[t++]=a[l++];
while(r<=rend)
temp[t++]=a[r++];
for(int i=0;i<noe;i++;rend--)
a[rend]=temp[rend];
}
159
PART – C
EXAMPLE PROGRAMS
The input should be sorted. The search in the list can be made faster by using “divide
and conquer” technique.It has the following characteristics:
• The input list must be sorted
• It is faster as compared to linear search.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[100],n,i,beg,end,mid,item;
{
cout<<"Data is Not Found";
}
getch();
}
Example
7. Write an algorithm to sort a set of 'N' numbers using Radix sort. Trace the
algorithm for the following set of numbers.
88,11,22,44,66,99,32,67,54,10
Radix sort is a non-comparative integer sorting algorithm that sorts data with
integer keys bygrouping keys by the individual digits which share the same
significant position and value
Sort by the least significant digit first (counting sort)
Numbers with the same digit go to same bin
Reorder all the numbers: the numbers in bin 0 precede the numbers in bin
1, which precede the numbers in bin 2, and so on
Sort by the next least significant digit
Continue this process until the numbers have been sorted on all k digits
Given the input the array has to be sorted using radix sort
Code:
#include<stdio.h>
#include<conio.h>
radix_sort(int array[], int n);
void main()
{
int array[100],n,i;
clrscr();
printf("Enter the number of elements to be
sorted: "); scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nArray Before Radix Sort:"); //Array Before Radix Sort
161
div=1;
num=0;
large=arr[0];
162
0 10
1 11
2 22
3 32
4 44
5 54
6 66
7 67
8 88
9 99
It is already sorted. Therefore it is not necessary to go for the next significant digit.
163
A real time system is nothing but a dynamic system. OOP approach is very useful for
Real time system because code changing is very easy in OOP system and it leads
toward dynamic behaviour of OOP codes thus more suitable to real time system.
System modelling is another area where criteria for OOP approach is countable.
Representing a system is very easy in OOP approach because OOP codes are very
easy to understand and thus is preffered to represent a system in simpler form.
Hypertext and hypermedia is another area where OOP approach is spreading its legs.
Its ease of using OOP codes that makes it suitable for various media approaches.
CAM/CAE/CAD System : -
Computer has wide use of OOP approach. This is due to time saving in writing OOP
codes and dynamic behaviour of OOP codes.
164
Automation system is just a part or type of real time system. Embeded systems make
it easy to use OOP
In networking, the following are the applications of data structures
Stacks -
E.g., Conversion of recursive routines to non-recursion
Queues -Managing IDs
Linked lists are more common than arrays to maintain stacks or queues-
To have flexibility in the number of entries and for memory efficiency
Hashing
Used when order is not important but Lookup needs to be fast and it is used for
MAC table
Sorting-
E.g., to display list of users in a show command
E.g., to show the forwarding table used for switching
165
166
12. (a)Write a C++ code to construct classes of a person with name and age as public
properties,account details as private properties and percentage of mark as protected
property.Construct a class with sports details of person.Construct a class to rank person
based on the equal weightage to academic and sports details.Use inheritance
concept.(16)[Page No.66]
Or
(b) Explain class object to Base and Base to class object conversions using C++ with
suitable examples. [Page No.50]
13. (a)Write a C++ code to sum up all odd numbers in a single linked list.[Page No.102]
Or
(b)Write a C++ code to perform addition of two polynomials using linked list form of
queue. [Page No.74]
14. (a)Explain BFS and DFS with suitable example. [Page No.118]
Or
(b)Write a c++ code for the implementation of different types of tree traversals.State the
tree applications. [Page No.114]
15. (a)Write a C++ code to implement quick sort with suitable examples.Write C++ code to
implement linear search with suitable examples. [Page No.147,154]
Or
(b)Write a C++ code to implement merge sort with suitable examples.Write C++ code to
implement binary search with suitable examples. [Page No.159,156]
.
167
ThirdSemester
Electronics and Communication Engineering
EC6301 – OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
(Regulation 2013)
Time : Three Hours Maximum : 100 marks
Answer ALL Questions
PART A – (10 x 2 = 20 marks)
1. What is a reference variable? [Page No.9]
2. What is a friend function? [Page No.9]
3. What is overriding? [Page No.33]
4. Why there is need for operator overloading? [Page No.34]
5. What is abstract data type? [Page No.71]
6. Write short notes on queue.[Page No.71]
7. What is a tree? [Page No.110]
8. How a graph is represented? [Page No.85]
9. What is meant by sorting? [Page No.143]
10. What is time complexity?[Page No.143]
PART B – (5 x 16 = 80 marks)
11. (a) Describe the major components of object oriented programming with
illustrations.(16) [Page No.30]
Or
(b)What is the purpose of constructor and destructor? Explain with suitable example
the different types of constructors in C++.(16)[Page No.33]
12. (a) What is inheritance? Discuss in detail about the various types of inheritances in
c++ with suitable examples. (16) [Page No.57]
Or
(b) What is virtual function? Explain with an example how latebinding is achieved
using virtual function.(16) [Page No.52]
168
13. (a) Write a set of routines for implementing two stacks within a single array.
[Page No.86]
Or
(b) Write a set of routines for implementing queue using linked Lists. (16)
[Page No.90]
14. (a) Discuss the different methods traversing a binary tree with algorithm. (16)
[Page No.114]
Or
(b) Illustrate the depth First Search algorithm with a graph and explain.(16)
[Page No.118]
15. (a) Discuss the Quick sort algorithm and apply the same for the following
numbers:90,77,60,99,55,88,66 (16) [Page No.147]
Or
(b) Explain in detail about linear search algorithm with an example.(16)
[Page No.154]
169
12. (a)(i) Explain base and derived classes with examples.(8) [Page No.45]
(ii) Write a program to illustrate how constructors are implemented when the classes
are inherited? (8) [Page No.70]
Or
170
(b) (i) Give an account on virtual functions with an example(8) [Page No.41]
(ii) Write a note on “this” pointer with an example. (8) [Page No.44]
14.(a) (i) How can you construct an expression tree?Describe your answer with an
example.(8) [Page No.127]
(ii) Discuss how sets are represented?(4) [Page No.131]
(iii) Explain union find operations. (4) [Page No.133]
Or
(b)Describe in detail about breadth-first search and depth-first search in a graph.
[Page No.118]
171
172
14. a) Discuss the graph traversals with suitable algorithms and examples. (13)
Or
b) Explain the algorithm for union and find operations in disjoint sets. (13)
15. a) Explain the algorithm of quick sort by sorting ther following set of numbers as an
example: 42 47 52 57 62 37 32 27 22
Or
b) Write the algorithm to perform binary search on an array and demonstrate with an
example.
PART C – (1 * 15 = 15 Marks)
16. a) Implement the ATM transaction in C++. (15)
Or
b) Define an abstract class called employee. Derive two classes called hourly
employee and salaried employee. Hourly employee has number of hours (integer),
and wage per hour (float).
Salaried Employee has salary of type float. Calculate salary() in an abstract function
in class employee which inherited by derived classes. Write a main program to create
objects of all classes and calculate salary of each object. (15)
173
PART B – (5 x 13 = 65 Marks)
11. a) i) What is function overloading? Explain with example, why it is important? (6)
ii) Write a program in C++ using friend function to find the product of two
complex numbers. (7)
Or
b) i) What is a container? Explain the types of sequence containers with examples.(7)
ii) Write a program in C++ to demonstrate the addition of two complex numbers by
overloading + operator. (6)
174
13. a) i) Represent two polynomials using singly linked lists and develop procedures to
add them. (6)
ii) Develop algorithms to perform insertion, deletion and search operations in a
queue implemented using singly linked lists. (7)
Or
b) Develop procedures to perform push and pop operation on an array
implementation of statch and use the same to evaluate a postfix expression
1 2 3 * - 4 +. (13)
14. a) i) How can binary trees be represented using arrays? Write routines to perform
insertion and deletion in a tree. (7)
ii) Write routines to convert a set as a tree and perform find operation on the
elements. Illustrate with examples. (6)
Or
b) With necessary algorithms, explain the two graph traversal methods. Demonstrate
with examples. (13)
15. a) Write a recursive algorithm for quick sort and apply the same to sort the elements
12, 3, 2, 26, 5, 21, 18, 25 and 50 and trace the output. (13)
Or
b) i) Sort the elements 12, 3, 2, 26, 5, 21, 18, 25 and 50 using merge sort and trace
the output. (6)
175
176