Data Structures and Object Oriented Programming in C++: Two Marks With Answer
Data Structures and Object Oriented Programming in C++: Two Marks With Answer
com
Prepared by
M. Rameshkumar,Lect(CSE)
www.vidyarthiplus.com
www.vidyarthiplus.com
EC2202 DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
Large programs are divided into smaller programs called Programs are divided into objects.
functions.
Functions share global data. Functions that operate on the data of an object are
tied together.
Data move openly around the system from function to Data is hidden and cannot be accessed by external
function. functions.
www.vidyarthiplus.com
www.vidyarthiplus.com
32. What is static member function?
A member function that is declared as static has the following properties
A static function can have access to only other static member declared in the same class
A static member function can be called using the classname as follows
classname ::function_name;
33. What is called pass by reference?
In this method address of an object is passed, the called function works directly on the actual arguments.
34. Define constructor
A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same
as class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it
constructs the values of data members of the class
Eg:
Class integer
{
……
public:
integer( );//constructor
………
}
35. Define default constructor
The constructor with no arguments is called default constructor
Eg:
Class integer
{
int m,n;
Public:
Integer( );
…….
};
integer::integer( )//default constructor
{
m=0;n=0;
}
the statement
integer a;
invokes the default constructor
36. Define parameterized constructor
constructor with arguments is called parameterized constructor
Eg;
Class integer
{ int m,n;
public:
integer(int x,int y)
{ m=x;n=y;
}
To invoke parameterized constructor we must pass the initial values as arguments to the constructor function when an object is
declared. This is done in two ways
1.By calling the constructor explicitly
eg: integer int1=integer(10,10);
2.By calling the constructor implicitly
eg: Integer int1(10,10);
37. Define default argument constructor
The constructor with default arguments are called default argument constructor
Eg:
www.vidyarthiplus.com
www.vidyarthiplus.com
Complex(float real,float imag=0);
The default value of the argument imag is 0. The statement complex a(6.0) assign real=6.0 and imag=0 the statement complex
a(2.3,9.0)
assign real=2.3 and imag=9.0
38. What is the ambiguity between default constructor and default argument constructor ?
The default argument constructor can be called with either one argument or no arguments. when called with no arguments ,it
becomes a default constructor. When both these forms are used in a class ,it cause ambiguity for a statement such as A a; The
ambiguity is whether to call A::A() or A::A(int i=0)
39. Define copy constructor
A copy constructor is used to declare and initialize an object from another object. It takes a reference to an object of the same
class as an argument.
Eg: integer i2(i1);
would define the object i2 at the same time initialize it to the values of i1. Another form of this statement is
Eg: integer i2=i1;
The process of initializing through a copy constructor is known as copy initialization.
40. Define dynamic constructor
Allocation of memory to objects at time of their construction is known as dynamic constructor. The memory is allocated with the
help of the NEW operator
Eg:
Class string
{
char *name;
int length;
public:
string( )
{
length=0;
name=new char[length +1];
}
void main( )
{
string name1(“Louis”),name3(Lagrange);
}
41. Define const object
We can create constant object by using const keyword before object declaration.
Eg: Const matrix x(m,n);
42. Define destructor
It is used to destroy the objects that have been created by constructor. Destructor name is same as class name preceded by tilde
symbol(~)
Eg;
~integer()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler upon exit from the program will invoke it.
Whenever new operator is used to allocate memory in the constructor, we should use delete to free that memory.
43. Define multiple constructors (constructor overloading).
The class that has different types of constructor is called multiple constructors
Eg:
#include<iostream.h>
#include<conio.h>
class integer
{
int m,n;
public:
www.vidyarthiplus.com
www.vidyarthiplus.com
integer( ) //default constructor
{
m=0;n=0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{
m=i.m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}
44. Write some special characteristics of constructor
• They should be declared in the public section
• They are invoked automatically when the objects are created
• They do not have return types, not even void and therefore, and they cannot return values
• They cannot be inherited, though a derived class can call the base class
• They can have default arguments
• Constructors cannot be virtual function
57. What is the purpose of using operator function? Write its syntax.
To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied.
This is done by Operator function , which describes the task. Operator functions are either member functions or friend functions.
The general form is
return type classname :: operator (op-arglist )
{
function body
}
where return type is the type of value returned by specified operation. Op-operator being overloaded. The op is preceded by a
keyword operator. operator op is the function name.
58. Write at least four rules for Operator overloading.
www.vidyarthiplus.com
www.vidyarthiplus.com
Only the existing operators can be overloaded. The overloaded operator must have at least one operand that is of user defined
data type.
The basic meaning of the operator should not be changed. Overloaded operators follow the syntax rules of the original operators.
They cannot be overridden.
59. How will you overload Unary & Binary operator using member functions?
When unary operators are overloaded using member functions it takes no explicit arguments and return no explicit values. When
binary operators are overloaded using member functions, it takes one explicit argument. Also the left hand side operand must be
an object of the relevant class.
60. How will you overload Unary and Binary operator using Friend functions?
When unary operators are overloaded using friend function, it takes one reference argument (object of the relevant class)
When binary operators are overloaded using friend function, it takes two explicit arguments.
61. How an overloaded operator can be invoked using member functions?
In case of Unary operators, overloaded operator can be invoked as op object_name or object_name op In case of binary operators,
it would be invoked as
Object . operator op(y) //where op is the overloaded operator and y is the argument.
62. How an overloaded operator can be invoked using Friend functions?
In case of unary operators, overloaded operator can be invoked as Operator op (x); In case of binary operators, overloaded
operator can be invoked as Operator op (x , y)
63. List out the operators that cannot be overloaded using Friend function.
• Assignment operator =
• Function call operator ( )
• Subscripting operator [ ]
• Class member access operator →
64. What is meant by casting operator and write the general form of overloaded casting operator.
A casting operator is a function that satisfies the following conditions
It must be a class member.
It must not specify a return type.
It must not have any arguments.
The general form of overloaded casting operator is
operator type name ( )
{
……….. // function statements
}
It is also known as conversion function.
65. Explain basic to class type conversion with an example.
Conversion from basic data type to class type can be done in destination class. Using constructors does it. Constructor takes a
single argument whose type is to be converted.
Eg: Converting int type to class type
class time
{
int hrs,mins;
public:
………….
Time ( int t) //constructor
{
hours= t/60 ; //t in minutes
mins =t % 60;
} };
Constructor will be called automatically while creating objects so that this conversion is done automatically.
66. Explain class to basic type conversion with an example.
Using Type Casting operator, conversion from class to basic type conversion can be done. It is done in the source class itself.
Eg: vector : : operator double( )
{
double sum=0;
www.vidyarthiplus.com
www.vidyarthiplus.com
for(int I=0;I<size;I++)
sum=sum+v[ i ] *u[ i ] ;
return sqrt ( sum ) ;
}
This function converts a vector to the corresponding scalar magnitude.
67. Explain one class to another class conversion with an example.
Conversion from one class type to another is the combination of class to basic and basic to class type conversion. Here
constructor is used in destination class and casting operator function is used in source class.
Eg: objX = objY
objX is the object of class X and objY is an object of class Y. The class Y type data is converted into class X type data and the
converted value is assigned to the obj X. Here class Y is the source class and class X is the destination class.
68. What is meant by inheritance?
Inheritance is the process by which objects of one class acquire the properties of another class. It supports the concept of
hierarchical classification. It provides the idea of reusability. We can add additional features to an existing class without
modifying it by deriving a new class from it.
69. What is meant by single inheritance?
If a single class is derived from a single base class is called single inheritance.
Eg:
Base class
Derived class
Here class A is the base class from which the class D is derived. Class D is the public derivation of class B hence it inherits all
the public members of B. But D cannot access private members of B.
70.What is multiple inheritance?
If a class is derived from more than one base class, it is called multiple inheritance.
Eg: Base classes
Derived class
Here class C is derived from two base classes A & B.
86) What is hierarchical inheritance?
If a number of classes are derived from a single base class then it is called hierarchical inheritance.
Eg : Hierarchical classification of students in University
A
B
A
C
B
71. What is multilevel inheritance?
If a class is derived from a class, which in turn is derived from another class, is called multilevel inheritance. This process can be
extended to any number of levels.
Eg: Base class Grand father , Intermediate , Base class Father , Derived class Child
72. What is hybrid inheritance?
It is the combination of one or more types of inheritance.
• Multilevel
• inheritance
• Multiple
• inheritance
The class result will have both the multilevel and multiple inheritances.
73. What is meant by Abstract base class?
A class that serves only as a base class from which derived classes are derived. No objects of an abstract base class are created. A
base class that contains pure virtual function is an abstract base class.
74. Write short notes on virtual base class.
A base class that is qualified as virtual in the inheritance definition. In case of multiple inheritance, if the base class is not virtual
the derived class will inherit more than one copy of members of the base class. For a virtual base class only one copy of members
will be inherited regardless of number of inheritance paths between base class and derived class.
Eg: Processing of students’ results. Assume that class sports derive the roll number from class student. Class test is derived from
www.vidyarthiplus.com
www.vidyarthiplus.com
class Student. Class result is derived from class Test and sports. As a virtual base class As a virtual base class
75. What are the iteration statements used in C++?
While: repeats a statement or block while its controlling expression is true.
Syntax: while(condition){
//body of loop }
do-while: Executes its body atleast once
Syntax: do{
//body of loop
}while(condition);
for: consists of three portions initialization,conditon,termination.
Syntax: for(initialization,conditon,termination.){
//body }
76. What is the difference between break & continue statements?
Break: We can force immediate termination of a loop, bypassing the conditional, the loop expression & any remaining code in
the body of the loop. When a break statement is encountered in a loop, the loop is terminated & the program control resumes at
the next statement following the loop. Continue: useful to force early termination. it continue running the loop, but stop
processing the remainder of the code in it’s body for this particular iteration
UNIT 3, 4 & 5
1. What is an Algorithm?
An algorithm is clearly specified set of simple instructions to be followed to solve a problem. The algorithm forms a base
for program.
2. What are the properties of an Algorithm?
Takes zero or more inputs
Results in one or more outputs
All operations are carried out in a finite time
Efficient and flexible
Should be concise and compact to facilitate verification of their correctness.
3. Define Program?
It is an instruction and it is written according to the instructions, which is given in the algorithm.
4. What is Complexity analysis?
It is the analysis of the amount of memory and time an algorithm requires to completion.
There are two types of Complexity Space Complexity and Time Complexity
5. Explain the performance analysis of the algorithm?
The analysis of the performance of an algorithm based on specification is called performance analysis. It is
loosely divided into
a. Priori estimates
b. Posterior Testing
6. Explain Space complexity?
Space complexity of an algorithm is the amount of memory it needs to run to completion.
7. Explain Time complexity?
Time complexity is the amount of computer time an algorithm requires to run to completion.
8. List out the components that are used for space complexity?
a. Instruction Space
b. Environment Stack
www.vidyarthiplus.com
www.vidyarthiplus.com
c. Data Space.
9. What do asymptotic notation means?
Asymptotic notations are terminology that is introduced to enable us to make meaningful statements about the time and space
complexity of an algorithm. The different notations are
Big – Oh notation
Omega notation
Theta notation.
10. Define Efficiency of an algorithm?
It denotes the rate at which an algorithm solves a problem of size n. It is measured by the amount of resources it uses, the
time and the space.
11. Define Worst case of an algorithm?
It is the longest time that an algorithm will use over all instances of size n for a given problem to produce the result.
12. Define Best case of an algorithm?
It is the shortest time that an algorithm will use over all instances of size n for a given problem to produce the result.
13. Define average case an algorithm?
It is the average time that an algorithm will use over all instances of size n for a given problem to produce the result.
14. Define Divide and Conquer algorithm?
Divide and Conquer algorithm is based on dividing the problem to be solved into several, smaller sub instances, solving them
independently and then combining the sub instances solutions so as to yield a solution for the original instance.
15. Mention some application of Divide and Conquer algorithm?
a. Quick Sort
b. Merge Sort
c. Binary search
16. Define dynamic programming algorithm?
Dynamic programming algorithm is a general class of algorithms which solve problems by solving smaller versions of the
problem, saving the solutions to the small problems and then combining them to solve the larger problems.
17. Mention application of dynamic programming algorithm?
Efficient Fibonacci number computation
Chained matrix multiplication.
Longest common subsequence problem
18. State the various steps in algorithm?
Devising the algorithm
Validating the algorithm
Expressing the algorithm
Determination of complexity of the algorithm
19. Define algorithm paradigms space of an algorithm?
Algorithmic paradigms are defined as the general approach to design and construct efficient solutions to problems.
20. Mention the various spaces utilized by a program?
a. A fixed amount of memory occupied by the space for the program code and space occupied by the variables used in the
program.
b. A variable amount of memory occupied by the variable whose size is dependent on the problem being solved. This
space increases or decreases depending upon whether the program uses iterative or recursive procedures.
www.vidyarthiplus.com
www.vidyarthiplus.com
25. What are different types of Circular Linked List?
Circular Single linked list
Circular double linked list
26. List the basic operations carried out in a linked list?
a. Creation of list
b. Insertion of list
c. Deletion of list
d. Modification of list
e. Traversal of List
27. Define a stack?
Stack is an ordered collection of elements in which insertions and deletions are restricted to one end. The end from which
elements are added and /or removed is referred to as top of the stack. Stacks are also referred as “piles” and “push-down lists”.
28. Define a queue?
Queue is an ordered collection of elements in which insertions and deletions are restricted to one end. The end from which
elements are added and / or removed is referred to as the rear end and the end from which deletions are made is referred to as
front end.
29. Difference between Arrays and Linked List?
Arrays Linked List
It is necessary to specify the number of elements It is not necessary to specify the number of
during declaration. elements during declaration.
Insertion and deletions are difficult and Insertions and deletions are done in less time
costly
It occupies less memory than a linked List. It occupies more memory.
www.vidyarthiplus.com
www.vidyarthiplus.com
37. What are the conditions that followed in the array implementation of queue?
Condition Situation
REAR<FRONT EMPTY QUEUE
FRONT==REAR ONE ENTRY QUEUE
REAR==ARRAY SIZE FULL QUEUE
38. What are the conditions that could be followed in a linked list implementations of queue?
Condition Situation
REAR==HEAD EMPTY QUEUE
REAR==LINK (HEAD) ONE ENTRY QUEUE
NO FREE SPACE TO INSERT FULL QUEUE
www.vidyarthiplus.com
www.vidyarthiplus.com
40. Define Circular queue?
A circular queue allows the queue to wrap around upon reaching the end of the array
41. Define tree.
Trees are non-liner data structure, which is used to store data items in a shorted sequence. It represents any
hierarchical relationship between any data Item. It is a collection of nodes, which has a distinguish node called the root and
zero or more non-empty sub trees T1, T2,….Tk. each of which are connected by a directed edge from the root.
42. Define Height of tree.
The height of n is the length of the longest path from root to a leaf. Thus all leaves have height zero. The height of a tree is
equal to a height of a root.
43. Define Depth of tree.
For any node n, the depth of n is the length of the unique path from the root to node n. Thus for a root the depth is always
zero.
www.vidyarthiplus.com
www.vidyarthiplus.com
56. General idea of hashing and what is the use of hashing function?
A hash table similar to an array of some fixes size-containing keys. The keys specified here might be either integer or strings,
the size of the table is taken as table size or the keys are mapped on to some number on the hash table from a range of 0 to
table size
57. What is priority queue?
A priority queue is a data structure that allows at least the following two operations: insert which does the obvious thing; and
Deletemin, which finds,returns, and removes the minimum element in the priority queue. The Insert operation is the
equivalent to enqueue.
58. Application of priority queues?
1. for scheduling purpose in operating system
2. used for external sorting
3. important for the implementation of greedy algorithm, which operates
by repeatedly finding a minimum.
59. What are the main properties of a binary heap?
1. Structure property
2. Heap order property
60. Define tree traversal and mention the type of traversals?
Visiting of each and every node in the tree exactly is called as tree traversal. Three types of tree traversal
1. inorder traversal 2. preoder traversal 3. postorder traversal.
61. What is insertion sort? How many passes are required for the elements to be sorted?
One of the simplest sorting algorithms is the insertion sort. Insertion sort consist of N-1 passes. For pass P=1 through N-1 ,
insertion sort ensures that the elements in positions 0 through P-1 are in sorted order .It makes use of the fact that elements in
position 0 through P-1 are already known to be in sorted order .
62. Write the function in C for insertion sort ?
Void insertionsort(elementtype A[ ] , int N)
{
int j, p;
elementtype tmp;
for(p=1 ; p <N ;p++ )
{
tmp = a[ p] ;
for ( j=p ; j>0 && a [ j -1 ] >tmp ;j--)
a [ j ]=a [j-1 ] ;
a [ j ] = tmp ;
}
}
63. Who invented shell sort? Define it?
Shell sort was invented by Donald Shell. It works by comparing element that are distant. The distance between the
comparisons decreases as the algorithm runs until the last phase in which adjacent elements are compared. Hence it is referred
as diminishing increment sort.
64. Write the function in c for shell sort?
Void Shellsort(Elementtype A[ ],int N)
{
int i , j , increment ;
elementtype tmp ;
for(elementtype=N / 2;increment > 0;increment / = 2)
For( i= increment ; i <N ; i ++)
{
tmp=A[ ];
for( j=I; j>=increment; j - =increment)
if(tmp< A[ ]=A[j – increment];
A[ j ]=A[ j – increment];
Else
Break;
A[ j ]=tmp;
}
}
www.vidyarthiplus.com
www.vidyarthiplus.com
65. What is maxheap?
If we want the elements in the more typical increasing sorted order, we can change the ordering property so that the parent
has a larger key than the child. it is called max heap.
66. What are the two stages for heap sort?
Stage 1: Construction of heap
Stage 2: Root deletion N-1 times
67. What is divide and conquer strategy?
In divide and conquer strategy the given problem is divided into smaller problems and solved recursively. The conquering
phase consists of patching together the answers. Divide and conquer is a very powerful use of recursion that we will see many
times.
68. Differentiate between merge sort and quick sort?
Mergesort
1. Divide and conquer strategy
2. Partition by position
Quicksort
1. Divide and conquer strategy
2. Partition by value
69. Mention some methods for choosing the pivot element in quicksort?
1. Choosing first element
2. Generate random number
3. Median of three
70. What are the three cases that arise during the left to right scan in quicksort?
1. I and j cross each other
2. I and j do not cross each other
3. I and j points the same position
71. What is the need of external sorting?
External sorting is required where the input is too large to fit into memory.So external sorting is necessary where the program
is too large.
72. Define two way merge?
It is a basic external sorting in which there are two inputs and two outputs tapes.
73. Define multi way merge?
If we have extra tapes then we can expect to reduce the number of passes required to sort our input. We do this by extending
two way merge to a k-way merge.
74. Define polyphase merge?
The k-way merging strategy requires the use of 2 k tapes. This could be prohibitive for some applications. It is possible to get
by with only k+1 tapes.
75. What is replacement selection?
We read as many records as possible and sort them. Writing the result to some tapes. This seems like the best approach
possible until one realizes that as soon as the first record is written to a output tape the memory it used becomes available for
another record. If the next record on the input tape is larger than the record we have just output then it can be included in the
item. Using this we can give algorithm. This is called replacement selection.
76. What is sorting?
Sorting is the process of arranging the given items in a logical order. Sorting is an example where the analysis can be
precisely performed.
77. What is mergesort?
The mergesort algorithm is a classic divide and conquer strategy. The problem is divided into two arrays and merged into
single array
78. What are the properties involved in heapsort?
1. Structure property
2. Heap order property
79. Define articulation points.
If a graph is not biconnected, the vertices whose removal would disconnect the graph are known as articulation points.
80. Give some example of NP complete problems.
i. Hamiltonian circuit.
ii. Travelling salesmen problems
iii. Longest path problems
iv. Bin packing
www.vidyarthiplus.com
www.vidyarthiplus.com
v. Knapsack problem
vi. Graph coloring problem
81. What is a graph?
A graph consists of a set of vertices V and set of edges E which is mathematically represented as G=(V,E).Each edge in a
pair(V,W) where V,W,belongs to E ,edges are sometimes referred to as arcs.
82. What are Directed graphs?
If a pair of vertices for any edge is ordered, then that graph is called as Digraph or directed graph.
83. Define Path.
A path in a graph is a sequence of vertices w1,w2w,3,wN such that Wi,Wi+1 belongs to E for a value 1<=I<=N. The length
of such a path is the number of edges on the path, which is equal to n-1.
84. Define Cycle.
A cycle is a path in which the first and last vertices are the same.
85. Define Acyclic graph.
A graph with no cycles is called Acyclic graph. A directed graph with no Edges is called as a directed Acyclic graph (or)
DAG. DAGS are used for Compiler Optimization process.
86. Define Connected graph.
A graph is said to be a weighted graph is connected if there is a path from every vertex to every other vertex. A directed graph
with this property is called as strongly connected graph. If a directed graph is not strongly connected but the underline graph.
Without direction is connected it is called as a weakly connected graph.
87. What are the conditions for a graph to become a tree?
A graph is a tree if it has two properties.
i. If it is a connected graph.
ii. There should not be any cycles in the graph.
www.vidyarthiplus.com