Download 17484 - SK Engineering Academy

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Lattice model (finance) wikipedia , lookup

Quadtree wikipedia , lookup

B-tree wikipedia , lookup

Interval tree wikipedia , lookup

Linked list wikipedia , lookup

Binary tree wikipedia , lookup

Binary search tree wikipedia , lookup

Transcript
EC2202 -DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
LTPC 3003
UNIT – I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING
9
Introduction- Tokens-Expressions-contour Structures –Functions in C++, classes and objects, constructors
and destructors ,operators overloading and type conversions .
UNIT – II ADVANCED OBJECT ORIENTED PROGRAMMING
9
Inheritance, Extending classes, Pointers, Virtual functions and polymorphism, File Handling Templates
,Exception handling, Manipulating strings.
UNIT – III DATA STRUCTURES & ALGORITHMS
9
Algorithm, Analysis, Lists, Stacks and queues, Priority queues-Binary Heap-Application, Heaps–hashinghash tables without linked lists
UNIT – IV NONLINEAR DATA STRUCTURES
9
Trees-Binary trees, search tree ADT, AVL trees, Graph Algorithms-Topological sort, shortest path
algorithm network flow problems-minimum spanning tree - Introduction to NP - completeness.
UNIT – V SORTING AND SEARCHING
9
Sorting – Insertion sort, Shell sort, Heap sort, Merge sort, Quick sort, Indirect sorting, Bucket sort,
Introduction to Algorithm Design Techniques –Greedy algorithm (Minimum Spanning Tree), Divide and
Conquer (Merge Sort), Dynamic Programming (All pairs Shortest Path Problem).
TOTAL HOURS = 45
TEXT BOOKS:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, 3rd ed, Pearson Education
Asia, 2007.
2. E. Balagurusamy, “ Object Oriented Programming with C++”, McGraw Hill Company Ltd., 2007.
REFERENCES:
1. Michael T. Goodrich, “Data Structures and Algorithm Analysis in C++”, Wiley student edition, 2007.
2. Sahni, “Data Structures Using C++”, The McGraw-Hill, 2006.
3. Seymour, “Data Structures”, The McGraw-Hill, 2007.
4. Jean – Paul Tremblay & Paul G.Sorenson, An Introduction to data structures with applications, Tata
McGraw Hill edition, II Edition, 2002.
5. John R.Hubbard, Schaum’s outline of theory and problem of data structure with C++, McGraw-Hill,
New Delhi, 2000.
6. Bjarne Stroustrup, The C++ Programming Language, Addison Wesley, 2000
7. Robert Lafore, Object oriented programming in C++, Galgotia Publication
UNIT I
PART – A
1. What is an identifier?
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.
2. What is a keyword?
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.,
3. Define constant in c++.
Constants in c++ refers to fixed values that do not change during execution of a program.
4. Define a variable.
A quantity ,Which may vary during execution of a program is called as a variable.
5. What are unary operators?
The operators that act upon a single operand are called as unary operators. The unary operators used in
c++ are - , ++, -- and sizeof operators.
6. What are binary operators?
The operators that act upon two operands are called binary operators. The binary operators used in c++
are +, -, *, / , %, =. etc.,
7. What are ternary operators?
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.
8. What is meant by an expression?
An expression is a combination of constant, variable, operators and function calls written in any form as
per the syntax of the c++ language.
9. State the difference between c and c++.
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 any where
the start of a c program in a c++ program.
(v) We can call a main() function, within This is not allowed
a program.
10. List the various oops concepts
Four main OOP concepts
Abstraction
creation of well-defined interface for an object, separate from its implementation
e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how
an object is implemented
Encapsulation
keeping implementation details “private” i.e., inside the implementation hierarchy an object is defined in
terms of other objects Composition => larger objects out of smaller ones
Inheritance => properties of smaller objects are “inherited” by larger
objects
Polymorphism
use code “transparently” for all types of same class of object
i.e., “morph” one object into another object within same hierarchy
11. Define class and object
Class: It is defined as blueprint or it is a collection of objects
Objects: is an instance of a class
Almost like struct, the default privacy specification is private whereas with struct, the default privacy
specification is public
Example:
class point
{
double x, y; // implicitly private
public:
void print();
void set( double u, double v );
};
12. Define inheritance
Inheritance
• Objects are often defined in terms of hierarchical classes with a base class and one or more levels of
classes that inherit from the classes that are above it in the hierarchy.
• For instance, graphics objects might be defined as follows:
Syntax for Inheritance
class derivedClass : public baseClass {
private :
// Declarations of additional members, if needed.
public:
// Declarations of additional members, if needed.
protected:
// Declarations of additional members, if needed.
}
13. Define encapsulation
Encapsulation is one of thr most important features of a class.It is the process os combining member
functions and the data it manipulates by logically binding the data ane keeping them safe from outside
interference.
14. Define abstraction.
Creation of well-defined interface for an object, separate from its implementation
e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how
an object is implemented
15. Define polymorphism
Polymorphism means “having many forms”. It allows different objects to respond to the same message in
different ways, the response specific to the type of the object.
E.g. the message displayDetails() of the Person class should give different results when send to a Student
object (e.g. the enrolment number).
16. List out the benefits of oops.
• 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
17. List out the application of oops.
• Client server computing
• Simulation such as flight simulations.
• Object-oriented database applications.
• Artificial intelligence and expert system
• Computer aided design and manufacturing systems.
18. Define data hiding.
The purpose of the exception handling mechanism is to provide a means to detect and report an
“exceptional circumstance” so that appropriate action can be taken.
19. What is the use of scope resolution operator?
In C, the global version of the variable cannot be accessed from within the inner block. C++ resolves this
problem by introducing a new operator :: called the scope resolution operator. It is used to uncover a
hidden variable.
Syntax:
:: variable name
20. When will you make a function inline?
When the function definition is small, we can make that function an inline function and we can mainly go
for inline function to eliminate the cost of calls to small functions.
21. What is overloading?
Overloading refers to the use of the same thing for different purposes.
There are 2 types of overloading:
• Function overloading
• Operator overloading
22. What is the difference between normal function and a recursive function?
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
23. What are objects? How are they created?
Objects are basic run-time entities in an object-oriented programming system. The class variables are
known as objects. Objects are created by using the syntax:
classname obj1,obj2,…,objn;
(or) during definition of the class:
class classname
{
------}obj1,obj2,…,objn;
24. List some of the special properties of constructor function.
• They should be declared in the public section.
• They are invoked automatically when the objects are created.
• They do not have return types, not even void and cannot return values.
• Constructors cannot be virtual.
Like other C++ functions, they can have default arguments
25. Describe the importance of destructor.
A destructor destroys the objects that have been created by a constructor upon exit from the program or
block to release memory space for future use. It is a member function whose name is the same as the class
name but is preceded by a tilde.
Syntax:
~classname(){ }
26. What do you mean by friend functions?
C++ allows some common functions to be made friendly with any number of classes, thereby allowing
the function to have access to the private data of thse classes. Such a function need not be a member of
any of these classes. Such common functions are called friend functions.
27. What are member functions?
Functions that are declared within the class definition are referred as member function.
28. Define dynamic binding.
Dynamic binding means that the code associated with a given procedure call is not known until the time
of the call at run-time.
PART B
PART B
1.Explain the basic concepts of object oriented programming in detail with example.
Objects: Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one instance of a
class. Each instance of a class can hold its own relevant data.
An Object is a collection of data members and associated member functions also known as methods.
Classes: Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represents a set of individual objects.
Characteristics of an object are represented in a class as Properties. The actions that can be performed by
objects become functions of the class and are referred to as Methods. For example consider we have a
Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context
each Car Object will have its own, Model, Year of Manufacture, Color, Top Speed, Engine Power etc.,
which form Properties of the Car class and the associated actions i.e., object functions like Start, Move,
and Stop form the Methods of Car Class.No memory is allocated when a class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class is created.
Inheritance: Inheritance is the process of forming a new class from an existing class or base class. The
base class is also known as parent class or super class. The new class that is formed is called derived
class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall
code size of the program, which is an important concept in object-oriented programming.
Data Abstraction: Data Abstraction increases the power of programming language by creating user
defined data types. Data Abstraction also represents the needed information in the program without
presenting the details.
Data Encapsulation:
Data Encapsulation combines data and functions into a single unit called Class. When using Data
Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the
class. Data Encapsulation enables the important concept of data hiding possible.
Polymorphism: Polymorphism allows routines to use variables of different types at different times. An
operator or function can be given different meanings or functions. Polymorphism refers to a single
function or multi-functioning operator performing in different ways.
Dynamic Binding : Binding refers to the linking of procedure call to the code to be executed in response
to the call. Dynamic Binding or Late Binding means that the code associated with a given procedure call
is known only at the run-time.
Message Passing : Objects communicate between each other by sending and receiving information
known as messages. A message to an object is a request for execution of a procedure. Message passing
involves specifying the name of the object, the name of the function and the information to be sent.
2.Explain inline functions in detail using examples.
An inline function is a function that is expanded in line when it is invoked. The compiler
Replaces the function call with corresponding function code. The inline funcitions are defined
As follows:
inline function-header
{
Function body;
}
Example:
inline double cube(double a)
{
Return(a*a*a);
}
Some situations where inline expansion may not work are:
 For functions returning values, if a loop , a switch, or a goto exists.
 For functions not returning values, if a return statement exists.
 If functions contain static variables.
 If inline functions are recursive.
