Upload
hoangtruc
View
214
Download
1
Embed Size (px)
Citation preview
UNIT 1
1. A.1. Define object. (Nov/Dec 12)
• An object doesn't exist until an instance of the class has been created; the class is just a
definition.
• When the object is physically created, space for that object is allocated in RAM. It is
possible to have multiple objects created from one class.
1. A.2. What is constructor? (Nov/Dec 12)
A constructor is a member function with the same name as its class.
For example:
class X {
public:
X(); // constructor for class X
};
Constructors are used to create, and can initialize, objects of their class type.
1. A.3. how is a class declared in C++? (Ap/May 10)
Classes are generally declared using the keyword class, with the following format:
classclass_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
1. A.4. what is a scope resolution operator and how can it be used for global variable?
(Ap/May 10)
• The :: (scope resolution) operator is used to qualify hidden names so that you can still use
them.
• You can use the unary scope operator if a namespace scope or global scope name is
hidden by an explicit declaration of the same name in a block or class. For example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
1. A.5. When do we declare a member of a class static? (Nov/Dec 09)
• A static member is shared by all objects of the class. All static data is initialized to zero
when the first object is created, if no other initialization is present.
• We can't put it in the class definition but it can be initialized outside the class as done in
the following example by redeclaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.
1. A.6. Why is it necessary to overload an operator? (Nov/Dec 09)
It is not necessary to overload operators.
Operator overloading enhences the following though:
- readability of code
- transparency of code
- maintainability of code (i.e. less lines to look into in order to correct "bugs")
1. A.7. what effects do the visibility labels private, protected and public have on the
members of a class?
(Nov/Dec 10)
Member access determines if a class member is accessible in an expression or declaration.
Suppose x is a member of class A. Class member x can be declared to have one of the following
levels of accessibility:
• public: x can be used anywhere without the access restrictions defined by private or
protected.
• private: x can be used only by the members and friends of class A.
• protected: x can be used only by the members and friends of class A, and the members
and friends of classes derived from class A.
1. A.8. what are the advantages of operator overloading? (Nov/Dec 10)
• By overloading standard operators on a class, you can exploit the intuition of the users of
that class.
• This lets users program in the language of the problem domain rather than in the
language of the machine.
• The ultimate goal is to reduce both the learning curve and the defect rate.
1. A.9. what is the difference between a pointer and a reference? (Nov/Dec 11)
• A pointer can be re-assigned any number of times while a reference cannot be
reassigned after initialization.
• A pointer can point to NULL while reference can never point to NULL
• You can't take the address of a reference like you can with pointers
• There's no "reference arithmetics" (but you can take the address of an object pointed
by a reference and do pointer arithmetics on it as in &obj + 5).
1. A.10. what are copy constructors? (Nov/Dec 11)
• A copy constructor is a special constructor for a class/struct that is used to make a copy
of an existing instance.
• According to the C++ standard, the copy constructor for MyClass must have one of the
following signatures:
1
2
3
4
MyClass( constMyClass& other );
MyClass( MyClass& other );
MyClass( volatileconstMyClass& other );
MyClass( volatileMyClass& other );
1.A.11. what is object oriented paradigm? (Nov/Dec 07)
• Object-oriented and component-based analysis, design, and programming has, in the last
10 years, changed the way systems are designed and developed.
• But objects and components are not necessarily the best way to implement every system.
Sometimes you need less abstraction, or abstraction of a different kind.
1.A.12. which feature of object oriented provides data hiding and reusability? (Nov/Dec 05)
• The reuse of source code is a common technique by developers that has been practiced
for some time now.
• Its general purpose is to reduce unnecessary coding which ultimately reduces project
development time and money.
• It is basically taking code from one area of a program and attempting to utilize it
elsewhere without having to change too much.
• This technique is similar to reusing software components in object-oriented
programming.
1. A.13. List any two drawbacks of procedure oriented programming? (Nov/Dec 05)
• Well, although procedural-oriented programs are extremely powerful, they do have some
limitations.
• Perhaps the most serious limitation is the tendency for large procedural-based programs
to turn into "spaghetti-code".
• Spaghetti code is code that has been modified so many times that the logical flow shown
in the figures above becomes so convoluted that any new programmer coming onto the
project needs a two month prep-course in order to even begin to understand the software
innards.
1. A.14. Name the mechanism that binds together code and data it manipulates. (Nov/Dec
06)
Encapsulation helps hide implementation behind an interface.Encapsulated code has two
features:
1.Instance variables are kept protected (usually with the private modifier).
2. Getter and setter methods provide access to instance variables.
1. A.15. What is the application of the scope resolution operator:: in c++? (Nov/Dec 06)
It is used to qualify a variable or function or pretty much anything else as being in a class or a
namespace:
1.A.16. How does a constructor differ from normal function? (Nov/Dec 07)
1) Functions have return type but constructors don't have a return type.
2) Name of the constructors must be similar to class where as function don't have such kind of
restrictions
UNIT 2
2. A.1. What is unique about this pointer? (Nov/Dec 05)
• These objects have the ability of taking ownership of a pointer: once they take ownership
they manage the pointed object by becoming responsible for its deletion at some point.
• unique_ptr objects automatically delete the object they manage (using a deleter) as soon
as they themselves are destroyed, or as soon as their value changes either by an
assignment operation or by an explicit call to unique_ptr::reset.
2. A.2. Write a function template to swap 2 variables. (Nov/Dec 05)
#include <iostream>
usingnamespacestd;
template<typename T>
void swap(T &n1, T &n2) // Note the &
{
T temp=n1; // Note use the type T
n1=n2;
n2=temp;
}
int main()
{
int a = 2;
int b = 3;
swap(a, b); // Now a = 3 and b = 2
double x = 2.3;
double y = 4.5;
swap(x, y); // Now x = 4.5 and y = 2.3
}
2. A.3. Why is it necessary to include the file IO stream in all our programs? (Nov/Dec 06)
• It is a command to the compiler telling it to take the file iostream and to insert it instead
of the directive.
• This is necessary because there the file iostream introduces some new commands we
need later.
2. A.4. Name the two ways in which a file can be opened. (Nov/Dec 06)
• The first operation generally performed on an object of one of these classes is to associate
it to a real file.
• This procedure is known as to open a file.open (filename, mode);
2. A.5. What is an IO stream? (Nov/Dec 07)
• In the C++programming language, Input/output library refers to a family of class
templates and supporting functions in the C++ Standard Library that implement stream-
based input/output capabilities.
• It is an object-oriented alternative to C's FILE-based streams from the C standard library.
2. A.6. What is the type of class for which the object cannot be created? (Nov/Dec 07)
template<class T>
classTest
{
private:
T variable;
public:
Test(){cout<<"CONSTRUCTOR CALLED"<<endl;}
};
2. A.7. What is an abstract class? (Nov/Dec 09)
• An abstract class is, conceptually, a class that cannot be instantiated and is usually
implemented as a class that has one or more pure virtual (abstract) functions.
• A pure virtual function is one which must be overridden by any concrete (i.e., non-
abstract) derived class. This is indicated in the declaration with the syntax " = 0" in the
member function's declaration.
2. A.8. What does ‘this’ pointer point to? (Nov/Dec 09)
• The keyword this identifies a special type of pointer. Suppose that you create an object
named x of class A, and class A has a nonstatic member function f().
• If you call the function x.f(), the keyword this in the body of f() stores the address of x.
You cannot declare the this pointer or make assignments to it.
• A static member function does not have a this pointer
2. A.9. What is inheritance? What are its advantages? (Nov/Dec 10)
Inheritance is a mechanism of reusing and extending existing classes without modifying them,
thus producing hierarchical relationships between them.
• Allows the code to be reused as many times as needed. The base class once defined and
once it is compiled, it need not be reworked.
• Saves time and effort as the main code need not be written again.
2. A.10. Define virtual function. (Nov/Dec 10)
• A virtual function is a member function that is declared within a base class and redefined
by a derived class.
• To create virtual function, precede the function’s declaration in the base class with the
keyword virtual.
• When a class containing virtual function is inherited, the derived class redefines the
virtual function to suit its own needs.
2. A.11. What is a friend function? (Nov/Dec 11)
• A friend function of a class is defined outside that class's scope but it has the right to
access all private and protected members of the class.
• Even though the prototypes for friend functions appear in the class definition, friends are
not member functions.
2. A.12. What is a virtual base class? (Nov/Dec 11)
• When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects by
declaring the base class as virtual when it is being inherited.
• Such a base class is known as virtual base class.
• This can be achieved by preceding the base class’ name with the word virtual.
2. A.13. What is meant by binding? (Ap/May 10)
• Each argument may either be bound to a value or be a placeholder:
- If bound to a value, calling the returned function object will always use that value as
argument.
-
ca
2. A.14. H
• A
p
• T
co
• A
(h
2. A.15. L
• M
is
• C
2. A.16. W
The follo
An arrow
The orde
construct
A direct b
class
class
If a placeho
all (the one w
How the po
A smart poin
ointers are o
These objects
onstructor an
A smart poin
hence called
List out the
Most can be o
s technically
C++ adds a f
What does m
owing inheri
w points to th
er of derivati
tors and clea
base class ca
s B1 { /* ...
s D : public
older, calling
whose order
ointer is imp
nter is a po
objects which
s are flexibl
nd destructo
nter is desig
smart).
e operators w
overloaded.
an operator
few of its ow
multiple inh
itance graph
he direct bas
on is relevan
anup by destr
annot appear
*/ };
B1, private B
g the returned
r number is s
plemented in
ointer which
h behave lik
le as pointer
rs called aut
gned to han
which cann
The only C
r).
wn operators
heritance m
h describes th
e class of th
nt only to de
ructors.
r in the base
// direct
B1 { /* ... */
d function ob
specified by
n C++? (Ap
h is smart. W
ke pointers bu
rs and have
tomatically).
dle the prob
ot be overlo
operators th
, most of wh
mean? (Nov/D
he inheritanc
he class at the
etermine the
list of a der
t base class
/ }; // error
bject forwar
the placehol
p/May 10)
What does
ut do more t
e the advant
.
blems cause
oaded. (Nov
hat can't be a
hich can be o
Dec 12)
ce relationsh
e tail of the a
order of def
rived class m
rds an argum
lder).
that mean?
than a pointe
tage of bein
ed by using
v/Dec 12)
are .and ?: (a
overloaded e
hips of the ab
arrow:
fault initializ
more than onc
ment passed t
? Actually, s
er.
ng an object
normal poi
and sizeof, w
except :: and
bove exampl
zation by
ce:
to the
smart
(like
inters
which
d .*.
le.
UNIT 3
3. A.1. Define the worst case and average case complexities of an algorithm? (Nov/Dec 05)
• Best, worst and average cases of a given algorithm express what the resource usage is at
least, at most and on average, respectively.
• Usually the resource being considered is running time, but it could also be memory or
other resources.
3. A.2. Define a Queue model. (Nov/Dec 05)
• Queuing refers to lining up jobs for a computer or device. For example, if you want to
print a number of documents, the operating system (or a special print spooler) queues the
documents by placing them in a special area called a print buffer or print queue.
• The printer then pulls the documents off the queue one at a time. Another term for this is
print spooling .
3. A.3. Define Abstract data type (ADT). (Nov/Dec 06) (Nov/Dec 12)
• An abstract data type (ADT) is a mathematical model for a certain class of data
structures that have similar behavior; or for certain data types of one or more
programming languages that have similar semantics.
• An abstract data type is defined indirectly, only by the operations that may be performed
on it and by mathematical constraints on the effects (and possibly cost) of those
operations.
3. A.4. List out the operations of the list ADT. (Nov/Dec 06)
• A list or sequence is an abstract data type that implements an ordered collection of
values, where the same value may occur more than once.
• An instance of a list is a computer representation of the mathematical concept of a finite
sequence.
• Each instance of a value in the list is usually called an item, entry, or element of the list;
if the same value occurs multiple times, each occurrence is considered a distinct item.
3. A.5. What is an algorithm? (Nov/Dec 07)
Algorithm: a process or set of rules used for calculation or problem-solving, esp. with a
computer.
3. A.6. List few applications of queue. (Nov/Dec 07)
1) When a resource is shared among multiple consumers. Examples include CPU scheduling,
Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.
3. A.7. What is deque? (Nov/Dec 09)
• DeQueue is a data structure in which elements may be added to or deleted from the front
or the rear. Like an ordinary queue, a double-ended queue is a data structure it supports
the following operations: enq_front, enq_back, deq_front, deq_back, and empty.
• Dequeue can be behave like a queue by using only enq_front and deq_front , and behaves
like a stack by using only enq_front and deq_rear. .
3. A.8. What is a heap and mention its types? (Nov/Dec 09)
• Choose MinHeap or MaxHeap if you need a simple minimum or maximum heap (which
always keeps the minimum/maximum element at the head of the Heap).
• If you wish to manually annotate a value with a priority, e. g. an IO () action with an Int
use MinPrioHeap or MaxPrioHeap. They manage (prio, val) tuples so that only the
priority (and not the value) influences the order of elements.
• If you still need something different, define a custom order for the heap elements by
implementing an instance of HeapItem and let the maintainer know what's missing.
3. A.9. Define stack. Mention the operations on stack. (Nov/Dec 10)
• A stack is a homogeneous collection of items of any one type, arranged li nearly with
access at one end only, called the top. This means that data can be added or removed
from only thetop.
• Formally this type of stack is called a Last In, First Out (LIFO) stack. Data is added to the
stack using the Push operation, and removed using the Pop operation. Representation- A
stack as
3. A.10. What is binary heap? What are its types? (Nov/Dec 10)
A binary heap is a complete binary tree which satisfies the heap ordering property. The ordering
can be one of two types:
• themin-heap property: the value of each node is greater than or equal to the value of its
parent, with the minimum-value element at the root.
• th
p
3. A.11. W
The man
• A
In
• A
S
• O
ac
th
• A
C
3. A.12. W
(Nov/De
• T
so
fr
• T
so
la
3. A.13. W
• O
sp
• B
3. A.14. W
Big O no
algorithm
execution
The relat
gro
hemax-heap
arent, with t
What are m
ipulator clas
An Init metho
nit Method.
A Cleanup m
ee Creating
OnMouseDow
ctions when
he mouse. Se
An OnKeybo
Creating an O
What is the
c 11)
The term "fun
ometimes us
rom a functio
This ambigu
omething lik
atter.
Write any t
OS heap man
pecifically h
Besides, OS
What are th
otation is use
m. Big O spe
n time requir
tion
ows much fas
property: th
he maximum
manipulator
ss definition
od - this met
method - this
a Cleanup M
wn, OnMou
the user act
ee Creating M
oard method
OnKeyboard
e difference
nction templ
sed to mean
on template.
uity is best
ke "function
two data str
nagement is
heap manage
memory ma
he represen
ed in Compu
ecifically des
red or the sp
is
ster than
he value of ea
m-value elem
s? How do y
file will hav
thod initializ
method des
Method.
useUp, OnM
tivates the m
Mouse Even
- this metho
Method.
between a f
late" refers t
the same th
.
avoided b
n template in
ructures use
s not part of
ement.
anagement is
tations of B
uter Science
scribes the w
pace used (e.
s read as "
, or simila
ach node is l
ment at the ro
you create a
ve the follow
zes a manipu
stroys pointe
MouseMotio
manipulator a
nt Methods.
od links keyb
function tem
o a kind of t
hing, and so
y using "fu
nstance" or "
ed in Operat
f the C lang
s OS specific
Big and smal
to describe t
worst-case sc
g. in memor
is little-
arly, the grow
less than or
oot.
a one? (Nov
wing compon
ulator object
ers or objects
on methods
and interacts
board event
mplate and t
template. Th
ometimes to
function tem
"instance of
ting System
guage. The C
c and may va
ll ‘O’ notati
the performa
cenario, and
ry or on disk
-o of ".
wth of
equal to the
v/Dec 11)
nents:
t. See Creatin
s created by
- these m
s with the vi
s to manipul
template fu
he term "tem
mean a func
mplate" for
f a function t
m? (Ap/May
C langauge
ary among O
ions? (Ap/M
ance or comp
d can be used
k) by an algo
. Intuitively,
is nothing c
value of its
ng a Manipu
y the manipu
methods per
isualization u
lator actions
unction?
mplate functio
ction instant
the former
template" fo
y 10)
does not re
OSes
May 10)
plexity of an
d to describe
orithm.
it means tha
compared to
ulator
ulator.
rform
using
s. See
on" is
tiated
r and
or the
equire
n
e the
at
that
of .
→ ∞ mea
3. A.15. W
A data st
elements
declared
structstru
member_
member_
member_
.
.
} object_
3. A.16. D
(1) In pr
when the
whose siz
(2) A spe
leaves. A
UNIT 4
4. A.1. D
• A
u
• N
p
n
• A
fo
It assumes t
ans that for e
What are th
tructure is a g
, known as m
in C++ usin
ucture_name
_type1 memb
_type2 memb
_type3 memb
_names;
Define heap
rogramming,
e program a
ze can be de
ecial type of
A heap sort a
Define comp
A binary tre
sually distin
Nodes with c
arents. Outs
odes), if it ex
Any node in
ollowing refe
that f and g a
every positiv
he basic dat
group of dat
members, ca
ng the follow
e {
ber_name1;
ber_name2;
ber_name3;
p. (Nov/Dec
, an area of
ctually exec
etermined wh
f binary tree
algorithm wo
lete binary
ee is a tree d
nguished as "
children are
ide the tree,
xists.
the data str
ferences to ei
are both fun
ve constant
ta structure
ta elements g
an have diffe
wing syntax:
12)
f memory re
cutes. In con
hen the prog
in which th
orks by first
tree. (Nov/D
data structur
"left" and "ri
parent node
there is ofte
ructure can
ither the left
ctions of one
there exists
s available i
grouped toge
erent types an
served for d
ntrast, the st
gram is comp
he value of e
organizing a
Dec 05)
re in which
ight".
es, and child
en a referen
be reached
t or right chil
e variable. F
s a constant N
in C++? (No
ether under o
nd different
data that is
tack is an ar
piled.
each node is
a list of data
each node h
d nodes may
nce to the "ro
by starting
ld.
Formally, f(n
N such that
ov/Dec 12)
one name. T
lengths. Dat
created at ru
rea of memo
greater than
into a heap.
has at most
y contain re
oot" node (th
at root nod
n) = o(g(n)) a
These data
ta structures
untime -- th
ory used for
n the values
two child n
eferences to
he ancestor
de and repea
as n
are
hat is,
r data
of its
nodes,
their
of all
atedly
4. A.2. H
• A
b
• A
co
4. A.3. W
(Nov/De
• A
co
• T
im
co
ob
4. A.4. D
06)
• A
• T
on
se
4. A.5. W
• A
by
• T
ad
af
ad
How binary
Arrays can b
inary tree, al
At the deepe
omplete bina
What is the s
c 06)
An adjacency
ollection of
There are m
mplement th
ollections, in
bjects, and i
Draw a direc
A directed ac
That is, it is f
ne vertex to
equence of e
What is the m
An AVL tree
y no more th
To maintain
dditional pie
fter every i
dditional pi
tree represe
be used to r
ll of the dept
est depth, th
ary tree with
space requir
y list represe
its neighbori
many variatio
he associatio
n whether th
n what kind
cted acyclic
cyclic graph
formed by a
o another, su
edges that ev
minimum n
e is a binary
han 1, and w
balance in a
ece of inform
nsert and d
ece of info
ented using
represent com
ths are full,
he nodes are
h 9 nodes; ea
rement of a
entation for
ing vertices
ons of this
on between v
hey include b
s of objects
graph with
h is a directe
a collection o
uch that ther
ventually loo
umber of n
search tree
whose left and
a height bal
mation that
delete operat
rmation is
an array? G
mplete bina
except perha
e as far left
ach node con
n adjacency
a graph asso
or edges.
basic idea,
vertices and
both vertices
are used to r
h 4 vertices a
ed graph with
of vertices a
re is no way
ops back to v
odes in the
whose left s
d right subtr
lanced binar
is needed to
tion has be
called the b
Give an exa
ary trees. Re
aps for the d
ft as possibl
ntains a char
y list repres
ociates each
, differing
d collections,
s and edges
represent the
and give its
h no directed
and directed
y to start at
v again.
AVL tree o
subtree and
rees are them
ry tree, each
o efficiently
een performe
balance fac
ample. (Nov
emember th
deepest.
le. For exam
racter.
sentation of
h vertex in th
in the deta
, in how the
or only vert
e vertices an
topological
d cycles.
edges, each
some verte
of height 5?
right subtre
mselves AVL
h node will
maintain ba
ed. For an
ctor, and it
v/Dec 05)
hat in a com
mple, below
f a graph?
he graph wit
ails of how
ey implemen
tices as first
nd edges
l sort. (Nov/
h edge conne
x v and foll
(Nov/Dec 0
ee differ in h
L trees.
have to kee
alance in the
n AVL tree
t indicates i
mplete
w is a
th the
they
nt the
class
/Dec
ecting
low a
7)
height
ep an
e tree
, this
if the
difference in height between the left and right subtrees is the same or, if not, which of the
two subtrees has height one unit larger.
• If a node has a balance factor rh (right high) it indicates that the height of the right
subtree is 1 greater than the height of the left subtree. Similarly the balance factor for a
node could be lh (left high) or eh (equal height).
4. A.6. Define NP complete problem? (Nov/Dec 07)
• In computational complexity theory, the complexity classNP-complete (abbreviated NP-
C or NPC) is a class of decision problems.
• A decision problem L is NP-complete if it is in the set of NP problems and also in the set
of NP-hard problems. The abbreviation NP refers to "nondeterministicpolynomial time."
4. A.7. What is AVL tree? (Nov/Dec 09) • An AVL tree (Adelson-Velskii and Landis' tree, named after the inventors) is a self-
balancing binary search tree, and it was the first such data structure to be invented.
• In an AVL tree, the heights of the two childsubtrees of any node differ by at most one; if
at any time they differ by more than one, rebalancing is done to restore this property.
• Lookup, insertion, and deletion all take O(log n) time in both the average and worst
cases, where n is the number of nodes in the tree prior to the operation.
4. A.8. When does a graph become tree? (Nov/Dec 09)
• A tree is an undirected graph in which any two vertices are connected by exactly
onesimple path. In other words, any connected graph without simple cycles is a tree.
• A forest is a disjoint union of trees.
4. A.9. What is meant by an adjacency matrix? (Nov/Dec 10)
• An adjacency matrix is a means of representing which vertices (or nodes) of a graph are
adjacent to which other vertices.
• Another matrix representation for a graph is the incidence matrix.
• Specifically, the adjacency matrix of a finite graph G on n vertices is the n × n matrix
where the non-diagonal entry aij is the number of edges from vertex i to vertex j, and the
diagonal entry aii, depending on the convention, is either once or twice the number of
edges (loops) from vertex i to itself.
4. A.10. State the properties of binary search tree. (Nov/Dec 10)
• Binary Search tree is a binary tree in which each internal node x stores an element such
that the element stored in the left subtree of x are less than or equal to x and elements
stored in the right subtree of x are greater than or equal to x.
• This is called binary-search-tree property.
4. A.11. What is an abstract class? (Nov/Dec 11)
An abstract class is a class that is designed to be specifically used as a base class. An abstract
class contains at least one pure virtual function. You declare a pure virtual function by using a
pure specifier (= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:
class AB {
public:
virtual void f() = 0;};
4. A.12. Under which contexts would you use ‘final’ and ‘finally’. (Nov/Dec 11)
4. A.13. How many trees are possible with 3 nodes? (Ap/May 10)
For example (notation: root(left,right)):
A(-,B(-,C))
A(-,C(B,-))
B(A,C)
C(B(A,-),-)
C(A(-,B),-)
4. A.14. What is a spanning tree? (Ap/May 10)
• Aspanning treeT of a connected, undirected graphG is a tree composed of all the vertices
and some (or perhaps all) of the edges of G.
• Informally, a spanning tree of G is a selection of edges of G that form a tree spanning
every vertex.
• That is, every vertex lies in the tree, but no cycles (or loops) are formed. On the other
hand, every bridge of G must belong to T.
4. A.15. When the tree is called complete binary tree? (Nov/Dec 12)
• Trees satisfying property (H) are particularly useful if they are well balanced, in the sense
of having short path lengths from root to leaves.
• T
p
UNIT 5
5. A.1. W
• M
al
• Q
qu
"m
• B
sq
• E
p
5. A.2. D
Analyze
Ex: quick
– O(N lo
– leads to
time, ind
5. A.3. H
What ha
• In
ou
• O
it
re
They don't ha
ath lengths a
What is the r
Mergesort: th
lways recurs
Quicksort: I
uicksort alg
middle" list,
But this isn't
quared.
Each time all
artition, then
Determine th
average runn
ksort.
g N) if input
o randomize
dependent of
How many p
appens in its
nsertion sort
utput list.
On a repetitio
t belongs wi
emain.
ave to be qu
are as short a
running tim
his will run
se on both ha
can imagine
gorithm wou
which woul
a very comm
l of the elem
n recursively
he average r
ning time ov
t is assumed
d algorithm
f input
passes does t
s ith pass? (N
t iterates, con
on, insertion
ithin the sor
uite as well b
as possible. F
me of insertio
on the order
alves of the a
e this being
uld put all
ldn't need to
mon implem
ments, save t
y sorted, givi
running tim
ver some dis
d to be in ran
with O(N lo
the insertion
Nov/Dec 06)
nsuming one
sort remove
rted list, and
balanced as t
For example
on sort if al
r of nlog(n).
array.
g either linea
elements eq
o be recursive
mentation. M
he pivot, wi
ing the dread
me of quick s
stribution of
ndom order.
og N) expect
n sort algor
)
e input elem
es one eleme
d inserts it t
the tree abo
e, we could h
ll keys are e
. Regardless
ar or quadra
qual to the
ely sorted.
More likely, it
ill be dumpe
ded quadrati
sort. (Nov/D
inputs.
ted running
rithm do to
ment each rep
ent from the
there. It rep
ve. All we r
have
equal? (Nov/
s of the inpu
atic. For the
pivot in th
t would run
ed into eithe
ic runtime.
Dec 05)
sort a list of
petition, and
input data, f
peats until n
require is tha
/Dec 05)
ut, mergesort
e linear case
heir own sp
on the order
er the left or
f 5 elements
growing a s
finds the loc
no input elem
at the
t will
e, the
pecial
r of n
right
s?
sorted
cation
ments
5. A.4. Mention the time complexities of merge sort and shell sort. (Nov/Dec 06)
Suppose (for simplicity) that n = 2k for some entire k. Let T(n) the time used to sort n elements.
As we can perform separation and merging in linear time, it takes cn time to perform these two
steps, for some constant c. So,
T(n) = 2T(n/2) + cn.
In the same way:
T(n/2) = 2T(n/4) + cn/2, so
T(n) = 4T(n/4) + 2cn.
Going in this way ...
T(n) = 2mT(n/2m) + mcn, and
T(n) = 2kT(n/2k) + kcn = nT(1) + cnlog2n = O(n log n).
Remember, as n=2k k = log2n!
The general case requires a bit more work, but it takes O(n log n) time anyway.
LSD
MSD Radix sort O(n.k/s) O(n.k/s.2^s)
n=no of items to be sorted
k=size of each key
s=chunk size used by implementation
LSD=Least Significant Digit
MSD=Most Significant Digit
5. A.5. What is the time complexity of insertion sort algorithm? (Nov/Dec 07)
It depends on whether the structure is a linked list or a binary tree. Linked lists are generally
O(n), with an expected average of O(n/2). With binary trees, the average is O(log n) if the tree is
balanced.
5. A.6. What is insertion sort? (Nov/Dec 07)
• One of the simplest methods to sort an array is an insertion sort. An example of an
insertion sort occurs in everyday life while playing cards.
• To sort the cards in your hand you extract a card, shift the remaining cards, and then
insert the extracted card in the correct place.
• This process is repeated until all the cards are in the correct sequence. Both average and
worst-case time is O(n2).
5. A.7. What is the worst case and best case time complexity of binary tree sort? (Nov/Dec
09)
• A tree sort is a sort algorithm that builds a binary search tree from the keys to be sorted,
and then traverses the tree (in-order) so that the keys come out in sorted order.
• Its typical use is when sorting the elements of a stream from a file.
• Several other sorts would have to load the elements to a temporary data structure,
whereas in a tree sort the act of loading the input into a data structure is sorting it.
5. A.8. What is indexed sequential search? (Nov/Dec 09)
• An index file can be used to effectively overcome the above mentioned problem, and to
speed up the key search as well.
• The simplest indexing structure is the single-level one: a file whose records are pairs key-
pointer, where the pointer is the position in the data file of the record with the given key.
• Only a subset of data records, evenly spaced along the data file, are indexed, so to mark
intervals of data records.
5. A.9. What is sorting? How is sorting essential for data base applications? (Nov/Dec 10)
Sorting is any process of arranging items in some sequence and/or in different sets, and
accordingly, it has two common, yet distinct meanings:
1. ordering: arranging items of the same kind, class, nature, etc. in some ordered sequence,
2. categorizing: grouping and labeling items with similar properties together (by sorts).
5. A.10. What is meant by dynamic programming? (Nov/Dec 10)
• The idea behind dynamic programming is quite simple. In general, to solve a given
problem, we need to solve different parts of the problem (subproblems), then combine the
solutions of the subproblems to reach an overall solution.
• The dynamic programming approach seeks to solve each subproblem only once, thus
reducing the number of computations: once the solution to a given subproblem has been
computed, it is stored or "memo-ized": the next time the same solution is needed, it is
simply looked up.
• This approach is especially useful when the number of repeating subproblemsgrows
exponentially as a function of the size of the input.
5. A.11. How is the keyword ‘super’ used in Java? (Nov/Dec 11)
• If your method overrides one of its superclass's methods, you can invoke the overridden
method through the use of the keyword super.
• You can also use super to refer to a hidden field (although hiding fields is discouraged).
Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
5. A.12. What are wrapper classes in Java? (Nov/Dec 11)
• Java uses primitive types, such as int, char, double to hold the basic data types supported
by the language.
• Sometimes it is required to create an object representation of these primitive types.
• These are collection classes that deal only with such objects. One needs to wrap the
primitive type in a class.
• To satisfy this need, java provides classes that correspond to each of the primitive types.
Basically, these classes encapsulate, or wrap, the primitive types within a class.
5. A.13. What is the feature of bucket sort algorithm? (Ap/May 10)
Bucket sort works as follows:
1. Set up an array of initially empty "buckets".
2. Scatter: Go over the original array, putting each object in its bucket.
3. Sort each non-empty bucket.
4. Gather: Visit the buckets in order and put all elements back into the original array.
5. A.14. Define dynamic programming. (Ap/May 10)
• The idea behind dynamic programming is quite simple.
• In general, to solve a given problem, we need to solve different parts of the problem
(subproblems), then combine the solutions of the subproblems to reach an overall
solution.
• Often when using a more naive method, many of the subproblems are generated and
solved many times.
• T
re
5. A.15. D
• A
th
• A
b
5. A.16. W
(Nov/De
• If
li
• F
ar
• H
an
co
The dynamic
educing the n
Define span
A spanning tr
he tree once.
A minimum
etween node
What is the
c 12)
f the value b
ikely, the exp
or example,
re equally lik
However, if i
nd the exp
orresponding
c programmi
number of c
nning tree. (
ree is a tree
spanning tr
es is minimiz
e worst case
eing sought
pected numb
if the value
kely, the exp
it is known t
pected numb
g to a single
ing approac
omputations
(Nov/Dec 12
associated w
ree is a span
zed.
and best ca
occurs k tim
ber of compa
e being sough
pected numb
that it occur
ber of com
if-then-else
ch seeks to
s:
2)
with a netwo
nning tree o
ase no. of co
mes in the lis
arisons is
ht occurs on
ber of compa
rs once, than
mparisons is
e construct).
solve each
ork. All the n
organized so
omparisons
st, and all ord
nce in the lis
arisons is
n at most n
(for exam
subproblem
nodes of the
o that the to
in a linear s
derings of th
t, and all ord
.
- 1 compari
mple, for n
m only once,
e graph appe
otal edge w
search?
he list are eq
derings of th
isons are ne
= 2 this
, thus
ear on
weight
qually
he list
eded,
is 1,
UNIT 1
1. B.1. Explain the following concepts of object oriented programming. Data abstraction,
inheritance, polymorphism and objects in detail with example. Or
Data abstraction
Abstraction is the process of recognizing and focusing on important characteristics of a situation
or object and leaving/filtering out the un-wanted characteristics of that situation or object.
Inheritance
Inheritance enables new classes to receive—or inherit—the properties and methods of existing
classes. In previous articles, you learned that an object is a self-contained component that
contains properties and methods needed to make a certain type of data useful.
Polymorphism Polymorphism is the ability of an object or reference to take many different forms at different instances. These are of two types one is the "compile time polymorphism" and other one is the "run-time polymorphism".
Objects
An object is a location in memory having a value and referenced by an identifier. An object can be a variable, function, or data structure. With the later introduction of object-oriented programming the same word, "object," refers to a particular instance of a class.
1. B.2 List out any 5 merits of object oriented methodology.
• Maintainable
• Reusable
• Scalable
1. B.3 Compare and contrast the following control structures with example.
a) If……..else statement and switch statement.
Simply saying, IF-ELSE can have values based on constraints.
Where SWITCH can have values based on user choice.
b) Do…….while statement and while statement.
• The main difference between a while loop and a do-while loop lies in when the condition
is evaluated.
• With a while loop, it's evaluated before the loop is run; with a do-while loop, it's
evaluated after the loop is run.
In other words, with a while loop, the procedure goes like this:
1. Check the condition. If it's true, go to step 2. Otherwise, move on.
2. Run the code in the body of the loop.
3. Go to step 1.
With a do-while loop, the procedure goes like this:
1. Run the code in the body of the loop.
2. Check the condition. If it's true, go to step 1. Otherwise, move on.
1. B.4. Write a program to overload = operator. Assign values of data members of one
object to another object of the same type. Or
#include<iostream> #include<conio.h> #include<iomanip> usingnamespacestd; classarr { public: int *arr1; intlen; arr&operator = (constarr&eq) //for copying two arrays. <--- my overloader { arr temp1(eq.len); arr *pttemp; int i=0; //temp.arr1=new int[eq.len]; //temp.len = eq.len; for(i = 0 ; i <eq.len ; i++) { temp1.arr1[i] = eq.arr1[i]; } pttemp = &temp1; return temp1; }; friendistream&operator>> (istream&ist, arr& r) { staticint i = 0; int *arrNew;
if (i == r.len) { r.len *=2; arrNew = newint[r.len]; // allocate the new array for(int j = 0; j <r.len/2; j++)// copy the old array to the first half of the new array arrNew[j] = r.arr1[j];// delete the old array delete [] r.arr1;// let arr point to the new array and continue use arr r.arr1 = arrNew; deletearrNew; } ist>>r.arr1[i]; i++; returnist; } arr() //initializing constructor { len = 5; arr1 = newint[len]; }; arr(int size) //initializing constructor with args { len = size; arr1 = newint[len]; }; arr(arr& a) : arr1(a.arr1) //copy constructor { arr1 = newint[len]; }; ~arr() //delete constructor { delete arr1; }; }; void main() { int size = 5,i,temp,trig = 0; arrorig(size), asc(size), desc(size); //generate random numbers for orig for (i = 0 ; i < size ; i++) {
orig.arr1[i] = rand(); } //copy original set to asc and desc asc = orig; desc = orig; //sorting ascending for (i = 0 ; i < size-1 ; i++) { trig = 1; if (asc.arr1[i] < asc.arr1[i+1]) { temp = asc.arr1[i]; asc.arr1[i] = asc.arr1[i+1]; asc.arr1[i+1] = temp; trig = 0; } if (trig = 1) break; if (i == size - 1) { i = 0; } } //sorting descending for (i = 0 ; i < size-1 ; i++) { trig = 1; if (desc.arr1[i] > desc.arr1[i+1]) { temp = desc.arr1[i]; desc.arr1[i] = desc.arr1[i+1]; desc.arr1[i+1] = temp; trig = 0; } if (trig = 1) break; if (i == size - 1) { i = 0; } } //printing cout<<"Original Array: "; for (i = 0 ; i < size ; i++) {
cout<<orig.arr1[i]<<" "; } cout<<endl; cout<<"Ascending Array: "; for (i = 0 ; i < size ; i++) { cout<<asc.arr1[i]<<" "; } cout<<endl; cout<<"Descending Array: "; for (i = 0 ; i < size ; i++) { cout<<desc.arr1[i]<<" "; } cout<<endl; getch(); } 1.B.5 Explain object oriented paradigm with all its essential elements.
• Object
• Class
• Instance
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Message Passing
1.B.6State merits and demerits of object oriented methodology.
• OOP provides a clear modular structure for programs which makes it good for defining abstract data types where implementation details are hidden and the unit has a clearly defined interface.
• OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
• OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.
Demerits of Object Oriented Programming
• Unfamiliarity (causing an added training cost for developers).
• Inability to work with existing systems • Data and operations are separated • No data abstraction or info hiding • Not responsive to changes in problem space • Inadequate for concurrent problems
1. B.7 Write a C++ program to extract the elements placed in the odd position of the array.
public class odd { intarr[10]; public: void getarr() { int i; cout<<"Enter the values for array"; for(i=0;i<10;i++) { cin>>arr[i]; } } void odddisp() { int i; for(i=0;i<10;i++) { if(i%2!=0) { cout<<"The odd position values are"<<arr[i]; } } } }; void main() { odd d; d.getarr(); d.odddisp(); return 0; }
1. B.8State the rule to be followed while overloading an operator. Write a program to
illustrate overloading. Or
// rules_for_operator_overloading.cpp class Point
{ public: Point operator<( Point & ); // Declare a member operator // overload. // Declare addition operators. friend Point operator+( Point&, int ); friend Point operator+( int, Point& ); }; int main() { }
#include <string> classPlMessageHeader { std::string m_ThreadSender; std::string m_ThreadReceiver; //return true if the messages are equal, false otherwise inlinebool operator == (constPlMessageHeader&b) const { return ( (b.m_ThreadSender==m_ThreadSender) && (b.m_ThreadReceiver==m_ThreadReceiver) ); } //return true if the message is for name inlineboolisFor (conststd::string &name) const { return (m_ThreadReceiver==name); } //return true if the message is for name inlineboolisFor (const char *name) const { return (m_ThreadReceiver==name);// since name type is std::string, it becomes unsafe if name == NULL }
1. B.9 Describe about polymorphism and its advantages.
• In object-oriented programming, polymorphism refers to a programming language's
ability to process objects differently depending on their data type or class.
• More specifically, it is the ability to redefine methods for derived classes. For example,
given a base class shape, polymorphism enables the programmer to define different area
methods for any number of derived classes, such as circles, rectangles and triangles.
• No matter what shape an object is, applying the area method to it will return the correct
results. Polymorphism is considered to be a requirement of any true object-oriented
programming language (OOPL).
1. B.10what are inline functions? Explain the situation where inline expansion may not
work.
An inline function is a function that is expanded in line when it is invoked.That is, the compiler replaces the function call with the corresponding function code. The inline functions are defined as follows: Inline function-header { function body }
Example: Inline double cube (double a) { return (a*a*a); }
The above inline function can be invoked by statements like C=cube (3.0); D=cube (2.5+1.5);
Some of the situations where inline expansion may not work are:
o For functions returning values,if a loop,aswitch,or a goto exists. o For functions not returning values,if a return statement exits. o If functions contain static variables. o If inline functions are recursive.
1. B.11 what is a friend function? What are the merits and demerits of using friend
function? (8)
• A friend function that is a "friend" of a given class is allowed access to public, private, or protecteddata in that class. Normally, a function that is defined outside of a class cannot access such information.
• Declaring a function a friend of a class allows this, in languages where the concept is supported.
• A friend function is declared by the class that is granting access. Friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords
Merits and demerits
• When the function needs access to the private and/or protected members of the
class within which it is declared.
• The demerit is that it exposes the entire class to the function, however this is no
worse than using public inheritance.
• It is a necessity to use friend functions when two classes must work together, or
where an external function is required to reverse an assignment operator.
1. B.12Define a class ‘string’. Use overload ‘= =’ operator to compare two strings. (8)
Or
#include<iostream.h> #include<conio.h> #include<string.h> enumboolean {false,true}; class STRING { private:charstr[40]; public:voidget_string(); boolean operator==(STRING s1); }; void STRING::get_string() { cin.getline(str,40); } boolean STRING::operator==(STRING s1) { boolean match; match=(strcmp(str,s1.str)==0) ? true : false; return match; }
int main() { STRING s1,s2; clrscr(); cout<<"\nPlz enter the first sentence :"<<endl; s1.get_string(); cout<<"\nPlz enter the second sentence :"<<endl; s2.get_string(); if(s1==s2) cout<<"\n....Two sentences are same....!!"<<endl; else cout<<"\n oops..!!Dissimilar sentence...\n"<<endl; getch(); return 0; } 1.B.13what is a parameterized constructor? Explain with example. (8)
In C++, Constructor is automatically called when object(instance of class) create.It is special member function of the class.Which constructor has arguments that’s called Parameterized Constructor.
It has same name of class. It must be a public member. No Return Values. Default constructors are called when constructors are not defined for the classes.
Syntax class class-name { Access Specifier: Member-Variables Member-Functions public: class-name(variables) { // Constructor code } ... other Variables & Functions }
Example Program #include<iostream> #include<conio.h> using namespace std; class Example { // Variable Declaration
inta,b; public //Cons Examp // Assi a=x; b=y; cout<< } void D cout<< } }; int main( Exa // Co Obj // W getc retu} 1. B.14w
You can
type of it
Con
>>-+
'-c
>--+
| .-
| V
'---
:
structor ple(intx,int yign Values In
<"Im Constru
Display() { <"Values :"<
() {ample Objectonstructor inect.Display(
Wait For Outpch(); urn 0;
what is a con
define a me
ts class to an
nversion func
+-----------+-
class--::-'
+--------------
---------------
V
-pointer_ope
y) { n Constructo
uctor\n";
<<a<<"\t"<<
{ t(10,20); nvoked. ();
put Screen
nversion fun
mber functio
nother specif
ction syntax
--operator--+
+-const-
'-volatile-'
--------+--(--
---. | '-{-
| |
erator-+-'
or
<b;
nction? How
on of a class
fied type.
+----------+--
----+
-)--+----------
--function_b
w is it create
s, called a co
-conversion_
------------+-
body--}-'
ed? Explain
onversion fun
_type------->
-----><
n its syntax.
nction, that c
>
(8)
converts fromm the
A conversion function that belongs to a class X specifies a conversion from the class type X to
the type specified by the conversion_type. The following code fragment shows a conversion
function called operator int():
class Y {
int b;
public:
operatorint();
};
Y::operator int() {
return b;
}
void f(Y obj) {
int i = int(obj);
int j = (int)obj;
int k = i + obj;
}
All three statements in function f(Y) use the conversion function Y::operator int().
Classes, enumerations, typedef names, function types, or array types cannot be declared or
defined in the conversion_type. You cannot use a conversion function to convert an object of
type A to type A, to a base class of A, or to void.
Conversion functions have no arguments, and the return type is implicitly the conversion type.
Conversion functions can be inherited. You can have virtual conversion functions but not static
ones.
1. B.15Compare and contrast Structured Programming and Object Oriented
Programming. (8)
• Structured programming is based around data structures and subroutines.
• The subroutines are where stuff actually "happens", and the data structures are
simply containers for the information needed by those subroutines.
Object oriented programming, on the other hand, shifts your primary focus to the
data itself.
• Instead of asking "what do I want to do and what will I need to know to do it",
you ask "what kind of things do I want to have and what can those things do for
me".
• Instead of designing your functions first and then coming up with data structures
to support them, you design types first and then come up with the operations
needed to work with them.
1. B.16Distinguish between Data Encapsulation and Data Abstraction. (4)
Data Encapsulation:
• It is a process of bundling the data, and the functions that use them, as a single unit(
atleast in C++) .
• In C++ the data type "class" is used to achieve this.
Data Abstraction:
• It is a process of exposing only the interfaces and hiding the implementation details from
the user.
• The interface exposed will remain the same: even if the internal implementation changes.
• This helps the user to use the new functionality without rewriting the client that was
designed for previous implementation (strictly speaking ... previous interface).
1. B.17 Mention the purpose of Constructor and Destructor functions. (4) Or
• A constructor is responsible for preparing the object for action, and in particular
establishing initial values for all its data, i.e. its data members.
• Although it plays a special role, the constructor is just another member function, and in
particular can be passed information via its argument list that can be used to initialize it.
• The name of the constructor function is the name of the class; that's how C++ knows it’s
a constructor.
• Destructor is a method which is automatically invoked when the object is destroyed.
• It can happen when its lifetime is bound to scope and the execution leaves the scope,
when it is embedded into another object whose lifetime ends, or when it was allocated
dynamically and is released explicitly.
• Its main purpose is to free the resources (memory allocations, open files or sockets,
database connections, resource locks, etc.) which were acquired by the object along its
life cycle and/or deregister from other entities which may keep references to it.
1. B.18 Explain the control structures of C++ with suitable examples. (12)
A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that
serve to specify what has to be done by our program, when and under which circumstances.
{statement1; statement2; statement3 ;}
• If..else
• For loop
• While
• Do…while
• Break statement
• Switch statement
1. B.19 Define function overloading with a simple example. (4)
Function overloading is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters. Consider the following function:
#include<iostream>
usingnamespacestd;
classprintData
{
public:
voidprint(int i){
cout<<"Printing int: "<< i <<endl;
}
voidprint(double f){
cout<<"Printing float: "<< f <<endl;
}
voidprint(char* c){
cout<<"Printing character: "<< c <<endl;
}
};
int main(void)
{
printDatapd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return0;
}
This trivial function adds two integers. However, what if we also need to add two floating point numbers? This function is not at all suitable, as any floating point parameters would be converted
to integers, causing the floating point arguments to lose their fractional values.
1. B.20 Explain the basic Object Oriented concepts. (10)
Refer Q.No. 1.B.1
1. B.21 Write a C++ program that will ask for a temperature in Fahrenheit and display it.
(6) Or
#include<iostream.h> class con { public : float f; float convert() { return (((f-32)/9)*5); } }; int main() { float c; con ob1;
cout<<"Enter Temperature in Fahrenheit : "; cin>>ob1.f; c=ob1.convert(); cout<<"Temperature in Celsius : "<<c; return 0; }
1. B.22 Illustrate the concept of function overloading to find the maximum of two numbers.
(10)
#include <iostream.h>
#include <conio.h>
void main()
{
int sum(int,int); //function with 2 argumentint sum(int,int,int); //function with 3
argumentint sum(int,int,int,int); //function with 4 argumentint sum(int[],int); //function with n
argument
clrscr();
inta,b,c,d,result;
cout<<"\n\nfor 2 argument\n";
cout<<"Enter 2 Integers\n";
cin>>a>>b;
result=sum(a,b);
cout<<"Addition ="<<result;
cout<<"\n\nfor 3 argument\n";
cout<<"Enter 3 Integers\n";
cin>>a>>b>>c;
result=sum(a,b,c);
cout<<"Addition ="<<result;
cout<<"\n\nfor 4 argument\n";
cout<<"Enter 4 Integers\n";
cin>>a>>b>>c>>d;
result=sum(a,b,c,d);
cout<<"Addition ="<<result;
cout<<"\n\nHow many Argument You want to enter:-";
int no;
cin>>no;
intnum[50];
cout<<"Enter "<<no<<" Integers\n";
for(int i=0;i<no;i++)
cin>>num[i];
result=sum(num,no);
cout<<"Addition ="<<result;
getch();
}
//function with 2 argumentintsum(inta,int b)
{
return(a+b);
}
//function with 3 argumentintsum(inta,intb,int c)
{
return(a+b+c);
}
//function with 4 argumentintsum(inta,intb,intc,int d)
{
return(a+b+c+d);
}
//function with n argumentintsum(int a[],int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+a[i];
}
return(sum);
}
1. B.23 what are inline functions? Write a sample code to explain. (6)
Refer Q.No. 1.B.4 b)
1. B.24 Give the syntax and usage of the reserved word inline with two examples. (8)
Refer Q.No. 1.B.4 b)
1. B.25 Explain the importance of constructors and destructors with example. (8) Or
Refer Q.No. 1.B.6 a)iii)
1. B.26 what is operator overloading? Overload the numerical operators ‘+’and ‘/’ for
complex numbers “addition” and “division” respectively. (16)
• In C++ the overloading principle applies not only to functions, but to operators too.
• That is, of operators can be extended to work not just with built-in types but also classes.
• A programmer can provide his or her own operator to a class by overloading the built-in
operator to perform some specific computation when the operator is used on objects of
that class.
#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5){ }
void operator ++() {
count=count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
temp t;
++t; /* operator function void operator ++() is called */
t.Display();
return 0;
}
UNIT 2
2. B.1. Describe the various file modes and its syntax. (6)
In order to open a file with a stream object open() member function is used. open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in Open for input operations.
ios::out Open for output operations. ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
ios::nocreate Open fails if the file does not exist ios::noreplace Open files if the file already exists.
2. B.2Discuss the need for exception with try catch and throw keywords. (10) (Nov/Dec 06)
• Exceptions use the try, catch and throw keywords.
• A throw expression signals the error or exceptional condition. You can use an object of any type as the operand of a throw expression.
• This object is typically used to convey information about the error. Typically, you should use the std::exception class or one of the derived classes that are defined in the standard library, or if none of those are appropriate, then derive your own exception class from std::exception.
• A try block encloses one or more statements that might throw an exception. • One or more catch blocks immediately follow a try block. Each catch block specifies the
type of exception it can handle. • The following syntax shows an example try block and its handlers. Assume that
GetNetworkResource() acquires data over a network connect, and that the two exception types are user-defined classes that derive from std::exception Note that the exceptions are passed by reference in the catch statement:
try { throw CSomeOtherException(); } catch(...) { // Catch all exceptions – dangerous!!! // Respond (perhaps only partially) to exception throw; // Pass exception to some other handler } 2. B.3. Explain the four functions seekg, seekp, tellg tellp used for setting pointers during
file operation and show how they are derived from fstream class. (6)
seekg Sets the position of the get pointer. The get pointer determines the next location to be read in the source associated to the stream. Syntax:
seekg ( position ); Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file). seekg ( offset, direction ); Using this function, the position of the get pointer is set to an offset value relative to some specific point determined by the parameter direction. offset is of the member type off_type, which is also an integer type. And direction is of type seekdir, which is an enumerated type (enum) that determines the point from where offset is counted from. seekp The seekp method changes the location of a stream object's file pointer for output (put or write.) In most cases, seekp also changes the location of a stream object's file pointer for input (get or read.) seekp ( position ); Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file).
seekp ( offset, direction ); Using this function, the position of the put pointer is set to an offset value relative to some specific point determined by the parameter direction. offset is of the member type off_type, which is also an integer type. And direction is of type seekdir, which is an enumerated type (enum) that determines the point from where offset is counted from tellg The tellg() function is used with input streams, and returns the current "get" position of the pointer in the stream. Syntax: pos_type tellg(); It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer.
1. tellp Returns the absolute position of the put pointer. The put pointer determines the location in the output sequence where the next output operation is going to take place. Syntax: pos_type tellp(); The tellp() function is used with output streams, and returns the current "put" position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.
2. B.4 Write a program to append the contents of a file. (10) (Nov/Dec 07) Or
#include<stdio.h> #include<conio.h> void main() { FILE *fp1,*fp2; char ch,fname1[20],fname2[20]; printf("\n enter sourse file name"); gets(fname1); printf("\n enter sourse file name"); gets(fname2); fp1=fopen(fname1,"r"); fp2=fopen(fname2,"a"); if(fp1==NULL||fp2==NULL) { printf("unable to open"); exit(0); }
do { ch=fgetc(fp1); fputc(ch,fp2); } while(ch!=EOF); fcloseall(); }
2.B.5 Write a program to write the text in a file. Display the contents of file in reverse order. (8)
#include<stdio.h> void main() { int i; float f; FILE *ofp; printf("Please enter an integer number\n"); scanf("%d", &i); printf("Please enter a floating point number\n"); scanf("%f", &f); ofp = fopen("exercise3.txt", "w"); fprintf(ofp, "%d \n %f", i, f); }
2. B.6 What are the keywords used in C++ for exception handling ? Describe their usage with suitable examples. (8) (Nov/Dec 07)
• C++ exceptions deal with the relationship of an application and a class member.
• When the application calls the class member and an error occurs, the class member
informs the application of the error.
• The class member has done what is known as throwing an exception.
• The application takes this exception and handles it in a block of code called the catch
block or the exception handler.
• It is in this block of code that the error can be dealt with and the program allowed to
recover from this error.
• Taking a few steps back, the code that originally called the class member had to be
included in a try block.
• The try block makes it possible to return the exception errors to the catch block. It is a
guarded body of code that signifies what code is to return exception errors if they occur.
• Remember that code that does not interact with the class does not have to be in a try
block.
There are three keywords for exception handling in C++:
• try • catch • throw
try
• A try block is a group of C++ statements, normally enclosed in braces { }, which may cause an exception.
• This grouping restricts exception handlers to exceptions generated within the try block.
catch
A catch block is a group of C++ statements that are used to handle a specific raised exception. Catch blocks, or handlers, should be placed after each try block. A catch block is specified by:
• The keyword catch • A catch expression, which corresponds to a specific type of exception that may be thrown
by the try block • A group of statements, enclosed in braces { }, whose purpose is to handle the exception
Throw
The throw statement is used to throw an exception to a subsequent exception handler. A throw statement is specified with:
• The keyword throw • An assignment expression; the type of the result of the expression determines which
catch exception handler receives control.
#include<stdio.h> sing namespace std; int main() { void func() { try { throw 1;
} catch(int a) { cout << "Caught exception number: " << a << endl; return; } cout << "No exception detected!" << endl; return; }} 2. B.7 Write a program using get and getline member function to explain stream input. (8)
#include <iostream>
#include <fstream>
using namespace std;
int main () {
char c, str[256];
ifstream is;
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
is.open (str); // open file
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
is.close(); // close file
return 0;
}
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
2. B.8 Write a program using sequential file access to maintain and access employee pay roll. (8) (Nov/Dec 08)
2. B.9 Define friend class and specify its importance. Explain with Suitable example. (8)
A friend class in C++, can access the "private" and "protected" members of the class in which it is declared as a friend.
On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared.
Friend status is not inherited; every friendship has to be explicitly declared. Friend classes can help in improving Encapsulation if used wisely.
#include <iostream> class B { // B declares A as a friend... friendclass A; private: void privatePrint() { std::cout<<"hello, world"<< std::endl;
} }; class A { public: A() { B b; // ... and A now has access to B's private members b.privatePrint(); } }; int main() { A a; return0; } 2. B.10 Discuss Virtual function and polymorphism with example. (8) Or (Ap/May 10) #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () {
CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout<< rect.area() << endl; cout<< trgl.area() << endl; return 0; }
A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.
Class A { int a; public: A() { a = 1; } virtual void show() { cout <<a; } };
Class B: public A { int b; public: B() { b = 2; } virtual void show() { cout <<b; } };
int main() {
A *pA; B oB; pA = &oB; pA->show(); return 0; }
2. B.11 Explain the concept of inheritance by considering an example of “vehicle”. (8) • The term inheritance refers to the fact that one class can inherit part or all of its structure
and behavior from another class.
• The class that does the inheriting is said to be a subclass of the class from which it
inherits. If class B is a subclass of class A, we also say that class A is a superclass of class
B. (Sometimes the terms derived class and base class are used instead of subclass and
superclass; this is the common terminology in C++.)
• A subclass can add to the structure and behavior that it inherits. It can also replace or
modify inherited behavior (though not inherited structure).
• The relationship between subclass and superclass is sometimes shown by a diagram in
which the subclass is shown below, and connected to, its superclass, as shown in the
illustration to the right.
class Vehicle { int registrationNumber; Person owner; // (Assuming that a Person class has been defined!) void transferOwnership(Person newOwner) { . . . } . . . } class Car extends Vehicle { int numberOfDoors; . . . } class Truck extends Vehicle { int numberOfAxles; . . . } class Motorcycle extends Vehicle { boolean hasSidecar; . . .
} 2. B.12 Explain the operators used for dynamic memory allocation with examples. (8)
• At times, you will have classes for which you want to specialize memory allocation.
Why? You know something about how the class is used.
• For instance, you might specialize memory allocation for a class in order to squeeze some
extra performance out of your program.
• Suppose you have a linked list and you want to speed up the allocation of new nodes.
• One way to do this is to maintain a list of deleted nodes, whose memory can be reused
when new nodes are allocated.
• Instead of using the default new and delete, new will be overloaded to try to get a node
from the list of deleted nodes; only if no deleted nodes are available would it dynamically
allocate memory.
• Delete will simply add the node to the deleted nodes. This way instead of allocating new
memory from the heap (which is pretty time consuming) we will use the already allocated
space. The technique is usually called caching.
class Myclass { public: void* operator new(size_t); void operator delete(void*); }; void* Myclass::operator new(size_t size) { void *storage = malloc(size); if(NULL == storage) { throw "allocation fail : no free memory"; } } 2. B.13 Describe the syntax of multiple inheritance. When do we use such an inheritance? (10)
class AbsBase { virtual void init() = 0; virtual void work() = 0; } class AbsInit : public AbsBase { void init() { do_this(); }
// work() still abs } class AbsWork : public AbsBase { void work() { do_this(); } // init() still abs } class NotAbsTotal : public AbsInit, public AbsWork { // Nothing, both should be defined } 2.B.14 What is a virtual function? When do we make a virtual function ‘‘pure’’? (6) Or (Nov/Dec 9)
• A virtual function is a member function that is declared within a base class and redefined
by a derived class.
• To create virtual function, precede the function’s declaration in the base class with the
keyword virtual.
• When a class containing virtual function is inherited, the derived class redefines the
virtual function to suit its own needs.
• Base class pointer can point to derived class object. In this case, using base class pointer
if we call some function which is in both classes, then base class function is invoked.
• But if we want to invoke derived class function using base class pointer, it can be
achieved by defining the function as virtual in base class, this is how virtual functions
support runtime polymorphism.
Consider following program code:
Class A { int a; public: A() { a = 1; } virtual void show() { cout <<a; } };
Class B: public A { int b; public: B() { b = 2; } virtual void show() { cout <<b; } };
int main() { A *pA; B oB; pA = &oB; pA->show(); return 0; }
2.B.15 What is a file mode? Describe the various file mode options available. (8)
Mode Description ios::ate Write all output to the end of file (even if file
position pointer is moved with seekp) ios::app Open a file for output and move to the end of the
existing data (normally used to append data to a file, but data can be written anywhere in the file
ios::in The original file (if it exists) will not be truncated ios::out Open a file for output (default for ofstream objects)ios::trunc Discard the file's contents if it exists (this is also the
default action for ios::out, if ios::ate, ios::app, or ios::in are not specified)
ios::binary Opens the file in binary mode (the default is text mode)
ios::nocreate Open fails if the file does not exist ios::noreplaceOpen files if the file already exists.
2. B.16 what is an exception? How is an exception handled in C++? (8)
Refer Q.No 2.B.2
2. B.17 Differentiate inheritance from polymorphism. (6)
Refer Q.No 2.B.10, 2.B.10,
2. B.18 Write a C++ program to illustrate the concept of hierarchical inheritance. (10)
Or (Nov/Dec 10)
Hierarchical inheritance is a is a method of inheritance where one or more derived classes are
derived from common base class.
Example:
#include<iostream>
class Side
{
protected:
int l;
public:
void set_values (int x)
{ l=x;}
};
class Square: public Side
{
public:
int sq()
{ return (l *l); }
};
class Cube:public Side
{
public:
int cub()
{ return (l *l*l); }
};
int main ()
{
Square s;
s.set_values (10);
cout << "The square value is::" << s.sq() << endl;
Cube c;
c.set_values (20);
cout << "The cube value is::" << c.cub() << endl;
return 0;
}
2. B.19 what is the use of template? Write an overloaded function template
called max( ), which will find the maximum of any two given integers. (8)
• If you call the name of an overloaded function template, the compiler will try to deduce its template arguments and check it’s explicitly declared template arguments.
• If successful, it will instantiate a function template specialization, and thenadds this specialization to the set of candidate functions used in overload resolution.
• The compiler proceeds with overload resolution, choosing the most appropriate function from the set of candidate functions.
• Non-template functions take precedence over template functions. The following example describes this:
#include <iostream> using namespace std; template<class T> void f(T x, T y) { cout << "Template" << endl; } void f(int w, int z) { cout << "Non-template" << endl; } int main() { f( 1 , 2 ); f('a', 'b'); f( 1 , 'b'); }
The following is the output of the above example:
Non-template Template
2. B.20 Explain the exception handling mechanism of C++ in detail. (8)
Refer Q.No 2.B.16
2. B.21 Create a class that contains one data member. Overload all the four arithmetic
operators so that they operate on the objects of that class. (10)
#include<iostream.h> #include<conio.h> class FLOAT { float no; public: FLOAT(){} void getdata() { cout<<"\n ENTER AN FLOATING NUMBER :"; cin>>no; } void putdata() { cout<<"\n\nANSWER IS :"<<no; } FLOAT operator+(FLOAT); FLOAT operator*(FLOAT); FLOAT operator-(FLOAT); FLOAT operator/(FLOAT); }; FLOAT FLOAT::operator+(FLOAT a) { FLOAT temp; temp.no=no+a.no; return temp; } FLOAT FLOAT::operator*(FLOAT b) { FLOAT temp; temp.no=no*b.no; return temp; } FLOAT FLOAT::operator-(FLOAT b) { FLOAT temp; temp.no=no-b.no; return temp; } FLOAT FLOAT::operator/(FLOAT b) {
FLOAT temp; temp.no=no/b.no; return temp; } main() { clrscr(); FLOAT a,b,c; a.getdata(); b.getdata(); c=a+b; cout<<"\n\nAFTER ADDITION OF TWO OBJECTS"; c.putdata(); cout<<"\n\nAFTER MULTIPLICATION OF TWO OBJECTS"; c=a*b; c.putdata(); cout<<"\n\nAFTER SUBSTRACTION OF TWO OBJECTS"; c=a-b; c.putdata(); cout<<"\n\nAFTER DIVISION OF TWO OBJECTS"; c=a/b; c.putdata(); getch(); }
2. B.22 Describe the syntax of the different forms of inheritance in C++.(6) Or
(Nov/Dec 11)
Base & Derived Classes: #include<iostream> usingnamespace std; // Base class classShape { public: void setWidth(int w) { width= w; } void setHeight(int h) { height= h;
} protected: int width; int height; }; // Derived class classRectangle:publicShape { public: int getArea() { return(width * height); } }; int main(void) { RectangleRect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout<<"Total area: "<<Rect.getArea()<< endl; return0; }
Access Control and Inheritance:
Access public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no
Type of Inheritance:
• Public Inheritance
• Protected Inheritance
• Private Inheritance:
• Multiple Inheritances:
Let us try the following example:
#include<iostream> usingnamespace std; // Base class Shape classShape { public: void setWidth(int w) { width= w; } void setHeight(int h) { height= h; } protected: int width; int height; }; // Base class PaintCost classPaintCost { public: int getCost(int area) { return area *70; } }; // Derived class classRectangle:publicShape,publicPaintCost { public: int getArea() { return(width * height); } }; int main(void) {
RectangleRect; int area; Rect.setWidth(5); Rect.setHeight(7); area=Rect.getArea(); // Print the area of the object. cout<<"Total area: "<<Rect.getArea()<< endl; // Print the total cost of painting cout<<"Total paint cost: $"<<Rect.getCost(area)<< endl; return0; }
2. B.23 what are virtual functions? Explain with a suitable program.(10)
Refer Q.No. 2.B.10
2. B.24 what is dynamic binding? How is it achieved? (6)
• Dynamic binding means that the address of the code in a member function invocation is
determined at the last possible moment: based on the dynamic type of the object at run
time.
• It is called "dynamic binding" because the binding to the code that actually gets called is
accomplished dynamically (at run time).
• Dynamic binding is a result of virtual functions.
When you have a pointer to an object, the object may actually be of a class that is derived from the class of the pointer (e.g., a Vehicle* that is actually pointing to a Car object; this is called "polymorphism"). Thus there are two types: the (static) type of the pointer (Vehicle, in this case), and the (dynamic) type of the pointed-to object (Car, in this case).
Static typing means that the legality of a member function invocation is checked at the earliest possible moment: by the compiler at compile time. The compiler uses the static type of the pointer to determine whether the member function invocation is legal. If the type of the pointer can handle the member function, certainly the pointed-to object can handle it as well. E.g., if Vehicle has a certain member function, certainly Car also has that member function since Car is a kind-of Vehicle.
2. B.25 Define friend function. What is polymorphism? Explain multiple inheritances.
(16)Or(Nov/Dec 12)
Refer Q.No. 2.B.9, 2.B.10, 2.B.11,2.B13.
2. B.26 what is string? Write a C++ program to sort the given strings in alphabetical. (16)
• Strings are objects that represent sequences of characters. • The standard string class provides support for such objects with an interface similar to
that of standard containers, but adding features specifically designed to operate with strings of characters.
• The string class is an instantiation of the basic_string class template that uses char as the character type, with its default char_traits and allocator types (see basic_string for more info on the template). #include <stdlib.h>
#include<iostream.h> #include<string.h> int main (void) { char string[128], temp; int n, i, j; printf("\nEnter string: "); gets(string); n = strlen(string); for (i=0; i<n-1; i++) { for (j=i+1; j<n; j++) { if (string[i] > string[j]) { temp = string[i]; string[i] = string[j]; string[j] = temp; } } } printf("\n%s", string); printf("\n"); return 0; }
UNIT 3
3. B.1. Find the average search cost of the binary search algorithm. ? (Nov/Dec 05)
Binary search can interact poorly with the memory hierarchy (i.e. caching), because of its random-access nature. For in-memory searching, if the span to be searched is small, a linear search may have superior performance simply because it exhibits better locality of reference. For external searching, care must be taken or each of the first several probes will lead to a disk seek. A common method is to abandon binary searching for linear searching as soon as the size of the remaining span falls below a small value such as 8 or 16 or even more in recent computers. The exact value depends entirely on the machine running the algorithm.
3. B.2 Give the procedure to convert an infix expression a+b* c+ (d * e + f) * g to postfix
notation. (Nov/Dec 05) Or
1. Initialise the stack to be empty. 2 For each character in the infix string if operand append to output else if stack empty or the operator has higher precedence than the operator on top of the stack then push it onto the stack else pop the stack and append it to the output 3. If input end encountered then loop until stack not empty pop the stack and append to the output.
3. B.3 Write a routine to insert an element in a linked list. (Nov/Dec 05)
• Assuming your new element is e and the list is L: - Find the node in L that you want to precede e, lets call it x, and the node following it y. So right now your list looks like:
• L->L+1->....->x->y->y+1->...->NULL • e->NULL
• Modify e's next pointer to point to x->next (in this case this equals y), so both x and e point to y
• L->L+1->....->x->y->y+1->...->NULL • e->y • Modify x's next pointer to point to e: • L->L+1->....->x->e->y->y+1->...->NULL
3. B.4. What is the stack ADT? Give any one implementation of stack and explain clearly
the data structure and routines are used. (Nov/Dec 06) Or
#include<iostream> #include<conio.h> #include<stdlib.h> using namespace std; class node { public: class node *next; int data; }; class stack : public node { node *head; int tos; public: stack() { tos=-1; } void push(int x) { if (tos < 0 ) { head =new node; head->next=NULL; head->data=x; tos ++; } else { node *temp,*temp1; temp=head; if(tos >= 4) { cout<<"stack over flow";
return; } tos++; while(temp->next != NULL) temp=temp->next; temp1=new node; temp->next=temp1; temp1->next=NULL; temp1->data=x; } } void display() { node *temp; temp=head; if (tos < 0) { cout <<" stack under flow"; return; } while(temp != NULL) { cout<<temp->data<< " "; temp=temp->next; } } void pop() { node *temp; temp=head; if( tos < 0 ) { cout<<"stack under flow"; return; } tos--; while(temp->next->next!=NULL) { temp=temp->next; } temp->next=NULL; } }; main() { stack s1;
int ch; while(1) { cout<<"\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n enter ur choice:"; cin>> ch; switch(ch) { case 1: cout <<"\n enter a element"; cin>> ch; s1.push(ch); break; case 2: s1.pop();break; case 3: s1.display(); break; case 4: exit(0); } } return (0); } 3. B.5 How does Queue work? Explain the algorithm for inserting and deleting from a
Queue. (Nov/Dec 06)
In computer science, a queue is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed. Often a peek or front operation is also implemented, returning the value of the front element without dequeuing it. A queue is an example of a linear data structure, or more abstractly a sequential collection.
Algorithm for Insertion:-
Step-1: If “rear” of the queue is pointing to the last position then go to step-2 or else step-3 Step-2: make the “rear” value as 0 Step-3: increment the “rear” value by one Step-4:
if the “front” points where “rear” is pointing and the queue holds a not NULL value for it, then its a “queue overflow” state, so quit; else go to step-4.2 insert the new value for the queue position pointed by the “rear”.
Step-5:EXIT.
Algorithm for deletion:-
Step-1: If the queue is empty then say “empty queue” and quit; else continue Step-2: Delete the “front” element Step-3: If the “front” is pointing to the last position of the queue then step-4 else step-5 Step-4: Make the “front” point to the first position in the queue and quit Step-5: Increment the “front” position by one Step-6:EXIT.
3. B.6 Write a routine to implement a queue using arrays and to enqueue an element into it.
Or (Nov/Dec 07)
public class CircularQueue { private int size; private int head; private int tail; private int q[]; public CircularQueue(int s) { size = s; q = new int[s+1]; head = 0; tail = 0; } public synchronized void initialize() { head = 0; tail = 0; } public synchronized boolean enqueue(int v) { int tmp = (tail+1) % size; if (tmp == head) return false; q[tail] = v; tail = tmp; return true; } public synchronized int dequeue() throws Exception{ if (head == tail) throw new Exception("queue underflow!"); int tmp = q[head];
head = (head + 1) % size; return tmp; }
}
3. B.7 Delete the first occurrence of an element Y from the list. Trace the routine with an
example.
3. B.8 Explain Priority Queues and how are binary heaps used in that. (8)
• Definition of Priority queue • Types:Ascending and Descending priority queue • Array Implementation of priority queue
3. B.9 Explain the properties of heap. (8) Or (Ap/May 10)
Two Properties of a Heap:
I Shape Property: left-complete binary tree
I Order Property: max-heap: A[Parent(i)] _ A[i]
Max-Heapify used to maintain max-heap property.
I Before Max-Heapify, A[i] may be smaller that its children.
I Assume left and right subtrees of i are max-heaps.
Before Max-Heapify, A[i] may be smaller that its children.
I Assume left and right subtrees of i are max-heaps.
I After Max-Heapify, subtree rooted at i is a max-heap.
I Time: O(lg n)
Max-Heapify(A; i; n
3. B.10 Write a C ++ program to implement Stack and its operations PUSH and POP. (10)
#include <stdio.h> #include <conio.h> #define MAXSIZE 5 struct stack /* Structure definition for stack */ { int stk[MAXSIZE]; int top; }; typedef struct stack STACK; STACK s; /* Function declaration/Prototype*/
void push (void); int pop(void); void display (void); void main () { int choice; int option = 1; clrscr (); s.top = -1; printf ("STACK OPERATION\n"); while (option) { printf ("------------------------------------------\n"); printf (" 1 --> PUSH \n"); printf (" 2 --> POP \n"); printf (" 3 --> DISPLAY \n"); printf (" 4 --> EXIT \n"); printf ("------------------------------------------\n"); printf ("Enter your choice\n"); scanf ("%d", &choice); switch (choice) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: return; } fflush (stdin); printf ("Do you want to continue(Type 0 or 1)?\n"); scanf ("%d", &option); } } /*Function to add an element to the stack*/ void push () { int num; if (s.top == (MAXSIZE - 1)) { printf ("Stack is Full\n"); return; } else
} 3. B.11 W
• T
ar
• If
ar
ca
• W
lo
• S
• W
ru
• S
g
• D• S• M• D• M• F• P
{ pr sc s.t s.} return;
What is hash
The problem
rray for a giv
f the array is
rray. If the a
ase runtime
We could se
ocated in the
uppose we d
With this ma
untime O(1)
uch a functi
iven a key, g
Direct methodubtraction m
Modulo-DiviDigit-ExtractMid-Square m
olding methseudo-rando
rintf ("Enter canf ("%d", &top = s.top +stk[s.top] =
hing? Class
at hands is
ven value.
s not sorted,
array is sorte
complexity
arch even f
e array.
do have that
agic function
.
ion is called
generates an
d, method, sion methodion method,
method, hod, om method.
the element&num); + 1; num;
ify hashing
s to speed u
the search m
ed, we can u
to O(log n).
faster if we
magic funct
n our search
d a hash fun
n address in t
d,
t to be pushe
functions b
up searching
might require
se the binary
know in ad
tion that wou
h is reduced
nction . A h
the table.
ed\n");
based on the
g. Consider t
e examining
y search, and
dvance the i
uld tell us th
d to just one
hash functio
e various m
the problem
g each and al
d therefore r
index at wh
he index for a
e probe, givi
on is a func
ethods. (6)
m of searchin
ll elements o
reduce the w
hich that val
a given valu
ing us a con
tion which w
ng an
of the
worse-
lue is
ue.
nstant
when
3. B.12 Explain the operations performed on queue in detail. Write a C++ program to
implement these queue operations. (10)
• Queue is the concept used in data structures. It is also referred to the linear data structure
as the object or item can be added in one terminal and the item can be retrieved from the
other end.
• Item, which is added to one end, is called as REAR and the item that is retrieved from
the other end is called as FRONT.
• Queue is used in array as well as in linked list of the computer programs mainly used by
the programmers.
• Queue follows the concept of FIFO (First-In-First-Out) . It means that the items, which
are enters first will be accessed or retrieved first.
Queue Operations The following are operations performed by queue in data structures
� Enqueue (Add operation)
� Dequeue (Remove operation)
� Initialize.
#include<stdio.h> #include<conio.h> int q[5],front=-1,rear=-1,max=5; void print() { int i; if(front==-1) printf("QUEUE EMPTY"); else { if(front<=rear) for(i=front;i<=rear;i++) printf(" %d ",q[i]); else { for(i=0;i<=rear;i++) printf(" %d ",q[i]); for(i=front;i<max;i++) printf(" %d ",q[i]); } }
} void insertrear() { if((front==rear+1)||((front==0)&&(rear==max-1))) printf("QUEUE IS FULL"); else { if(rear==max-1) rear=0; else rear++; if(front==-1) front++; printf("ENTER THE ELEMENT TO BE INSERTED :"); scanf("%d",&q[rear]); printf("\ QUEUE AFTER INSERTION :"); print(); } } void delbeg() { if(front==-1) printf("QUEUE EMPTY"); else { printf("ELEMENT DELETED : %d",q[front]); if(front==rear) { front=-1; rear=-1; } else if(front==max-1) front=0; else front++; printf("\ QUEUE AFTER DELETION :"); print(); } } void insertbeg() { if((front==rear+1)||((front==0)&&(rear==max-1)))
printf("QUEUE IS FULL"); else { if(front==-1) { front++; rear++; } else if(front==0) front=max-1; else front--; printf("ENTER THE ELEMENT TO BE INSERTED :"); scanf("%d",&q[front]); printf("\ QUEUE AFTER INSERTION :"); print(); } } void delrear() { if(front==-1) printf("QUEUE EMPTY"); else { printf("ELEMENT DELETED : %d",q[rear]); if(front==rear) { front=-1; rear=-1; } else if(rear==0) rear=max-1; else rear--; printf("\ QUEUE AFTER DELETION :"); print(); } } void main() { int ch; clrscr(); do {
printf("\nFRONT\printf("\nscanf("%switch(ch{ case 1:inbreak; case 2:inbreak; case 3:debreak; case 4:debreak; default :pbreak; } }while(chgetch(); } 3. B.13 E
• A
Example
• Ifatelw
Operatio
• In• D• D
n1) INSERT\n4.DELETIn ENTER CH
%d",&ch); h)
sertbeg();
sertrear();
elbeg();
elrear();
printf("WRO
h>=1&&ch<
Explain inse
A min-max h
of Min-max
f it is not emt min level. Llement in x h
with root x. A
ons on Min-
nserting an eDeletion of laDeletion of sm
ION AT FRON AT REAHOICE ");
ONG CHOIC
<=4);
ertion, delet
heap is a com
x heap
mpty, each eleLet x be anyhas the mini
A node on a m
-Max
element withargest key mallest key
RONT \n2)INAR\n ");
CE");
tion and rep
mplete binary
ement has a y node in a mmum (maximmin (max) le
h an arbitrary
NSERTION A
placement of
y tree contain
data membemin-max heapmum) key frevel is called
y key
AT REAR\n
f nodes in a
ning alternat
er called keyap. If x is on rom among ad a min (max
n3.DELETE
a heap. (6) O
ting min and
y. The root isa min (max)all elements x) node.
EION AT
Or (Nov/Dec
d max levels
s always pres) level then tin the subtre
c 10)
.
sent the ee
Inserting an element with an arbitrary key
To add an element to a Min-Max Heap perform following operations:
Insert the required key into given Min-Max Heap.
Compare this key with its parent if it is found to be smaller (greater) compared to its parent, then it is surely smaller (greater) than all other keys present at nodes at max(min) level that are on the path from the present position of key to the root of heap. Now, just check for nodes on Min(Max) levels.
If the key added is in correct order then stop otherwise swap that key with its parent.
3. B.14 what are the advantages of linked list over array? (4)
1. Linked lists do not need contiguous blocks of memory; extremely large data sets stored in an array might not be able to fit in memory.
2. Linked list storage does not need to be preallocated (again, due to arrays needing contiguous memory blocks).
3. Inserting or removing an element into a linked list requires one data update, inserting or removing an element into an array requires n (all elements after the modified index need to be shifted).
3. B.15 Define Hashing. (2)
Refer 3.B.11
3. B.16 Write a C++ program to implement stack through linked list. (10)
Refer 3.B.4
3. B.17 Define double linked list. Explain the various operations of double linked list with
algorithm. (16) Or (Nov/Dec 09)
• A doubly linked list is a linked data structure that consists of a set of sequentially linked
records called nodes.
• Each node contains two fields, called links, that are references to the previous and to the
next node in the sequence of nodes.
• The beginning and ending nodes' previous and next links, respectively, point to some
kind of terminator, typically a sentinel node or null, to facilitate traversal of the list.
• If there is only one sentinel node, then the list is circularly linked via the sentinel node.
• It can be conceptualized as two singly linked lists formed from the same data items, but
in opposite sequential orders.
Operations of double linked list
• Insertion
• Deletion
• Traversing
3. B.18 What is hashing? Explain the various hash functions with example. (10)
Refer 3.B.11
3. B.19 What is priority queue? Discuss the array implementation of priority queue. (6)
Refer 3.B.8
3. B.20 Explain the features of I/O system supported in C++. (10)
iostream is a header file which is used for input/output in the C++ programming language. It is
part of the C++ standard library. The name stands for Input/Output Stream. In C++ and its
predecessor, the C programming language, there is no special syntax for streaming data input or
output. Instead, these are combined as a library of functions. Like the cstdio header inherited
from C's stdio.h, iostream provides basic input and output services for C++ programs. iostream
uses the objectscin, cout, cerr, and clog for sending data to and from the standard streams input,
output, error (unbuffered), and log (buffered) respectively. As part of the C++ standard library,
these objects are a part of the stdnamespace.[
3. B.21 Write a program containing a possible exception. Use a try block and throw it and a
catch block to handle it properly. (6) Or (Nov/Dec 11)
Refer 2.B.20
3. B.22 Write a program that reads a name from the keyboard into three separate string
objects and then concatenates them into a new string object using ‘+’ operator and
append() function. (10)
3. B.23 List the major categories of containers supported by STL. (6)
The Standard Template Library (STL) is a C++software library that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functional, and iterators.[1]
The STL provides a ready-made set of common classes for C++, such as containers and associative arrays, that can be used with any built-in type and with any user-defined type that supports some elementary operations (such as copying and assignment). STL algorithms are independent of containers, which significantly reduces the complexity of the library.
The STL
polymorp
C++comp
3. B.24 E
3. B.25 W
UNIT 4
4. B.1. D
12) (Nov
• Dpr
• TG
• Fco
• Idv
• Fdrca
• An
• D(wimth
• Tar
4. B.2Wi
• In
p
L achieves its
phism that is
pilers are tun
Explain the
Write algori
Describe the
v/De 07)
Dijikstra’s iroblem for a
This algorithmGPS technolo
or a given sost (i.e. the sIt can also bestination vertex has be
For exampleriving distanan be used to
As a result, otably IS-IS
Dijkstra's oriwhere is mplemented he number o
This is asymrbitrary direc
ith example
n computer
osition of a
s results thro
s often more
ned to minim
operation o
ithm for ins
e shortest pa
is a graph a graph with m is often uogy. source verteshortest pathbe used for vertex by stoen determine
e, if the vertnces betweeno find the shthe shortest
S and OSPF (
iginal algorithe number by a Fibon
f edges) is dmptotically cted graphs
e explains th
science, a
specified va
ough the use
efficient tha
mize any abs
of binary he
R
sertion and
R
ath identific
search algonon-negativ
used in routi
x (node) in h) between thfinding costopping the aed. tices of the gn pairs of ci
hortest route t path first i(Open Short
ithm does nof vertices)
acci heap andue to (Fredm
the fastest with unboun
he binary se
binary sea
lue (the inpu
of templates
an traditiona
straction pen
ap. Or (Nov
Refer 3.B.8
deletion in l
Refer 3.B.3
cation using
orithm that ve edge path ing as a sub
the graph, that vertex ants of shortesalgorithm on
graph represities connectbetween oneis widely utest Path Firs
not use a mi. The implemnd running iman & Tarja
known sinnded non-neg
earch techni
arch or ha
ut "key") wit
s. This appro
al run-time p
nalty arising
v/Dec 12)
linked stack
g dijikstra’s
solves the costs, produ
broutine in o
the algorithmnd every othst paths fromnce the sho
sent cities anted by a diree city and al
used in netwst).
in-priority qmentation bin
an 1984). ngle-source gative weigh
ique.
lf-interval
thin a sorted
oach provide
polymorphism
from heavy
k.
s algorithm.
single-sourucing a shortother graph
m finds the er vertex.
m a single vortest path to
nd edge patect road, Dijll other cities
work routing
queue and rased on a m
shortest-pathts.
search algo
d array.
es compile-t
m. Modern
use of the S
Or (Nov/D
rce shortest test path treealgorithms,
path with lo
vertex to a so the destin
th costs reprjkstra's algors. g protocols,
runs in min-priority q
(where
th algorithm
orithm find
time
STL.
ec
path e. or in
owest
single nation
resent rithm
most
queue is
m for
s the
• I
m
• I
re
• O
re
gr
• I
th
In each step
middle eleme
If the keys m
eturned.
Otherwise, if
epeats its act
reater, on th
If the remain
he array and
p, the algori
ent of the arr
match, then
f the sought
tion on the s
e sub-array t
ning array to
a special "N
ithm compar
ray.
a matching
key is less
sub-array to
to the right.
o be searched
Not found" in
res the inpu
element has
than the m
the left of t
d is reduced
ndication is r
ut key value
s been found
middle eleme
the middle e
d to zero, the
returned.
e with the k
d so its inde
ent's key, th
element or, i
en the key ca
key value o
ex, or positio
hen the algor
f the input k
annot be fou
of the
on, is
rithm
key is
und in
4. B.3 Traverse the tree given below using Inorder, Preorder and Postorder traversals. (10)
Pre-order:
• Visit the root. • Traverse the left subtree. • Traverse the right subtree.
In-order (symmetric):
• Traverse the left subtree. • Visit the root. • Traverse the right subtree.
Post-order:
• Traverse the left subtree. • Traverse the right subtree. • Visit the root.
4. B.4 Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and
postfix notations. (6) Or (Ap/May 10)
• Prefix Notation:
^ – * +ABC – DE + FG
• Postfix Notation:
AB + C * DE – - FG + ^
4. B.5 Convert the given graph with weighted edges to minimal spanning tree. (10)
4. B.6 Write a short note on AVL trees. (6)
AVL Trees The Concept
• These are self-adjusting, height-balanced binary search trees and are named after the inventors: Adelson-Velskii and Landis.
• A balanced binary search tree has Theta(lg n) height and hence Theta(lg n) worst case lookup and insertion times.
• However, ordinary binary search trees have a bad worst case. • When sorted data is inserted, the binary search tree is very unbalanced, essentially more
of a linear list, with Theta(n) height and thus Theta(n) worst case insertion and lookup times. AVL trees overcome this problem.
Definitions The height of a binary tree is the maximum path length from the root to a leaf. A single-node binary tree has height 0, and an empty binary tree has height -1. As another example, the following binary tree has height 3. 7 / \ 3 12 / / \ 2 10 20 / \ 9 11
4. B.7 Discuss the different methods of traversing a binary tree with algorithm.(16) Or
(Nov/Dec 09)
BinaryTreeTraversal
• There are many operations that we often want to perform on trees. One notion that arises frequently is the idea of traversing a tree or visiting each node in the three exactly once.
• A full traversal produces a linear order for the information in a tree. • This linear order may be familiar and useful. When traversing a binary tree we want treat
each node and its subtrees in the same fashion. • If we let L, D, R stand for moving left, printing the data, and moving right when at a node
then there are six possible combinations of traversal: LDR, LRD, DLR, DRL, RDL, and RLD.
• If we adopt the convention that we traverse left before right then only three traversals remain: LDR, LRD, and DLR.
• To these we assign the names inorder, postorder and preorder because there is a natural correspondence between these traversals and producing the infix, postfix and prefix forms of an expression.
• Inorder Traversal: informally this calls for moving down the tree towards the left untilyou can go no farther.
• Then you "visit" the node, move one node to the right and continue again. If you cannot move to the right, go back one more node.
• A precise way of describing this traversal is to write it as a recursive procedure. procedure inorder(currentnode:treepointer); {currentnode is a pointer to a noder in a binary tree. For full tree traversal, pass inorder the pointer to the top of the tree} begin {inorder}
if currentnode <>nil then begin inorder(currentnode^.leftchild); write(currentnode^.data); inorder(currentnode^.rightchild); end end; {of inorder}
Recursion is an elegant device for describing this traversal. A second form of traversal is preorder: procedurepreorder(currentnode:treepointer); {currentnode is a pointer to a node in a binary tree. For full tree traversal, pass preorder the ponter to the top of the tree} begin {preorder} if currentnode <> nil then begin write(currentnode^.data); preorder(currentnode^.leftchild); preorder(currentnode^.rightchild); end {of if} end; {of preorder}
4. B.8 Discuss Prim’s and Kruskal’s algorithm for computing the minimal spanning tree
weighted undirected graph. (16)
• In computer science, Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connectedweightedundirected graph.
• This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.
• The algorithm was developed in 1930 by Czech mathematician Vojtěch Jarník and later independently by computer scientist in 1957 and rediscovered by Edsger Dijkstra in 1959. Therefore it is also sometimes called the DJP algorithm, the Jarník algorithm, or the Prim–Jarník algorithm.
• Other algorithms for this problem include Kruskal's algorithm and Borůvka's algorithm. However, these other algorithms can also find minimum spanning forests of disconnected graphs, while Prim's algorithm requires the graph to be connected.
• If a graph is empty then we are done immediately. Thus, we assume otherwise.
The algorithm starts with a tree consisting of a single vertex, and continuously increases its size one edge at a time, until it spans all vertices.
• Input: A non‐empty connected weighted graph with vertices V and edges E (the weights can be negative).
• Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V, Enew = {} • Repeat until Vnew = V:
o Choose an edge {u, v} with minimal weight such that u is in Vnew and v is not (if there are multiple edges with the same weight, any of them may be picked)
o Add v to Vnew, and {u, v} to Enew • Output: Vnew and Enew describe a minimal spanning tree
4. B.9 Write an algorithm to traverse binary tree level by level, with each level of the tree
being traversed from left to right. (10)
Refer Q.No. 4.B.3
4. B.10 Explain spanning tree and minimal spanning tree with examples.(6)Or (Nov/Dec
10)
Refer Q.No. 4.B.8
4. B.11 Define AVL tree. Explain the operations on AVL tree with illustrations. (6)
Refer Q.No. 4.B.6
4. B.12 Explain breadth first search algorithm for the traversal of any graph with suitable
examples. Define time complexity of the algorithm. (10)
• In graph theory, breadth-first search (BFS) is a strategy for searching in a graph when
search is limited to essentially two operations: (a) visit and inspect a node of a graph; (b)
gain access to visit the nodes that neighbor the currently visited node.
• The BFS begins at a root node and inspects all the neighboring nodes.
• Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which
were unvisited, and so on.
• Compare BFS with the equivalent, but more memory-efficient Iterative deepening depth-
first search and contrast with depth-first search.
The algorithm uses a queue data structure to store intermediate results as it traverses the graph, as follows:
1. Enqueue the root node 2. Dequeue a node and examine it
o If the element sought is found in this node, quit the search and return a result. o Otherwise enqueue any successors (the direct child nodes) that have not yet been
discovered. 3. If the queue is empty, every node on the graph has been examined – quit the search and
return "not found".
4. If
Time com
The time
will be edependin
4. B.13 D
(10)
* This is a Save this*/ class We { // A java pub { } } For those
Suppose
Compilin
After we
use the c
Go to the
c:\>javac
The java
These by
bytecode
program
command
c:\>java W
So the ou
Welcome
f the queue i
mplexity
e complexity
explored in ng on how sp
Describe the
sample javas file as Welc
elcome
a program wlic static voi System.out.p
e who are us
if you are en
ng the prog
have writte
ompiler call
e command p
c Welcome.j
ac compiler
ytecodes hav
es into mach
in order to g
d line type a
Welcome
utput will be
e to Java-Sam
s not empty,
y can be ex
the worst cparse the inp
e structure o
a program come.java
ill start fromid main(Strin
println(" W
ing the IDE,
ntering your
gram
n our progra
ed javac wh
prompt and t
ava
will create a
ve to be inte
hine codes. O
get the outpu
as shown her
displayed a
mples!!!
, repeat from
xpressed as
case. Note: put graph is (
of a typical
m here. ng args[])
elcome to Ja
, you can fol
r program in
am we need
ich is provid
type the file
a class file
erpreted by
Once we suc
ut. So this c
re.
as
m Step 2.
ma(assuming th
Java progr
ava-Samples
llow the inst
notepad, the
to compile a
ded by java.
name as sho
called Welc
a Java Virtu
ccessfully co
an be done b
since e
ay vary betwhat the graph
am and give
s!!! ");
tructions hav
en save this
and run the p
own here.
come.class th
ual Machine
ompiled the
by the java i
every vertex
ween h is connecte
e the steps t
ve given by t
file as Welc
program. Fo
hat contains
e(JVM) that
program, w
interpreter c
x and every
and ed).
to execute it
there.
come.java
or that we ne
s only bytec
t will conver
e need to ru
called java. I
edge
,
t.
eed to
codes.
rt the
un the
In the
4. B.14 Explain the importance of JVM in JRE. (6) or (Nov/Dec 11)
• A Java virtual machine is a program which executes certain other programs, namely those
containing Java byte code instructions.
• JVM's are most often implemented to run on an existing operating system, but can also
be implemented to run directly on hardware.
• A JVM provides a run-time environment in which Java byte code can be executed,
enabling features such as automated exception handling, which provides root-cause
debugging information for every software error (exception).
• A JVM is distributed along with Java Class Library, a set of standard class libraries (in
Java byte code) that implement the Java application programming interface (API).
• These libraries, bundled together with the JVM, form the Java Runtime Environment
(JRE).
• JVMs are available for many hardware and software platforms. The use of the same byte
code for all JVMs on all platforms allows Java to be described as a write once, run
anywhere programming language, versus write once, compile anywhere, which describes
cross-platform compiled languages.
• Thus, the JVM is a crucial component of the Java platform.
4. B.15 Create a Complex number class in Java. The class should have a constructor and
methods to add, subtract and multiply two complex numbers, and to return the real and
imaginary parts.(10)
4. B.16 what are packages? How we they created and used? (6)
Java is a object oriented programming language which uses classes and methods. A java class consists of methods and variables. Methods holds function of the class. Class example: Class addition { int a, b, c; } Method Example: public static void main (String[] args) { // This Java program prints "Hello World!" System.out.println{"Hello World!");
} Package: A Java package is a set of classes which are grouped together. Every class is part of some package. All classes in a file are part of the same package. You can specify the package using a package declaration: package name ; as the first (non-comment) line in the file. 4. B.17. State the kruskal’s algorithm to compute the MST of a graph. Or (Nov/Dec 07)
Refer Q.No. 4.B.8
4. B.18 Explain with examples how a node is inserted into an AVL tree. Discuss all possible
cases. (Nov/Dec 06)
Refer Q.No. 4.B.6
UNIT 5
5. B.1 Explain the algorithm of Quicksort by sorting the following set of numbers as an
example:
42 47 52 57 62 37 32 27 22 Or (Ap/May 10)
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller
sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-
lists.
The steps are:
1. Pick an element, called a pivot, from the list.
2. Reorder the list so that all elements with values less than the pivot come before the pivot,
while all elements with values greater than the pivot come after it (equal values can go
either way). After this partitioning, the pivot is in its final position. This is called the
partition operation.
3. Recursively apply the above steps to the sub-list of elements with smaller values and
separately the sub-list of elements with greater values.
The base case of the recursion are lists of size zero or one, which never need to be sorted.
The correctness of the partition algorithm is based on the following two arguments:
• At each iteration, all the elements processed so far are in the desired position: before the
pivot if less than the pivot's value, after the pivot if greater than the pivot's value (loop
invariant).
• Each iteration leaves one fewer element to be processed (loop variant).
5. B.2 Describe divide and conquer technique with the help of merge sort. (16)
Divide and Conquer Strategy:-
The principle behind this strategy is that it is easier to solve several small instances of a problem than one large complex problem. The “divide - and - conquer” technique involves in solving a particular computational problem by dividing it into smaller sub problems, solving the problem recursively and then combining the results of all the sub problems to produce the result for the original complex problem ‘P’.
The strategy involves three steps at each level of recursion.
1. Divide:-Divide the problem into a number of sub problems. 2. Conquer:-Conquer the sub problems by solving them recursively. If the sub problem
sizes are small enough, then just solve the sub problems in a straight forward manner. 3. Combine:-Combine the solutions to the sub problems to form the solution for the
original problem.
Let ‘n’ represent the size of the original problem. Let S(n) denote this problem. We solve the problem S(n) by solving a collection of k sub problems- S(n1),S(n2),…S(nk), where ni<n for i=1,2,..k. Finally we merge the solutions to these problems.
5. B.3 Write a ‘C’ program to implement binary search and compute its complexity. (8)
#include <stdio.h> int main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter value to find\n"); scanf("%d",&search); first = 0; last = n - 1; middle = (first+last)/2;
while( first <= last ) { if ( array[middle] < search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first > last ) printf("Not found! %d is not present in the list.\n", search); return 0; }
5. B.4 Compare the worst case and best case time complexity of various sorting techniques.
(8) Or (Nov/Dec 09)
The term best-case performance is used in computer science to describe an algorithm's behavior under optimal conditions. For example, the best case for a simple linear search on a list occurs when the desired element is the first element of the list.
Development and choice of algorithms is rarely based on best-case performance: most academic and commercial enterprises are more interested in improving average performance and worst-case performance. Algorithms may also be trivially modified to have good best-case running time by hard-coding solutions to a finite set of inputs, making the measure almost meaningless.
Worst-case analysis has similar problems: it is typically impossible to determine the exact worst-case scenario. Instead, a scenario is considered such that it is at least as bad as the worst case. For example, when analysing an algorithm, it may be possible to find the longest possible path through the algorithm (by considering the maximum number of loops, for instance) even if it is not possible to determine the exact input that would generate this path (indeed, such an input may not exist). This gives a safe analysis (the worst case is never underestimated), but one which is pessimistic, since there may be no input that would require this path.
5. B.5 Explain the all pairs shortest path algorithm with an example. (16)
1. To find the shortest path between points, the weight or length of a path is calculated as the sum of the weights of the edges in the path.
2. A path is a shortest path is there is no path from x to y with lower weight. 3. Dijkstra's algorithm finds the shortest path from x to y in order of increasing distance from x. That is, it chooses the first minimum edge, stores this value and adds the next minimum value from the next edge it selects. 4. It starts out at one vertex and branches out by selecting certain edges that lead to new vertices. 5. It is similar to the minimum spanning tree algorithm, in that it is "greedy", always choosing the closest edge in hopes of an optimal solution.
Characteristics of a Shortest Path Algorithm: Dijkstra's algorithm selects an arbitrary starting vertex and then branches out from the tree constructed so far. Each of the nodes it visits could be in the tree, in the fringes or unseen. The designators:
TREE - nodes in the tree constructed so far
FRINGE - not in the tree, but adjacent to some vertex in the tree
UNSEEN - all others
designate for each node in the graph whether the node is part of the shortest path tree, a part of the set of fringes adjacent to the nodes in the tree or a part of, as of yet, unseen set of graph nodes. A crucial step in the algorithm is the selection of the node from the fringe edge. The algorithm always takes the edge with least weight from the tree to the fringe node. This is an example of a greedy algorithm which are used in optimization problems. They make locally optimal choices in hope that this will provide a globally optimal solution. The Applet performs the following operations:
• Add Node - adding a node to the graph • Remove a Node - deleting a node from the graph • Enter Weight - entering the weight of the edge
5. B.6 Ex
� A heapFurtherm
� Generi
5. B.7 Ex
10)
Prim's connectethat inclualgorithmindependin 1959. Prim–Ja
Other alHowevergraphs, w
If a graph
The algoone edge
• Inca
• In• R
xplain heap
p with n elemmore, the chil
ic heap sort
xplain the g
algorithm dweightedunudes every vm was devdently by comTherefore it
arník algorit
lgorithms for, these othwhile Prim's
h is empty th
rithm starts e at a time, un
nput: A non-an be negativnitialize: Vne
Repeat until V
sort with a
ments can beldren of a[i]
algorithm:
greedy algor
is a greedndirected grvertex, wherveloped in mputer scient is also somthm.
or this probher algorithm
algorithm re
hen we are d
with a tree cntil it spans
-empty connve). w = {x}, wheVnew = V:
an illustratio
e convenientcan be foun
rithm to find
dy algorithmraph. This mre the total w
1930 by ntistRobert C
metimes calle
blem includms can alsoequires the g
done immedi
consisting ofall vertices.
nected weigh
ere x is an ar
on. (8)
tly representnd in a[2i] (le
d minimum
m that finmeans it findweight of allCzech mat
C. Prim in 19ed the DJP a
de Kruskal'o find minimgraph to be c
iately. Thus,
f a single ver
hted graph w
rbitrary node
ted as the fireft child) an
m spanning t
nds a minimds a subset ol the edges ithematician 957 and redalgorithm, t
s algorithmmum spannconnected.
we assume
rtex, and con
with vertices
e (starting po
rst nelementsnd a[2i + 1] (
tree. (8)
mum spannof the edges in the tree is
Vojtěch Jdiscovered bythe Jarník a
m and Borůning forests
otherwise.
ntinuously in
V and edges
oint) from V
s of an array(right child)
Or (Nov/D
ning tree fthat forms a
s minimizedJarník and y Edsger Dijalgorithm, o
ůvka's algorof disconn
ncreases its s
s E (the weig
V, Enew = {}
y.
Dec
for a a tree
d. The later
jkstra or the
rithm. nected
size
ghts
o Choose an edge {u, v} with minimal weight such that u is in Vnew and v is not (if there are multiple edges with the same weight, any of them may be picked)
o Add v to Vnew, and {u, v} to Enew • Output: Vnew and Enew describe a minimal spanning tree
5. B.8 Explain the insertion sort with its time complexity. (8)
Insertion sort is a basic sorting algorithm which works the way people sort a hand of playing cards. Start with an empty left hand and then remove one card at a time from the deck and insert it into the correct position in your left hand. lets start with the Pseudo code for Insertion sort algorithm. input to the algorithm is an array A[1,2,...n] of length n. Insertion sort is an in-place algorithm , i.e the sorting takes place within the array.
for j = 2 to A.length
key = A[j]
i = j - 1
while (i > 0 and A[i] > key)
A[i+1] = A[i]
i = i - 1
A[i+1] = key
5. B.9 Explain as to how divide and conquer technique can be applied for merge sort. (8)
Refer Q.No.5.B.2
5. B.10 Describe the three different types of inheritance with an example Java program for
each.
There exists basically three types of inheritance.
1. Multilevel inheritance 2. Multiple inheritance 3. Hierarchical inheritance
1. In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases.
2. In multiple inheritance, one class directly extends more than one class. 3. In hierarchical inheritance one class is extended by more than one class.
For a fresher, it will be very confusing, no doubt. Let us go in detail of each one programmatically. Remember, to learn Java, C++ knowledge is not at all required. In fact, you learn OOPs concepts through C++ syntax in C++ and through Java syntax in Java. That is all.
1. Multilevel Inheritance
In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains.
class Aves { publicvoid nature() { System.out.println("Generally, Aves fly"); } } class Bird extends Aves { publicvoid eat() { System.out.println("Eats to live"); } } publicclass Parrot extends Bird { publicvoid food() { System.out.println("Parrot eats seeds and fruits"); } publicstaticvoid main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } }
Multiple Inheritance
In multiple inheritance, one class extends multiple classes. Java does not support multiple inheritance but C++ supports. The above program can be modified to illustrate multiple inheritance. The following program does not work.
calss Aves { } class Bird { } publicclass Parrot extends Aves, Bird { }
Hierarchical Inheritance
In hierarchical type of inheritance, one class is extended by many subclasses. It is one-to-many relationship. A realtime example is available at dynamic binding.
class Aves { publicvoid fly() { System.out.println("Generally, aves fly"); } } class Parrot extends Aves { publicvoid eat() { System.out.println("Parrot eats fruits and seeds"); } } class Vulture extends Aves { publicvoid vision() { System.out.println("Vulture can see from high altitudes"); } } publicclass FlyingCreatures { publicstaticvoid main(String args[]) { // all the following code is composition for FlyingCreatures Parrot p1 = new Parrot(); p1.eat(); // calling its own member p1.fly(); // calling super class member by inheritance Vulture v1 = new Vulture(); v1.vision(); // calling its own member
v1.fly(); // calling super class member by inheritance } }
5. B.11 Describe the concept of interface with the syntax. (6) or (Nov/Dec 11)
An interface in the Java programming language is an abstract type that is used to specify an
interface (in the generic sense of the term) that classes must implement. Interfaces are declared
using the interfacekeyword, and may only contain method signature and constant declarations
(variable declarations that are declared to be both static and final). An interface may never
contain method definitions.
Interfaces cannot be instantiated, but rather are implemented. A class that implements an
interface must implement all of the methods described in the interface, or be an abstract class.
Object references in Java may be specified to be of an interface type; in which case, they must
either be null, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must
have exactly one base class, the only exception being java.lang.Object (the root class of the Java
type system); multiple inheritance of classes is not allowed.
A Java class may implement, and an interface may extend, any number of interfaces; however an
interface may not implement an interface.
[visibility] interface InterfaceName [extends other interfaces] {
constant declarations
abstract method declarations
}
5. B.12 Write a Java program to demonstrate how to read and write data to a file. (10)
• FileReader for text files in your system’s default encoding (for example, files containing Western European characters on a Western European computer).
• FileInputStream for binary files and text files that contain ‘weird’ characters.
FileReader (for text files) should usually be wrapped in a BufferedFileReader. This saves up data so you can deal with it a line at a time or whatever instead of character by character (which usually isn’t much use).
If you want to write files, basically all the same stuff applies, except you’ll deal with classes named FileWriter with BufferedFileWriter for text files, or FileOutputStream for binary files.
import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; // This will reference one line at a time String line = null; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } // Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } }
5. B.13 what is a thread? How do you create threads? (6)
Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads concurrently. If your computer does not have multi-processors then the multi-threads really do not run concurrently. public class HelloRunnable implements Runnable { public void run() {
System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } }
5. B.14 Describe the concept of bubble sort & merge sort with example. (16) (Nov/Dec 12)
Or
If you are sorting content into an order, one of the most simple techniques that exists is the bubble sort technique. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest
number using bubble sort algorithm. In each step, elements written in bold are being compared.
First Pass:
( 51 4 2 8 ) ( 15 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 154 2 8 ) ( 1 45 2 8 ), Swap since 5 > 4
( 1 4 52 8 ) ( 1 4 25 8 ), Swap since 5 > 2
( 1 4 2 58 ) ( 1 4 2 58 ), Now, since these elements are already in order (8 > 5), algorithm does
not swap them.
Second Pass:
( 14 2 5 8 ) ( 14 2 5 8 )
( 1 42 5 8 ) ( 1 24 5 8 ), Swap since 4 > 2
( 1 2 45 8 ) ( 1 2 45 8 )
( 1 2 4 58 ) ( 1 2 4 58 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 12 4 5 8 ) ( 12 4 5 8 )
( 1 24 5 8 ) ( 1 24 5 8 )
( 1 2 45 8 ) ( 1 2 45 8 )
( 1 2 4 58 ) ( 1 2 4 58 )
Finally, the array is sorted, and the algorithm can terminate.
5. B.15 With example explains the binary search technique. (16)
Refer Q.No. 4.B.2
5. B.16. State and explain the algorithm to perform heap sort with an example. (Nov/Dec
07) Or
Heapify picks the largest child key and compare it to the parent key. If parent key is larger than heapify quits, otherwise it swaps the parent key with the largest child key. So that the parent is now becomes larger than its children. It is important to note that swap may destroy the heap property of the subtree rooted at the largest child node. If this is the case, Heapify calls itself again using largest child node as the new root.
Heapify (A, i) l ← left [i] r ← right [i] if l ≤ heap-size [A] and A[l] >A[i] then largest ← l else largest ← i if r ≤ heap-size [A] and A[i] > A[largest] then largest ← r if largest ≠ i then exchange A[i] ↔ A[largest] Heapify (A, largest) Analysis If we put a value at root that is less than every value in the left and right subtree, then 'Heapify' will be called recursively until leaf is reached. To make recursive calls traverse the longest path to a leaf, choose value that make 'Heapify' always recurse on the left child. It follows the left branch when left child is greater than or equal to the right child, so putting 0 at the root and 1 at all other nodes, for example, will accomplished this task. With such values 'Heapify' will called h times, where h is the heap height so its running time will be θ(h) .
Example of Heapify In the following complete binary tree, the subtrees of 6 are heaps:
The Heapit works.
We then we have down the
Now, 7 is
pify proceduFirst, we lo
determine wa heap. If no
e tree. In this
s greater tha
ure alters theok at the roo
which of the ot, we exchas case, we ex
an 6, so we e
e heap so thaot of our tree
three nodes nge the appr
xchange 6 an
exchange the
at the tree rooe and its two
is the greateropriate childnd 8, and con
em.
We ar contin
oted at 6's poo children.
est. If it is thd with the rontinue.
re at the bottnue, so we te
osition is a h
he root, we aroot, and cont
tom of the trerminate
heap. Here's
re done, bectinue recursi
ree, and can't
how
ause ively
t
5. B.17 State and explain the algorithm to perform merge sort with an example.
Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time has a lower order of growth than insertion sort. Since we are dealing with subproblems, we state each subproblem as sorting a subarray A[p .. r]. Initially, p = 1 and r = n, but these values change as we recurse through subproblems.
To sort A[p .. r]:
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the subarray has just one element, so that it is trivially sorted.
5. B.18. Write down the complete quick sort algorithm and illustrate its working to sort the
list {45,23,11,35,62,87,24,66} Or (Nov/Dec 06)
Given elements : 45 23 11 35 62 87 24 66
• Pivot selection (N = 8)
Midpoint = 7/2 = 3 A [Left] = 45 A [Midpoint] = 35 A [Right] = 66
45 2
Swap A 35 2
Swap A 35 2 ↑ i Pivot = 4
• P
i is increm35 2
j is decre35 2
Here i<j
35 2 S
• P
o(i) Qsor
the s11 23
• Q
the s62 6
3 11
[Midpoint] w3 11
[Midpoint] w3 11
45
artitioning
mented until3 11
emented unti3 11
condition fa
3 11 mall
ivot =45 ,div
f< 45 and > rt (A, Left, i-
o (A, 0,o Qsort
sub-array 1 a 24
Qsort (A, i+1o (A, 5,o Qsort
sub-array 2 a6 87
35 62
with A [Left 45 62
with A [Righ 24 62
l A [i] < Pivo 24 62 ↑ i
il A [j] > Piv 24 62 ↑ ↑ j i
ails, Swap A
24 45 ↑ i
vides the arr
45 -1)
3) (A, 0, 3) –c
as : 35
, Right) 7) (A, 5, 7) –c
as :
87
t] 87
ht-1] 87
ot 87
vot 87
A [i] with A [
87
Larg
ray into two
alls the quic
alls the quic
24 66
24 66
45 66 ↑ j
45 66 ↑ j
45 66 ↑ Right-1
[Right-1]
62 66
ge
sub-arrays
cksort recursi
cksort recursi
ively and ret
ively and ret
turns
turns
• F
S
5. B.19 W
list {25,7
Given ele 25, 73, 1
inal sorted l
1
mall
Write down
73,10,95,68,8
ements : 10, 95, 68, 82
(i) Build He
ist
1 23
Piv
the comple
82,22,60}.
2, 22, 60.
eap routine e
24 35
vot L
ete heap sort
execution to
45
↑
arge
t algorithm
derive a Ma
62 66
↑
m and illustra
axHeap struc
87
ate its work
cture:
king to sort the
(ii) Delet
te Max routi
ine to derivee a sorted list
t:
25
73
82 60
68 10
22 95
22
73
25 60
68 10
82 95
10
68
25 60 22 73 82 95
22
60
10
22
25 10
25 60
68 73
68 73
82 95
82 95
10
22
25 60
68 73 82 95
S
10
22
5. B.20 W
case ana
The termunder opwhen the
Developmand commcase perftime by h
Sorted list
25 60
Write down
alysis Or
m best-case ptimal condit
e desired elem
ment and chmercial enteformance. Alhard-coding
68 73
the merge s
performance tions. For exment is the f
oice of algorrprises are mlgorithms msolutions to
82 95
sort algorith
is used in coample, the b
first element
rithms is rarmore interest
may also be tra finite set o
hm and give
omputer sciebest case for t of the list.
ely based onted in improvrivially modiof inputs, ma
e its worst c
ence to descra simple lin
n best-case pving averageified to haveaking the me
case, best ca
ribe an algornear search o
performancee performane good best-ceasure almos
ase and aver
rithm's behaon a list occu
: most acadence and worscase runningst meaningle
rage
avior urs
emic st-g ess.
Worst-case performance analysis and average case performance analysis have some similarities, but in practice usually require different tools and approaches.
Determining what average input means is difficult, and often that average input has properties which make it difficult to characterise mathematically (consider, for instance, algorithms that are designed to operate on strings of text). Similarly, even when a sensible description of a particular "average case" (which will probably only be applicable for some uses of the algorithm) is possible, they tend to result in more difficult to analyse equations.
5. B.21 Show how heap sort processes the input 142, 543, 123, 65, 453, 879, 572, 434, 111,
242, 811, 102.(Nov/Dec 05).
The input is read in as 142, 543, 123, 65, 453, 879, 572, 434, 111, 242, 811, 102 The result of the heapify is 879, 811, 572, 434, 543, 123, 142, 65, 111, 242, 453, 102 879 is removed from the heap and placed at the end. We'll place it in italics to signal that it is not part of the heap. 102 is placed in the hole and bubbled down, obtaining 811, 543, 572, 434, 453, 123, 142, 65, 111, 242, 102, 879 Continuing the process, we obtain 572, 543, 142, 434, 453, 123, 102, 65, 111, 242, 811, 879 543, 453, 142, 434, 242, 123, 102, 65, 111, 572, 811, 879 453, 434, 142, 111, 242, 123, 102, 65, 543, 572, 811, 879 434, 242, 142, 111, 65, 123, 102, 453, 543, 572, 811, 879 242, 111, 142, 102, 65, 123, 434, 453, 543, 572, 811, 879 142, 111, 123, 102, 65, 242, 434, 453, 543, 572, 811, 879 123, 111, 65, 102, 142, 242, 434, 453, 543, 572, 811, 879 111, 102, 65, 123, 142, 242, 434, 453, 543, 572, 811, 879 102, 65, 111, 123, 142, 242, 434, 453, 543, 572, 811, 879 65, 102, 111, 123, 142, 242, 434, 453, 543, 572, 811, 879