-Example program to illustrate inline functions :
#include <iostream.h>
inline float mul(float x, float y)
{ return(x*y);
}
inline double div(double p, double q)
{ return(p/q) ;
}
int main( )
{
float a=1.2 ;
float b=2.3;
cout<< mul(a,b)<<”\n”;
cout<< div(a,b)<<”\n”;
return 0;
}
3.Define function overloading.write a program to illustrate in detail using examples.
A single function name can be used to perform different types of tasks. The same function name can
be used to handle different number and different types of arguments. This is known as function
overloading or function polymorphism.
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
void swap(float &p,float &q)
{
float t;
t=p;
p=q;
q=t;
}
void swap(char &c1,char &c2)
{
char t;
t=c1;
c1=c2;
c2=t;
}
void main()
{
int i,j;
float a,b;
char s1,s2;
clrscr();
cout<<"\n Enter two integers : \n";
cout<<" i = ";
cin>>i;
cout<<"\n j = ";
cin>>j;
swap(i,j);
cout<<"\n Enter two float numbers : \n";
cout<<" a = ";
cin>>a;
cout<<"\n b = ";
cin>>b;
swap(a,b);
cout<<"\n Enter two Characters : \n";
cout<<" s1 = ";
cin>>s1;
cout<<"\n s2 = ";
cin>>s2;
swap(s1,s2);
cout<<"\n After Swapping \n";
cout<<" \n Integers i = "<<i<<"\t j = "<<j;
cout<<" \n Float Numbers a= "<<a<<"\t b = "<<b;
cout<<" \n Characters s1 = "<<s1<<"\t s2 = "<<s2;
getch();
}
4.Explain constructor and Destructor using an example program.
Constructor function gets invoked when an object of a class is constructed (declared) and destructor
function gets invoked when the object is destructed (goes out of scope).
Use of Constructor and Destructor function of a class.Constructor function is used to initialize
member variables to pre-defined values as soon as an object of a class is declared.Constructor
function having parameters is used to initialize the data members to the values passed values, upon
declarationGenerally, the destructor function is needed only when constructor has allocated dynamic
memory.
Example : constructor
class myclass
{ private: int a; int b;
public:
myclass()
{
//here constructor function is used to
//initialize data members to pre-def
//values
a=10;
b=10;
}
int add(void)
{
return a+b;
}
};
void main(void)
{
myclass a;
cout<<a.add();
}
Example Destructor
//Example Program in C++
#include<iostream.h>
class myclass
{
public:
~myclass()
{
cout<<"destructed\n";
}
};
void main(void)
{
myclass obj;
cout<<"inside main\n";
}
5.Write a C++ program to multiply two matrices and print the result.
#include<iostream.h>
Class matrix
{
Private: int a[3][3];
Public: void getmatrix(int r, int c);
void printmatrix(int r, int c);
void mul(matrix,matrix);
};
Void matrix::getmatrix(int r, int c)
{
int I,j;
cout<<”Enter matrix elements”;
For( i=0;i<r;i++)
For(j=0;j<c;j++)
Cin>>a[i][j];
}
Void matrix::printmatrix(int r, int c)
{
Int I,j;
For(i=0;i<r;i++)
{
For(j=0;j<c;j++)
{
Cout<<” “<<a[i][j];
}
Cout<<”\n”;
}
}
Void matrix::mul(matrix A, matrix B)
{
Matrix C;
Int I,j,k;
r1=A.r; c1=A.c;
r2=B.r; c2=B.c;
For(i=0;i<r1;i++)
{
For(j=0;j<c1;j++)
{
C.a[i][j]=0;
For(k=0;k<c2;k++)
{
c.a[i][j]=C.a[i][j]+A.a[i][k]*B.a[k][j];
}
}
}
Void main()
{
Matrix A[3][3],B[3][3],C[3][3];
Int r1,r2,c1,c2;
Cout<<”enter order of 2 matrices”;
Cin>>r1>>c1>>r2>>c2;
Try
{
If(r2==c1)
{
A.readmatrix(r1,c1);
B.readmatrix(r2,c2);
C=mul(A,B);
A.printmatrix(r1,c1);
B.printmatrix(r2,c2);
C.printmatrix(r1,c2);
Exit(0);
}
else
{ throw (c2);
}
}
Catch(int x)
{
Cout<<”Invalid matrix order”;
}
}
}
6.Explain operator overloading:
The process of making an operator to exhibit different behaviors at different instances.
• Only existing operators can be overloaded.
• We cannot change the basic meaning of an operator.
• The overloaded operator must have at least one operand.
• Overloaded operators follow the syntax rules of the original operators.
-General form of operator function is:
Return type classname :: operator (op-arglist)
{
Function body
}
Overloaded operator functions can be invoked by expression
x op y for binary operators
In the following program overloaded function is invoked when the expression c1+c2 is encountered. This
expression is the same as operator op(x,y) (ie) operator +(c1,c2)
using friend function
#include<iostream.h>
#include<conio.h>
class complex
{
private:
float real;
float img;
public:
complex()
{
real=0.0;
img=0.0;
}
complex(float a,float b)
{
real=a;
img=b;
}
friend complex operator +(complex,complex);
void display()
{
cout<<"\n"<<real<<"+-i"<<img<<"\n";
}
};
complex operator +(complex c1,complex c2)
{
complex t;
t.real=c1.real+c2.real;
t.img=c1.img+c2.img;
return(t);
}
void main()
{
clrscr();
complex c1(5.5,2.5);
complex c2(1.5,5.5);
complex c3;
c3=c1+c2;
c1.display();
c2.display();
c3.display();
getch();
}
UNIT-II
PART-A
1.What are the c++ operators that cannot be overloaded?
Size operator (sizeof)
Scope resolution operator (::)
member access operators(. , .*)
Conditional operator (?:)
2. What is a virtual base class?
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.
3. What is the difference between base class and derived class?
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.
4. What are the rules governing the declaration of a class of multiple inheritance?
• 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
5. Mention the types of inheritance.
1.Single inheritance.
2. Multiple inheritance.
3. Hierarchical inheritance.
4. Multilevel inheritance.
5. Hybrid inheritance.
6. Define dynamic binding.
Dynamic binding means that the code associated with a given procedure call is not known until the time
of the call at run-time.
7. What do u mean by pure virtual functions?
A pure virtual function is a function declared in a base class that has no definition relative to the base
class. In such cases, the compiler requires each derived class to either define the function or redeclare it as
a pure virtual function. A class containing pure virtual functions cannot be used to declare any objects of
its own.
8. What are templates?
Templates enable us to define generic classes. A template can be considered as a kind of macro. When an
object of a specific type is defined for actual use, the template definition for that class is substituted with
the required data type. Since a template is defined with a parameter that would be replaced by the specific
data type at the time of actual use of the class or function, the templates are sometimes called
parameterized classes or functions
9. What is exception handling?
The purpose of the exception handling mechanism is to provide a means to detect and report an
“exceptional circumstance” so that appropriate action can be taken.
10. Give the general format of class template.
The general format of a class template is:
template
class classname
{
//………
//class member specification
//with anonymous type T
//wherever appropriate
//………
};.
11. List the kinds of exception.
Exceptions are of two kinds namely
• Synchronous exceptions
• Asynchronous exceptions
12. What are the errors in synchronous type exceptions?
Errors such as “out-of-range index” and “over-flow” belong to the synchronous type exceptions.
13. What are the errors in asynchronous type exceptions?
The errors that ware caused by errors beyond the control of the program (such as keyboard interrupts) are
called asynchronous exceptions.
14. What are the tasks that are performed by the error handling mechanism?
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).
15. Mention the key words used in exception handling.
The keywords used in exception handling are
• throw
• try
• catch
16. List the ios format function.
The ios format functions are as follows:
• width()
• precision()
• fill()
• setf()
• unsetf()
17. List the manipulators.
The manipulators are:
• setw()
• setprecision()
• setfill()
• setiosflags()
• resetiosflags()
18. Mention the equicalent ios function for manipulators.
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”
19. Define fill functions.
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”;
will produce the following output:
20 .Give the syntax of exception handling mechanism.
The syntax of exception handling mechanism is as follows:
try
{
--------------------throw exception
--------------------}
catch(type arguments)
{
----------------------------------------}
------------------------------------------PART – B
1.Explain Difference types of inheritances with suitable c++ coding.
Inheritance is the process by which objects of one class acquire the properties of objects of another
class. It supports the concept of hierarchical classification and provides the idea of reusability. The
class which is inherited is known as the base or super class and class which is newly derived is known
as the derived or sub class.
The syntax of deriving a new class from an already existing class is given by,
class derived-class : visibility-mode base-class
{
body of derived class
}
The various types of inheritance are,
• Single inheritance : In single inheritance, one class is derived from an already existing base class.
• Multi-level inheritance : In multi-level inheritance, a new class is derived from a class already
derived from the base class.
• Multiple inheritance : In multiple inheritance, a single class is derived from more than one base
class.
• Hierarchical inheritance : In hierarchical inheritance, more than one class is derived from a single
base class.
• Hybrid inheritance : Hybrid inheritance is defined as a combination of more than one inheritance.
Example :
MULTIPLE INHERITANCE
#include<iostream.h>
#include<conio.h>
class add
{
protected:
int val;
public:
void sum(int a,int b)
{
val=a+b;
}
};
class sub
{
protected:
int res;
public:
void minus(int a,int b)
{
res=a-b;
}
};
class mul:public add,public sub
{
private:
int prod;
public:
void display()
{
cout<<"\n OUTPUT";
cout<<"\n~~~~~~~~";
cout<<"\n\n Added Value = "<<val;
cout<<"\n\n Subtracted Value = "<<res;
prod=val*res;
cout<<"\n\n Product = "<<prod;
}
};
void main()
{
clrscr();
int x,y;
mul s;
cout<<"\n Enter 2 numbers : \n";
cin>>x>>y;
s.sum(x,y);
s.minus(x,y);
s.display();
getch();
}
2. Explain virtual functions.(Run time polymorphism) (April/May 2011)
The two types of polymorphism are,
• Compile time polymorphism – The compiler selects the appropriate function for a particular call
at the compile time itself. It can be achieved by function overloading and operator overloading.
• Run time Polymorphism - The compiler selects the appropriate function for a particular call at the
run time only. It can be achieved using virtual functions
Program to implement runtime polymorphism:
include<iostream.h>
#include<conio.h>
template<class T>
T sqr(T & n)
{
return(n*n);
}
void main()
{
int a;
float b;
double c;
clrscr();
cout<<"\n\n Enter an Integer : ";
cin>>a;
cout<<"\n Square of a = "<<sqr(a)<<endl;
cout<<"\n\n Enter a Float Value : ";
cin>>b;
cout<<"\n Square of b = "<<sqr(b)<<endl;
cout<<"\n\n Enter a Double Value : ";
cin>>c;
cout<<"\n Square of c = "<<sqr(c);
getch();
}
3. Explain File Handling in C++.(Nov/Dec 2010) (April/May 2011)
Files are required to save our data for future use, as Ram is not able to hold our data permanently.
Files
Data Files
Program Files
Text Files
Binary Files
The Language like C/C++ treat every thing as a file , these languages treat keyboard , mouse, printer,
Hard disk , Floppy disk and all other hardware as a file.
The Basic operation on text/binary files are : Reading/writing ,reading and manipulation of data stored on
these files. Both types of files needs to be open and close.
How to open File
Using member function Open( )
Using Constructor
Syntax
Syntax
Filestream object;
Filestream
object(“filename”,mode);
Object.open(“filename”,mode);
Example
Example
ifstream fin;
fin.open(“abc.txt”)
ifstream
fin(“abc.txt”);
 Mode are optional and given at the end .
 Filename must follow the convention of 8.3 and it’s extension can be anyone
How to close file
All types of files can be closed using close( ) member function
Syntax
fileobject.close( );
Example
Program
fin.close( );
Program
// here fin is an object of istream class
ABC.txt file contents
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("abc.txt");
fout<<"This is my first program in file handling";
fout<<"\n Hello again";
fout.close();
return 0;
}
This is my first program in file handling
Hello again
include<fstream>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
char str[80];
fin.open("abc.txt");
fin>>str; // read only first //string from file
cout<<"\n From File :"<<str; // as
//spaces is
treated as termination point
getch();
return 0;
}
NOTE : To overcome this problem use
fin.getline(str,79);
Detecting END OF FILE
Using EOF( ) member function
Using filestream object
Syntax
Example
Filestream_object.eof( );
Example
// detecting end of file
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
char ch;
ifstream fin;
fin.open("abc.txt");
while(fin) // file object
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
char ch;
ifstream fin;
fin.open("abc.txt");
while(!fin.eof()) // using eof() function
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;}
Example : To read the contents of a text file and display them on the screen.
Program ( using getline member
function)
Program ( using get( ) member function)
#include<fstream>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
char str[100];
ifstream fin;
fin.open("c:\\abc.txt");
while(!fin.eof())
{
fin.getline(str,99);
cout<<str;
}
fin.close();
getch();
return 0;
}
#include<fstream>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
char ch;
ifstream fin;
fin.open("file6.cpp");
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
4. Explain about Exception handling in C++.(Nov/Dec 2010)
Exceptions are run time anomalies. They include conditions like division by zero or access
to an array outside to its bound etc.
Types: Synchronous exception
Asynchronous exception.




Find the problem ( Hit the exception )
Inform that an error has occurred. (Throw exception)
Receive error information (Catch exception)
Take corrective action (Handle exception)
C++ exception handling mechanism is basically 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 defined by the keyword catch catches the
 try block throwing an exception
 invoking function that generates exception
 throwing mechanism
 catching mechanism
 multiple catch statements
 catch all exceptions
 Rethrowing an exception
General form
try
{
…..
throw exception;
…….
}
Catch ( type arg)
{
……
}
Exceptions that has to be caught when functions are used- The form is as follows:
Type function (arg list)
{
……
Throw (object)
…..
}
try
{
…..
Invoke function here;
…….
}
Catch ( type arg)
{
Handles exception here
}
Multiple catch statements:
try
{
…..
throw exception;
…….
}
Catch ( type arg)
{
……// catch block1
}
Catch ( type arg)
{
……//catch block2
}
Catch ( type arg)
{
……//catch block n
}
Generic exception handling is done using ellipse as follows:
Catch ( . . .)
{
……
}
5. Illustrate virtual function and pure virtual function with suitable example?
Virtual Function:
#include<iostream.h>
#include<conio.h>
class abc
{
protected :
int a,b;
public:
void take()
{
cout<<"\nEnter two 'int' values::";
cin>>a>>b;
}
virtual void display()=0;
};
class xyz:public abc
{
public:
void display()
{
cout<<"\nSum for 1st derived class="<
}
};
class mn:public abc
{
public:
void display()
{
cout<<"\nSum for 2nd derived class:"<
}
};
void main()
{
clrscr();
xyz ob;
mn ob1;
abc *ptr;
ptr=&ob;
cout<<"\nFor object of 1st derived class."<
ptr->take();
ptr->display();
cout<<"\nFor object of 2nd derived class."<
ptr=&ob1;
ptr->take();
ptr->display();
getch();
}
Pure Virtual Function:
A virtual function body is known as Pure Virtual Function. In above example we can see that the function is
base class never gets invoked. In such type of situations we can use pure virtual functions
Example : same example can re-written
class base
{
public:
virtual void show()=0; //pure virtual function
};
class derived1 : public base
{
public:
void show()
{
cout<<"\n Derived 1";
}
};
class derived2 : public base
{
public:
void show()
{
cout<<"\n Derived 2";
}
};
void main()
{
base *b; derived1 d1; derived2 d2;
b = &d1;
b->show();
b = &d2;
b->show();
}
6. What are abstract classes? Write a program having student as an abstract class and create
many derived classes such as engineering, science, medical etc., from the student class. Create
their object and process them.
A class with no object is called abstract class.
#include<iostream.h>
class student
{
Public:
Int regno;
char name[20];
};
class engineering:public student
{
char branch[20];
public:
void get()
{
cin>>regno>>name>>branch;
}
void put()
{
cout<<regno<<name<<branch;
};
class science:public student
{
char branch[20];
public:
void get()
{
cin>>regno>>name>>branch;
}
void put()
{
cout<<regno<<name<<branch;
};
class medical: public student
{
{
char branch[20];
public:
void get()
{
cin>>regno>>name>>branch;
}
void put()
{
cout<<regno<<name<<branch;
};
void main()
{
engineering e:
e.get();
e.put();
science s;
s.get();
s.put();
medical m;
m.get();
m.put();
}
.
UNIT-III
PART-A
1.Write down the definition of data structures?
A data structure is a mathematical or logical way of organizing data in the memory that consider not
only the items stored but also the relationship to each other and also it is characterized by accessing
functions.
2. Give few examples for data structures?
Stacks, Queue, Linked list, Trees, graphs
3. Define Algorithm?
Algorithm is a solution to a problem independent of programming language. It consist of set of finite
steps which, when carried out for a given set of inputs, produce the corresponding output and terminate
in a finite time.
4. What are the features of an efficient algorithm?
• Free of ambiguity
• Efficient in execution time
• Concise and compact
• Completeness
• Definiteness
• Finiteness
5. List down any four applications of data structures?
Compiler design
Operating System
Database Management system
Network analysis
6. What is meant by an abstract data type (ADT)?
An ADT is a set of operation. A useful tool for specifying the logical properties of a datatype is the
abstract data type.ADT refers to the basic mathematical concept that defines the datatype.
Eg.Objects such as list, set and graph along their operations can be viewed as ADT's.
7. What are the operations of ADT?
Union, Intersection, size, complement and find are the various operations of ADT.
8. What is meant by list ADT?
List ADT is a sequential storage structure. General list of the form a1, a2, a3.…., an and the size of the
list is 'n'. Any element in the list at the position I is defined to be ai, ai+1 the successor of ai and ai-1 is
the predecessor of ai.
9. What are the two parts of ADT?
• Value definition
• Operator definition
10. What is a Sequence?
A sequence is simply an ordered set of elements.A sequence S is sometimes written as the enumeration
of its elements,such as
S =If S contains n elements,then length of S is n.
11. Define len(S),first(S),last(S),nilseq ?
len(S) is the length of the sequence S.
first(S) returns the value of the first element of S
last(S) returns the value of the last element of S
nilseq :Sequence of length 0 is nilseq .ie., contains no element.
12. What are the two basic operations that access an array?
Extraction:
Extraction operation is a function that accepts an array, a ,an index,i,and
returns an element of the array.
Storing:
Storing operation accepts an array , a ,an index i , and an element x.
13. Define Structure?
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.
14. Define Union ?
Union is collection of Structures ,which permits a variable to be interpreted in several different ways.
15. Define Automatic and External variables?
Automatic variables are variables that are allocated storage when the function is invoked.
External variables are variables that are declared outside any function and are allocated storage at the
point at which they are first encountered for the remeinder of the program’s execution.
16. What is a Stack?
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.
17. What are the two operations of Stack?
• _ PUSH
• _ POP
18. What is a Queue?
A Queue is an ordered collection of items from which items may be deleted at
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).
19. What is a Priority Queue?
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.
20. 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.
21. What is a doubly linked list?
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.
22. Define double circularly linked list?
In a doubly linked list, if the last node or pointer of the list, point to the first element of the list,then it is a
circularly linked list.
23. What is a circular queue?
The queue, which wraps around upon reaching the end of the array is called as circular queue.
24. Define max and min heap?
A heap in which the parent has a larger key than the child's is called a max heap.
A heap in which the parent has a smaller key than the child is called a min heap.
PART – B
1. Explain with example the insertion & deletion in doubly linked list
Doubly Linked List
A Doubly linked list is a linked list in which each node has three fields namely data field, forward link
(FLINK) and Backward Link (BLINK). FLINK points to the successor node in the list whereas BLINK
points to the predecessor node.
STRUCTURE DECLARATION : Struct Node
{
int Element;
Struct Node *FLINK;
Struct Node *BLINK
};
ROUTINE TO INSERT AN ELEMENT IN A DOUBLY LINKED LIST
void Insert (int X, list L, position P)
{
Struct Node * Newnode;
Newnode = malloc (size of (Struct Node));
If (Newnode ! = NULL)
{
Newnode ->Element = X;
Newnode ->Flink = P Flink;
P ->Flink ->Blink = Newnode;
P ->Flink = Newnode ;
Newnode ->Blink = P;
}
}
ROUTINE TO DELETE AN ELEMENT
void Delete (int X, List L)
{
position P;
P = Find (X, L);
If ( IsLast (P, L))
{
Temp = P;
P ->Blink ->Flink = NULL;
free (Temp);
}
else
{
Temp = P;
P ->Blink ->Flink = P->Flink;
P ->Flink ->Blink = P->Blink;
free (Temp);
}
}
Advantage
* Deletion operation is easier.
* Finding the predecessor & Successor of a node is easier.
Disadvantage
* More Memory Space is required since it has two pointers.
2. Explain with example the insertion & deletion in singly linked list
Singly Linked List Implementation
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 singly linked list is a linked list in which each node contains only one link field pointing to the next
node in the list.
DECLARATION FOR LINKED LIST
Struct node ;
typedef struct Node *List ;
typedef struct Node *Position ;
int IsLast (List L) ;
int IsEmpty (List L) ;
position Find(int X, List L) ;
void Delete(int X, List L) ;
position FindPrevious(int X, List L) ;
position FindNext(int X, List L) ;
void Insert(int X, List L, Position P) ;
void DeleteList(List L) ;
Struct Node
{
int element ;
position Next ;
};
ROUTINE TO INSERT AN ELEMENT IN THE LIST
void Insert (int X, List L, Position P)
/* Insert after the position P*/
{
position Newnode;
Newnode = malloc (size of (Struct Node));
If (Newnode! = NULL)
{
Newnode ->Element = X;
Newnode ->Next = P->Next;
P ->Next = Newnode;
}
}
ROUTINE TO CHECK WHETHER THE LIST IS EMPTY
int IsEmpty (List L) /*Returns 1 if L is empty */
{
if (L ->Next = = NULL)
return (1);
}
ROUTINE TO CHECK WHETHER THE CURRENT POSITION IS LAST
int IsLast (position P, List L) /* Returns 1 is P is the last position in L */
{
if (P->Next = = NULL)
return(1);
}
FIND ROUTINE
position Find (int X, List L)
{
/*Returns the position of X in L; NULL if X is not found */
position P;
P = L ->Next;
while (P! = NULL && P->Element ! = X)
P = P->Next;
return P;
}
}
FIND PREVIOUS ROUTINE
position FindPrevious (int X, List L)
{
/* Returns the position of the predecessor */
position P;
P = L;
while (P ->Next ! = Null && P ->Next ->Element ! = X)
P = P ->Next;
return P;
}
FINDNEXT ROUTINE
position FindNext (int X, List L)
{
/*Returns the position of its successor */
P = L ->Next;
while (P->Next! = NULL && P->Element ! = X)
P = P->Next;
return P->Next;
}
ROUTINE TO DELETE AN ELEMENT FROM THE LIST
void Delete(int X, List L)
{
/* Delete the first occurence of X from the List */
position P, Temp;
P = Findprevious (X,L);
If (!IsLast(P,L))
{
Temp = P->Next;
P ->Next = Temp->Next;
Free (Temp);
}
}
ROUTINE TO DELETE THE LIST
void DeleteList (List L)
{
position P, Temp;
P = L ->Next;
L->Next = NULL;
while (P! = NULL)
{
Temp = P->Next
free (P);
P = Temp;
}
}
3. Explain with example the insertion & deletion in circularly linked list(Refer singly LL)
Circular Linked List
In circular linked list the pointer of the last node points to the first node. Circular linked list can be
implemented as Singly linked list and Doubly linked list with or without headers.
Singly Linked Circular List
A singly linked circular list is a linked list in which the last node of the list points to the first node.
Doubly Linked Circular List
A doubly linked circular list is a Doubly linked list in which the forward link of the last node points to the
first node and backward link of the first node points to the last node of the list.
Advantages of Circular Linked List
• It allows to traverse the list starting at any point.
• It allows quick access to the first and last records.
• Circularly doubly linked list allows to traverse the list in either
4. Write a procedure to insert &delete a element in the array implementation of stack
Stack Model :
A stack is a linear data structure which follows Last In First Out (LIFO) principle, in which both insertion
and deletion occur at only one end of the list called the Top.
Pile of coins., a stack of trays in cafeteria.
Operations On Stack
The fundamental operations performed on a stack are
1. Push
2. Pop
PUSH :
The process of inserting a new element to the top of the stack. For every push operation the top is
incremented by 1.
POP :
The process of deleting an element from the top of stack is called pop operation. After every pop
operation the top pointer is decremented by 1.
EXCEPTIONAL CONDITIONS
OverFlow
Attempt to insert an element when the stack is full is said to be overflow.
UnderFlow
Attempt to delete an element, when the stack is empty is said to be underflow.
Array Implementation of stack
In this implementation each stack is associated with a pop pointer, which is -1 for an empty stack.
• To push an element X onto 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.
void push (int x, Stack S)
{
if (IsFull (S))
Error ("Full Stack");
else
{
Top = Top + 1;
S[Top] = X;
}
}
int IsFull (Stack S)
{
if (Top = = Arraysize)
return (1);
}
ROUTINE TO POP AN ELEMENT FROM THE STACK
void pop (Stack S)
{
if (IsEmpty (S))
Error ("Empty Stack");
else
{
X = S [Top];
Top = Top - 1;
}
}
int IsEmpty (Stack S)
{
if (S 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;
}
5. Write a procedure to insert & delete a element in the linked list implementation of stack
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.
struct node
{
int data;
struct node *link;
};
struct node *cur,*first;
void create();
void push();
void pop();
void display();
void create()
{
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
}
void display()
{
cur=first;
printf("\n");
while(cur!=NULL)
{
printf("%d\n",cur->data);
cur=cur->link;
}
}
void push()
{
printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=first;
first=cur;
}
void pop()
{
if(first==NULL)
{
printf("\nSTACK IS EMPTY\n");
}
else
{
cur=first;
printf("\nDELETED ELEMENT IS %d\n",first->data);
first=first->link;
free(cur);
}
}
6. Write a procedure to insert & delete a element in the array implementation of queue
A Queue is a linear data structure which follows First In First Out (FIFO) principle, in which insertion is
performed at rear end and deletion is performed at front end.
Example : Waiting Line in Reservation Counter,
Operations on Queue
The fundamental operations performed on queue are
1. Enqueue
2. Dequeue
Enqueue :
The process of inserting an element in the queue.
Dequeue :
The process of deleting an element from the queue.
Exception Conditions
Overflow : Attempt to insert an element, when the queue is full is said to be overflow condition.
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 using arrays and pointers.
Array Implementation
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)
print (" Queue overflow");
else
{
Rear = Rear + 1;
Queue [Rear] = X;
}
}
ROUTINE FOR DEQUEUE
void delete ( )
{
if (Front < 0)
print (" Queue Underflow");
else
{
X = Queue [Front];
if (Front = = Rear)
{
Front = 0;
Rear = -1;
}
else
Front = Front + 1 ;
}
}
7. Write a procedure to insert & delete a element in the linked list implementation of queue
Linked List Implementation of Queue
Enqueue operation is performed at the end of the list.
Dequeue operation is performed at the front of the list.
void create()
{
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
}
void display()
{
cur=first;
printf("\n");
while(cur!=NULL)
{
printf("%d\n",cur->data);
cur=cur->link;
}
}
void push()
{
printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=first;
first=cur;
}
void pop()
{
if(first==NULL)
{
printf("\nSTACK IS EMPTY\n");
}
else
{
cur=first;
printf("\nDELETED ELEMENT IS %d\n",first->data);
first=first->link;
free(cur);
}
}
8. Write short notes on cursor implementation with example.
Cursor implementation is very useful where linked list concept has to be implemented without using
pointers.
Comparison on Pointer Implementation and Curson Implementation of Linked List.
Pointer Implementation Cursor Implementation
1. Data are stored in a collection of structures. Data are stored in a global array .Each structure contains a
data and next structures. Here array index is pointer. considered as an address.
Pointer Implementation Cursor Implementation
2. Malloc function is used to create a node and It maintains a list of free cells called free function is used
to released the cell. cursors space in which slot 0 is considered as a header and Next is equivalent to the
pointer which points to the next slot.
ROUTINE TO DELETE AN ELEMENT
void Delete (int X, List L)
{
position P, temp;
P = Findprevious (X, L);
if (! IsLast (P, L))
{
temp = CursorSpace [P].Next;
CursorSpace [P].Next = CursorSpace [temp].Next;
CursorFree (temp);
}
}
ROUTINE FOR INSERTION
void Insert (int X, List L, position P)
{
position newnode;
newnode = CursorAlloc ( );
if (newnode ! = 0)
CursorSpace [newnode].Element = X;
CursorSpace [newnode]. Next = CursorSpace [P].Next;
CursorSpace [P].Next = newnode;
}
9. Evaluate the following postfix expression
abcd+e*+f+* where a=3 b=2 c=5 d=6 e= 8 f=2
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.
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.
Ans=186
10. Write an algorithm for convert infix expression to postfix expression with an example of
(A+(B*C-(D/E^F)*G)*H).(16)(AUT NOV 2011)
Read the infix expression one character at a time until it encounters the delimiter. "#"
Step 1 : If the character is an operand, place it on to the output.
Step 2 : If the character is an operator, push it onto the stack. If the stack operator has a higher or
equal priority than input operator then pop that operator from the stack and place it onto the
output.
Step 3 : If the character is a left paraenthesis, push it onto the stack.
Step 4 : If the character is a right paraenthesis, pop all the operators from the stack till it
encounters left parenthesis, discard both the parenthesis in the output.
Postfix Expression:ABC*DEF^/G*-H*+
UNIT – IV
PART – A
1. Define non-linear data structure?
Data structure which is capable of expressing more complex relationship than that of physical adjacency
is called non-linear data structure.
2. Define tree?
A tree is a data structure, which represents hierarchical relationship between individual Data items.
3.Define child and parent of a tree.
The root of each subtree is said to be a child of ‘r’ and ‘r’ is the parent of each subtree root.
4. Define leaf?
In a directed tree any node which has out degree o is called a terminal node or a leaf.
5. What is a Binary tree?
A Binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets.
The first subset contains a single element called the root of the tree. The other two subsets are themselves
binary trees called the left and right sub trees.
6. What are the applications of binary tree?
Binary tree is used in data processing.
a. File index schemes
b. Hierarchical database management system
7. What is meant by traversing?
Traversing a tree means processing it in such a way, that each node is visited only once.
8. What are the different types of traversing?
The different types of traversing are
a.Pre-order traversal-yields prefix form of expression.
b. In-order traversal-yields infix form of expression.
c. Post-order traversal-yields postfix form of expression.
9. What are the two methods of binary tree implementation?
Two methods to implement a binary tree are,
a. Linear representation.
b. Linked representation
10. Define Graph?
A graph G consist of a nonempty set V which is a set of nodes of the graph, a set E which is the set of
edges of the graph, and a mapping from the set for edge E to a set of pairs of elements of V.
It can also be represented as G=(V, E).
11. Define adjacent nodes?
Any two nodes which are connected by an edge in a graph are called adjacent nodes. For Example, if and
edge xÎE is associated with a pair of nodes (u,v) where u, v Î V, then we say that the edge x connects the
nodes u and v.
12.Name the different ways of representing a graph?
a. Adjacency matrix
b. Adjacency list
13. What are the two traversal strategies used in traversing a graph?
a. Breadth first search
b. Depth first search
14. What is an acyclic graph?
A simple diagram which does not have any cycles is called an acyclic graph.
15. Give some example of NP complete problems.
Hamiltonian circuit.
Travelling salesmen problems
16.What are AVL trees?
An AVL tree is a binary search tree with a balancing condition.For every node in the tree the heigh of the
left and right subtrees can differ at most by 1.The height of an empty tree is defined to be -1.It ensures
that the depth of the tree is O(log N)
17.What is topological sort?
A topological sort is an ordering of vertices in a directed acyclic graph,such that if there is a path from v i
then vj appears after vi in the ordering.
18.What is single source shortest path problem?
Given as an input a weighted graph, G=(V,E) and a distinguished vertex,’s’ find the shortest weighted
path from ‘s’ to every other vertex in G.
19.Mention some shortest –path problems.
Unweighted shortest paths
Dijikstra’s algorithm
All-pairs shortest paths
20.What are the algorithms used to find the minimum spanning tree?
Prim’s algorithm
Kruskal’s algorithm
PART B
1. What is traversal? Give the algorithm for traversal in the binary tree
Tree Traversals
Traversing means visiting each node only once. Tree traversal is a method for visiting all the nodes in the
tree exactly once. There are three types of tree traversal techniques, namely
1. Inorder Traversal
2. Preorder Traversal
3. Postorder Traversal
Inorder Traversal
The inorder traversal of a binary tree is performed as
* Traverse the left subtree in inorder
* Visit the root
* Traverse the right subtree in inorder.
RECURSIVE ROUTINE FOR INORDER TRAVERSAL
void Inorder (Tree T)
{
if (T ! = NULL)
{
Inorder (T ->left);
printElement (T ->Element);
Inorder (T ->right);
}
}
Preorder Traversal
The preorder traversal of a binary tree is performed as follows,
* Visit the root
* Traverse the left subtree in preorder
* Traverse the right subtree in preorder.
RECURSIVE ROUTINE FOR PREORDER TRAVERSAL
void Preorder (Tree T)
{
if (T ! = NULL)
{
printElement (T ->Element);
Preorder (T ->left);
Preorder (T ->right);
}
Postorder Traversal
The postorder traversal of a binary tree is performed by the following steps.
* Traverse the left subtree in postorder.
* Traverse the right subtree in postorder.
* Visit the root.
RECURSIVE ROUTINE FOR POSTORDER TRAVERSAL
void Postorder (Tree T)
{
if (T ! = NULL)
{
Postorder (T ->Left);
Postorder (T ->Right);
PrintElement (T ->Element);
}
2. Write a program that reads an expression in its infix form and builds the binary tree
corresponding to that expression. Also write procedures to print the infix and postfix
forms of the expression, using in order and post order traversals of this tree.
Step 2: Read an expression.
Step 3: Scan the expression from left to right and repeat steps 4 to 7 for each character in the expression
till the delimiter.
Step 4: If the character is an operand, place it on to the output.
Step 5: If the character is an operator, then check the Stack operator has a higher or equal priority than the
input operator then pop that operator from the stack and place it onto the output. Repeat this till there is
no higher priority operator on the top of the Stack and push the input operator onto the Stack.
Step 6: If the character is a left parenthesis, push it onto the Stack.
Step 7: If the character is a right parenthesis, pop all the operators from the Stack till it encounters left
parenthesis. Discard both the parenthesis in the output.
Step 8: Terminate the execution.
RECURSIVE ROUTINE FOR INORDER TRAVERSAL
void Inorder (Tree T)
{
if (T ! = NULL)
{
Inorder (T ->left);
printElement (T ->Element);
Inorder (T ->right);
}
}
RECURSIVE ROUTINE FOR PREORDER TRAVERSAL
void Preorder (Tree T)
{
if (T ! = NULL)
{
printElement (T ->Element);
Preorder (T ->left);
Preorder (T ->right);
}
RECURSIVE ROUTINE FOR POSTORDER TRAVERSAL
void Postorder (Tree T)
{
if (T ! = NULL)
{
postorder (T ->Left);
postorder (T ->Right);
printElement (T ->Element);
}
#include<stdio.h>
#include<alloc.h>
#include<process.h>
#include<conio.h>
#define SIZE 20
char Expr[SIZE];
char Stack[SIZE];
int Top=-1;
void push(char ch);
void pop();
void infix_to_postfix();
int m,l;
void main()
{
char ch;
clrscr();
printf("Program to covert infix expression into postfix expression:\n");
printf("Enter your expression & to quit enter fullstop(.)\n");
while((ch=getc(stdin))!='\n')
{
Expr[m]=ch;
m++;
}
l=m;
infix_to_postfix();
getch();
}
void push(char ch)
{
if(Top+1 >= SIZE)
{
printf("\nStack is full");
}
else
{
Top=Top+1;
Stack[Top] = ch;
}
}
void pop()
{
if (Top < 0)
{
printf("\n Stack is empty");
}
else
{
if(Top >=0)
{
if(Stack[Top]!='(')
printf("%c",Stack[Top]);
Top=Top-1;
}
}
}
void infix_to_postfix()
{
m=0;
while(m<l)
{
switch(Expr[m])
{
case '+' :
case '-' :
while(Stack[Top] =='-' || Stack[Top] =='+' ||Stack[Top] =='*'
||Stack[Top] =='/' ||Stack[Top] =='^' && Stack[Top] !='(')
pop();
push(Expr[m]);
++m;
break;
case '/' :
case '*' :
while(Stack[Top] =='*' ||Stack[Top] =='/' ||Stack[Top] =='^' &&
Stack[Top] !='(')
pop();
push(Expr[m]);
++m;
break;
case '^':
push(Expr[m]);
++m;
break;
case '(':
push(Expr[m]);
++m;
break;
case ')':
while(Stack[Top]!='(')
pop();
pop();
++m;
break;
case '.' :
while (Top >= 0)
pop();
exit(0);
default :
if(isalpha(Expr[m]))
{
printf("%c",Expr[m]);
++m;
break;
}
else
{
printf("\n Some error");
exit(0);
}
}
}
}
3.Narrate the operations of Binary search tree on searching a node, Insertion node and
deletion node from binary tree with example.(16) (AUT NOV 2011)(Refer 3)
struct tree * find(struct tree *t, int element)
{
if(t==NULL)
return NULL;
if(element<t->data)
return(find(t->lchild,element));
else
if(element>t->data)
return(find(t->rchild,element));
else
return t;
}
struct tree *findmin(struct tree *t)
{
if(t==NULL)
return NULL;
else
if(t->lchild==NULL)
return t;
else
return(findmin(t->lchild));
}
struct tree *findmax(struct tree *t)
{
if(t!=NULL)
{
while(t->rchild!=NULL)
t=t->rchild;
}
return t;
}
4.What are AVL tree? Explain in detail the AVL rotations.
AVL Tree : - (Adelson - Velskill and LANDIS)
An AVL tree is a binary search tree except that for every node in the tree, the height of the left and right
subtrees can differ by atmost 1. The height of the empty tree is defined to be - 1.
A balance factor is the height of the left subtree minus height of the right subtree. For an AVL tree all
balance factor should be +1, 0, or -1. If the balance factor of any node in an AVL tree becomes less than 1 or greater than 1, the tree has to be balanced by making either single or double rotations.
An AVL tree causes imbalance, when any one of the following conditions occur.
Case 1 : An insertion into the left subtree of the left child of node .
Case 2 : An insertion into the right subtree of the left child of node .
Case 3 : An insertion into the left subtree of the right child of node .
Case 4 : An insertion into the right subtree of the right child of node .
These imbalances can be overcome by
1. Single Rotation
2. Double Rotation.
Single Rotation
Single Rotation is performed to fix case 1 and case 4.
Case 1. An insertion into the left subtree of the left child of K2.
Single Rotation to fix Case 1.
ROUTINE TO PERFORM SINGLE ROTATION WITH LEFT
SingleRotatewithLeft (Position K2)
{
Position K1;
K1 = K2 ->Left ;
K2 ->left = K1 ->Right ;
K1 ->Right = K2 ;
K2 ->Height = Max (Height (K2 ->Left), Height (K2-> Right)) + 1 ;
K1 ->Height = Max (Height (K1 ->left), Height (K1 ->Right)) + 1;
return K1 ;
}
Single Rotation to fix Case 4 :Case 4 : - An insertion into the right subtree of the right child of K1.
ROUTINE TO PERFORM SINGLE ROTATION WITH RIGHT :Single Rotation With Right (Position K2)
{
Position K2 ;
K2 = K1-> Right;
K1 ->Right = K2 ->Left ;
K2 ->Left = K1 ;
K2 ->Height = Max (Height (K2 ->Left), Height (K2 ->Right)) +1 ;
K1 ->Height = Max (Height (K1 ->Left), Height (K1 ->Right)) +1 ;
Return K2 ;
}
Single Rotation with left (K3)
Double Rotation
Double Rotation is performed to fix case 2 and case 3.
Case 2 :
An insertion into the right subtree of the left child.
ROUTINE TO PERFORM DOUBLE ROTATION WITH LEFT :
Double Rotate with left (Position K3)
{ /* Rotation Between K1 & K2 */
K3 ->Left = Single Rotate with Right (K3 ->Left);
/* Rotation Between K3 & K2 */
Return Single Rotate With Left (K3);
}
Case 4 :
An Insertion into the left subtree of the right child of K1.
ROUTINE TO PERFORM DOUBLE ROTATION WITH RIGHT :
Double Rotate with Right (Position K1)
{
/* Rotation Between K2 & K3 */
K1-> Right = Single Rotate With Left (K1-> Right);
/* Rotation Between K1 & K2 */
return Single Rotate With Right (K1);
5.Explain with algorithm how insertion and deletion is performed in a AVL tree. Explain how
the tree is balanced after the operation.(16)(AU NOV 2011)
INSERTION ROUTINE
struct avltree *insertion(struct avltree *t,int x)
{
if(t==NULL)
{
t=(struct avltree*)malloc(sizeof(struct avltree));
t->data=x;
t->left=t->right=NULL;
t->height=0;
}
else if(x<t->data)
{
t->left=insertion(t->left,x);
if((height(t->left)-height(t->right))==2)
{
if(x<t->left->data)
t=singlerotationwithleft(t);
else
t=doublerotationwithleft(t);
}
}
else if(x>t->data)
{
t->right=insertion(t->right,x);
if((height(t->right)-height(t->left)) ==2)
{
if(x>t->right->data)
t=singlerotationwithright(t);
else
t=doublerotationwithright(t);
}
}
t->height=max(height(t->left),height(t->right))+1;
return t;
}
DELETION ROUTINE
Deletion is same as binary search tree .After deleting the element we have to check the balance factor of
the tree .If it is un balanced ,do suitable rotations to make the tree balanced.
UNIT V
PART A
1. What is meant by sorting?
Ordering the data in an increasing or decreasing fashion according to some relationship among the data
item is called sorting.
2. What are the two main classifications of sorting based on the source of data?
a. Internal sorting
b. External sorting
3. What is meant by external sorting?
External sorting is a process of sorting in which large blocks of data stored in storage Devices are moved
to the main memory and then sorted.
4. What is meant by internal sorting?
Internal sorting is a process of sorting the data in the main memory.
5. What are the various factors to be considered in deciding a sorting algorithm?
a. Programming time
b. Execution time of the program
c. Memory needed for program environment
6. What is the main idea in Bubble sort?
The basic idea underlying the bubble sort is to pass through the file sequentially Several times. Each pass
consists of comparing each element in the file with its successor (x[i] and x[i+1] and interchanging the
two elements if they are not in proper order.
7. What is the basic idea of shell sort?
Instead of sorting the entire array at once, it is first divide the array into smaller
segments, which are then separately sorted using the insertion sort.
8. What is the purpose of quick sort?
The purpose of the quick sort is to move a data item in the correct direction, just
enough for to reach its final place in the array.
9. What is the advantage of quick sort?
Quick sort reduces unnecessary swaps and moves an item to a greater distance, in one move.
10. What is the average efficiency of heap sort?
The average efficiency of heap sort is 0 (n(log2 n)) where, n is the number of
elements sorted.
11. Define Algorithm.
An algorithm is clearly specified set of simple instructions to be followed to
solve a problem. The algorithm forms a base for program.
12. What is complexity analysis?
It is the analysis of the amount of memory and time an algorithm requires to
completion.
There are two types of Complexity
• Space Complexity
• Time Complexity
13. What is performance analysis of an algorithm?
The analysis of the performance of an algorithm based on specification is called
performance analysis. It is loosely divided into
a. Priori estimates
b. Posterior Testing
14. Define space complexity.
Space complexity of an algorithm is the amount of memory it needs to run to
completion.
15. Define time complexity.
Time complexity is the amount of computer time an algorithm requires to run
to completion.
16. What does asymptotic notation mean?
Asymptotic notations are terminology that is introduced to enable us to make meaningful statements
about the time and space complexity of an algorithm.
The different notations are
• Big – Oh notation
• Omega notation
• Theta notation.
17. Define best case of an algorithm.
It is the shortest time that an algorithm will use over all instances of size n for
a given problem to produce the result.
18. What is divide and conquer technique?
Divide and Conquer algorithm is based on dividing the problem to be solved
into several, smaller sub instances, solving them independently and then combining
the sub instances solutions so as to yield a solution for the original instance.
19. What is dynamic programming?
Dynamic programming algorithm is a general class of algorithms which solve
problems by solving smaller versions of the problem, saving the solutions to the
small problems and then combining them to solve the larger problems.
20. Define Greedy method.
The greedy method suggests that one can devise an algorithm that works in stages, considering one input
at a time. At each stage, a decision is made regarding whether a particular input is an optimal solution. An
example for solution using greedy method is ‘knapsack problem’.
21.List some algorithms uses Dynamic Progrmming.
Matrix-chain multiplication
Optimal Binary Search Tree
0-1knapsack problem
All-pairs Shortest Path
22.List some algorithms uses Greedy approach.
Dijikistra’s algorithms.,Prim’s algorithms. ,Kruskal’s algorithms.
23.What is ahellsort also called?
Shellsort is also called as diminishing increment sort.
24.What is the basic strategy of merge sort?
Mergesort is the technique which has sorted subarrays which are merged to form a single sorted array.
25.What are the techniques used to choose the pivot element for quicksort?
The various techniques are First element,Random pick Median of three portioning
26.How many pointers are used for quicksort?
Quicksort requires two scans one from left to right and another from right to left,so two pointers needed
for the scans.
27.How many pointers are used in mergesort?
Three pointers are used in mergesort. ‘Aptr for the first sorted subarray,’Bptr’ for the second sorted
subarray and ‘cptr’ for the merged sorted subarray
PART B
1. Define Heap Sort . Write the algorithm for heap sort procedures.
Heap Sort
Heap sort operates by first converting the list in to a heap tree. Heap tree is a binary tree in which each
node has a value greater than both its children (if any). It uses a process called "adjust to accomplish its
task (building a heap tree) whenever a value is larger than its parent. The time complexity of heap sort is
O(nlogn).
Algorithm:
1. Construct a binary tree
• The root node corresponds to Data[0].
• If we consider the index associated with a particular node to be i, then the left child of this node
corresponds to the element with index 2*i+1 and the right child corresponds to the element with index
2*i+2. If any or both of these elements do not exist in the array, then the corresponding child node does
not exist either.
2. Construct the heap tree from initial binary tree using "adjust" process.
3. Sort by swapping the root value with the lowest, right most value and deleting the lowest, right most
value and inserting the deleted value in the array in it proper position
2. Explain Shell Sort Algorithm With examples.
The effect is that the data sequence is partially sorted. The process above is repeated, but each time with a
narrower array, i.e. with a smaller number of columns. In the last step, the array consists of only one
column. In each
step, the sortedness of the
3
3
2
0
5
1
5
3
7
9
0
5
1
6
sequence is
increased, until in the last step it is
7440616
completely sorted. 8 4 2 0 6 1 5
However, the number of sorting
879982
734982
operations
necessary in each step is limited,
due to the presortedness of the sequence obtained in the preceding steps.
Data elements 8 and 9 have now already come to the end of the sequence, but a small
element (2) is also still there. In the next step, the sequence is arranged in 3 columns,
which are again sorted:
Example: Let
3790516842
it is arranged in an
0
sorted (right):
5
4
1
7
8
3
5
7
0
6
9
2
2
1
4
6
8
9
0 6 1 5 7 3 4 9 8 2 be the data sequence to be sorted. First,
array with 7 columns (left), then the columns are
0 0 1
1 2 2
3 3 4
4 5 6
5 6 8
7 7 9
8 9
Now the sequence is almost completely sorted. When arranging it in one column in the
last step, it is only a 6, an 8 and a 9 that have to move a little bit to their correct position.
Shellsort is one of the oldest sorting algorithms, named after its inventor D.L. Shell
(1959). It is fast, easy to understand and easy to implement. However, its complexity
analysis is a little more sophisticated.
void shellsort (int[]
The idea of Shellsort is the following:
a, int n)
a. arrange the data sequence in a two-dimensional array
b. sort the columns of the array
{
int i, j, k, h, v;
int[] cols = {1391376, 463792, 198768, 86961, 33936, 13776, 4592,
1968, 861, 336, 112, 48, 21, 7, 3, 1}
for (k=0; k<16; k++)
{
h=cols[k];
for (i=h; i<n; i++)
{
v=a[i];
j=i;
while (j>=h && a[j-h]>v)
{
a[j]=a[j-h];
j=j-h;
}
a[j]=v;
}
}
}
3. Explain Merge Sort with examples.
The sorting algorithm Mergesort produces a sorted sequence by sorting its two halves and
merging them. With a time complexity of O(n log(n)) Mergesort is optimal.
Similar to Quicksort, the Mergesort algorithm is based on a divide and conquer strategy.
First, the sequence to be sorted is decomposed into two halves (Divide). Each half is
sorted independently (Conquer). Then the two sorted halves are merged to a sorted
sequence (Combine) .
The following procedure mergesort sorts a sequence a from index lo to index hi.
void mergesort(int lo, int hi)
The correctness of the algorithm follows from the fact that in the last step (with h = 1) an ordinary
Insertion Sort is performed on the whole array. But since data are presorted by the preceding steps (h =
3, 7, 21, ...) only few Insertion Sort steps are sufficient. How many exactly will be the subject of the
following analysis. The above sequence of h's
(denoted as h-sequence in the following) is just one of several possible; actually, the performance of
Shellsort depends on which h-sequence is used
{
if (lo<hi)
{
int m=(lo+hi)/2;
mergesort(lo, m);
mergesort(m+1, hi);
merge(lo, m, hi);
}
First, index m in the middle between lo and hi is determined. Then the first part of the sequence (from lo
to m) and the second part (from m+1 to hi) are sorted by recursive calls of mergesort. Then the two sorted
halves are merged by procedure merge. Recursion ends when lo = hi, i.e. when a subsequence consists of
only one element.
The main work of the Mergesort algorithm is performed by function merge. There are
different possibilities to implement this function.
Function merge is usually implemented in the following way: The two halves are first copied into an
auxiliary array b. Then the two halves are scanned by pointers i and j and the respective next-greatest
element at each time is copied back to array a (Figure 2).
At the end a situation occurs where one index has reached the end of its half, while the other has not.
Then, in principle, the rest of the elements of the corresponding half have to be copied back. Actually, this
is not necessary for the second half, since (copies of) the remaining elements are already at their proper
places.
void merge(int lo, int m, int hi
{
int i, j, k;
i=0; j=lo;
// copy first half of array a to auxiliary array b
while (j<=m)
b[i++]=a[j++];
i=0; k=lo;
// copy back next-greatest element at each time
hile (k<j && j<=hi)
if (b[i]<=a[j])
a[k++]=b[i++];
else
a[k++]=a[j++];
// copy back remaining elements of first half (if any)
while (k<j)
a[k++]=b[i++];
}
4. Explain Algorithm Design Techniques.
Introduction to Algorithm Design Techniques
Greedy Algorithms:
An optimization problem is one in which you want to find, not just a solution, but
the best solution
consequences
m at each step, you will end up
at a global optimum
Example: Counting money
possible bills and coins
At each step, take the largest possible bill or coin that does not overshoot
Minimum spanning tree
-cost subset of the edges of a graph that
connects all the nodes
y node and adding it to the tree
-cost edge from a node in the tree to a node not
in the tree, and add the edge and new node to the tree
st-cost (3+3+2+2+2=12) spanning tree
Divide-and-Conquer Algorithms
A divide-and-conquer algorithm
Derives the output directly, for small instances
Divides large instances to smaller ones, and (recursively) applies the algorithm on
the smaller instances.
Combines the solutions for the subinstances, to produce a solution for the original instance.
Merge Sort
Sets of cardinality greater than one are decomposed into two equal subsets, the algorithm is recursively
invoked on the subsets, and the returned ordered subsets are merged to provide a sorted variant of the
original set.
The time complexity of the algorithm satisfies the recurrence equation
whose solution is T(n) = O(n log n).
Dynamic Programming Algorithms
The approach assumes a recursive solution for the given problem, with a bottom-up evaluation of the
solution. The subsolutions are recorded (in tables) for reuse.
5.Write quick sort algorithm and explain.
Quick sort
Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely
applied in practice. On the average, it has O(n log n) complexity, making quicksort suitable for sorting big
data volumes.
The divide-and-conquer strategy is used in quicksort. Below the recursion step is
described:
1. Choose a pivot value. We take the value of the middle element as pivot value,
but it can be any value, which is in range of sorted values, even if it doesn't
present in the array.
2. Partition. Rearrange elements in such a way, that all elements which are lesser
than the pivot go to the left part of the array and all elements greater than the
pivot, go to the right part of the array. Values equal to the pivot can stay in any
part of the array. Notice, that array may be divided in non-equal parts.
3. Sort both parts. Apply quicksort algorithm recursively to the left and the right
parts.
There are two indices i and j and at the very beginning of the partition algorithm i points to the first
element in the array and j points to the last one. Then algorithm moves I forward, until an element with
value greater or equal to the pivot is found. Index j is moved backward, until an element with value lesser
or equal to the pivot is found. If i ≤ j then they are swapped and i steps to the next position (i + 1), j steps
to the previous one (j
- 1). Algorithm stops, when i becomes greater than j. After partition, all values before i-th element are less
or equal than the pivot and all values after j-th element are greater or equal to the pivot.
On the average quicksort has O(n log n) complexity, but strong proof of this fact is not trivial and not
presented here. Still, you can find the proof in [1]. In worst case, quicksort runs O(n2) time, but on the
most "practical" data it works just fine and outperforms other O(n log n) sorting algorithms
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}