ESP V-Programming & Data Structure
ESP V-Programming & Data Structure
Syllabus: Programming and data structures: programming in C; functions, recursion, parameter passing, scope,
binding; abstract data types, arrays, stacks, queues, linked lists, trees, binary search trees, binary heaps.
writing such a code (or a program) is called program- 1. Procedural Languages: These are those
ming. According to famous programmer Niklaus Wirth, languages which follow a certain procedure. These
are three different types-:
•• Algorithmic languages: The programmer specifies
PROGRAMS = DATA + ALGORITHMS
Every programming language has two important pil- the steps (algorithm) to be followed for accom-
lars- syntax (refers to grammatical representation) and plishing a particular task. Such languages have
semantic (refers to the meaning). A correct program built-in expressions, functions and procedures.
should be correct from syntactic view as well as from For example, C, COBOL, PASCAL.
semantic view. The different kinds of translators check •• Object-oriented languages: Instead of using func-
only the syntactic representation and the programmer tions, objects are used. The data and the func-
takes care of the semantic representation. There are dif- tions are combined in defining an object. Some
ferent generations of programming languages: of the important features are: Abstraction,
1. First Generation/1GL/(Machine level pro- Encapsulation, Polymorphism and Inheritance.
gramming): The program is written in a sequence For example, C++, Java.
of 0s and 1s (binary number system). Such a •• Scripting languages: It is a kind of language that
language is more closer to the machine and the combines different components together to per-
programs are machine dependent and difficult to form a difficult task. For example, Visual Basic
debug. The only advantage is that there is no need script, PERL.
for translator software (as the program is already 2. Non-Procedural Languages: 4GL languages
in machine code) and execution is very fast. are defined as non-procedural languages. These are
2. Second Generation /2GL/(Assembly level two different types-:
•• Functional language: The program consists of
programming): The program is written using
instructions based on mnemonics and hexadecimal
functions, such languages are used in the field
number system. Such a language is also machine-
of artificial intelligence. For example, LISt Pro-
dependent. Assembler is the translator used to
cessing (LISP).
•• Logic-based language: It is a set of rules that
convert assembly level code to machine level code.
The programs more reader friendly so are easier to
are defined and the answer is retrieved using
debug.
if−then rules. For example, PROgramming in
3. Third Generation /3GL/(High-level pro-
LOGic (PROLOG).
gramming): The program is written using
English-like statements and decimal number 3. Problem-Oriented Languages: Especially designed
system. Such a language is more closer to the user to solve certain kind of problems. These are of two dif-
and the programs are machine independent. There ferent types:
is a need of translator (compiler/interpreter) to •• Numerical problems: These contains the built-in
convert the high- level code to machine level code. functions, used to solve mathematical problems.
Such languages are user-friendly. Such languages For example, Mathematica.
are file-oriented. •• Publishing: It contains the built-in functions,
4. Fourth Generation /4GL/(Non-procedural used in publishing industry. For example,
programming): Such languages allow the user to LATEX.
specify the result instead of the describing how the
result is to be obtained. All kinds of query lan- 3.2.3 Procedural Programming and Object-
guages belong to this generation. Such languages Oriented Programming
are database-oriented.
5. Fifth Generation /5GL/(Natural Language 3.2.3.1 Procedural Programming
Programming): They are similar to 4GL and
eliminates the user or programmer to learn a spe- It uses a list of instructions in a stepwise manner to
cific language. The language used, resembles the computer. It relies on procedures. Procedures are also
human speech closely. Example- CLOUT, Q & A, known as routines or subroutines. A procedure consists
HAL (Human Access Language). of a series of computational steps that has to be carried
out. Procedural programming languages are also known
as top-down languages.
3.2.2 Classification of High-Level Languages
3.2.3.2 Object-Oriented Programming
Depending upon their usage, the high-level languages
are classified as: procedural, non-procedural and problem Object-oriented programming (OOP) is a problem-
oriented languages. solving approach in which all computations are carried
out using objects. An object is an entity of a program. 2. Modularization: Dividing the program into
It is used to perform actions and interactions with other small independent modules.
elements of the program. These are the fundamental
units of OOP, for example, a person. 3.2.4 Data Types
The other fundamental concepts of OOP are as
follows: It constitutes the type of values a variable can take and
a set of operations that can be applied to those values.
1. Class: It is a blueprint for an object. It does not
Data types in programming language can be broadly
define any data, rather it will define the object of
classified as shown in Fig. 3.1.
the class it consists and the operations performed
on the object.
2. Abstraction: It is used to provide essential char
information in a program without presenting the integer type
details. For example, in a database system, only int
data is shown, all the information regarding creat-
ing, storing, etc., is hidden. float
3. Encapsulation: It is used to place data and func- Basic data
tions at the same place. types float type
4. Inheritance: It is the process of forming a new class double
from an existing class. The new class is known as the bool
derived class and the existing class is known as the
base class. It uses the concept of reusability of code. void
5. Polymorphism: It is used to provide different
meanings or functions to the existing operators or array
functions.
6. Overloading: It is a branch of polymorphism. Data type Derived data
types function
When the existing operator or function is made to
operate on a new data type, then it is known as
overloading. pointer
3.2.3.3 Structured Programming
structure
A kind of programming approach that revolutionized
the programming concept, proposed by E. Dijkstra’. union
User defined
In 1968, Dijkstra submitted the famous article in data types
ACM Journal, highlighting the drawbacks of using the class
GOTO statement. He advocated that program written
without the use of GOTO statement (or JUMP state- enumeration
ment) were more stable. Nowadays, more and more
Figure 3.1 | Classification of data types in
programmers are following such kind of approach in
writing programs. Other notable attributes of struc- programming languages.
tured programming are:
1. Top-down analysis: A large problem is sub- Table 3.1 gives detail about basic data types with its
divided into smaller sub-problems. storage sizes and value ranges.
Table 3.1 | Basic data types, their storage size and value ranges
Type Storage Size Value Range (Depends on Compiler Type)
char 1 byte −128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte −128 to 127
int 2 or 4 bytes −32,768 to 32,767 or −2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
(Continued)
C language is a weakly typed language so it allows or take decisions and branches. For that purpose, any
implicit and explicit type conversions (Fig. 3.2). The programming language provides control flow statements
compiler promotes each term in a binary expression to that specifies the control flow of program or the order of
the highest precision operand. execution of statements (Fig. 3.3).
Programs consist of several statements and execution is These are used to execute a statement or a group of
not limited to a linear sequence of statements. During statements on the basis of certain conditions. These con-
its execution, a program may repeat segments of code, ditions are as follows:
char
int
unsigned int
Wide conversion Narrow conversion
(High precision) long
(Low precision)
unsigned long
long long
float
double
long double
Control statements
Conditional/ Unconditional
while
Decision control branch
if goto for
nested if continue
else-if return
switch
1. If: When the condition is satisfied then the state- 3.2.5.2 Loops
ments inside the parenthesis {} will be executed.
2. If-Else: If the condition is true then the state- These are used to execute a block of code several number
ments between if and else will be executed. If it of times. The statements are executed sequentially.
is false then the statement after else will be exe- Loop executes a statement or a group of statements
cuted. In nested if, one or more if-else block(s) lie multiple times. When the execution of statements in
within the parent if statement. the loop is unknown, then this concept is known as
3. Else-If: If the condition is true then the state- odd loop.
ments between if and else if will be executed. If it Loops are of the following three types:
is false then the condition in else if is checked, and
if it is true it will be executed. 1. while loop: It repeats a statement or group of
4. Switch: It is also known as matching case state- statements while a given condition is true. It tests
ments. It is used to test for equality against a list the condition before executing the loop body.
of values. It matches the value in variable with 2. for loop: It executes a sequence of statements
any of the case inside the switch. If it matches the multiple times.
case defined in the switch then that match will be 3. do … while loop: It is similar to while statement,
executed. If none of the cases match the statement except that it tests the condition at the end of the
then default will be executed. loop body.
Loops can be nested, that is, execution of one loop inside Note that the first element is numbered 0 and so on.
another loop. Here, the size of the array age is five times the size of
There are various control statements used for changing int because there are five elements.
execution from its normal sequence. These are as follows: Starting address of an array is also known as the base
1. break statement: It terminates the loop or address of the array. Suppose, the starting address of
switch and transfers the execution to the statement age[0] is 1000 and the size of int is 4 bytes. Then, the
immediately following the loop or switch. next address (address of age[1]) will be 1004, address of
2. continue statement: It skips the remainder of age[2] will be 1008 and so on.
the loop body and immediately begins execution
from the top.
3.2.6.2 Important Things to Remember in
3. goto statement: It transfers control to the
labelled statement. C Arrays
4. return statement: It transfers control from the
Following are the important points for arrays:
function to the calling function.
1. Suppose you want to declare an array of 10 stu-
3.2.6 Array dents. For example: arr[10]. Only array members
from arr[0] to arr[9] are used. But, if element arr[10],
Array handles similar types of data. For example, stor- arr[13], etc. are used, then the compiler may not
ing marks of 100 students. show error but may cause fatal error during pro-
An array is a set of homogenous elements, which uses gram execution.
contiguous memory locations. The lowest address cor- 2. The size of the array may not be defined during
responds to the first element and the highest address to initialisation. For example,
the last element. int age[] = {2, 4, 35, 5, 8};
3.2.6.1 Declaring an Array In this case, the compiler determines the size of the
array by calculating the number of elements of an
Array can be declared as follows: array.
type arrayName [arraySize]; 3. If we do not provide value to any position in the
where array it will store 0 by default. For example,
1. type represents the type of element an array stores. int age[5] = {2, 4, 35, 5};
For example, if array stores integer elements then
In this above case, first four places in the array will
type of array is `int’.
be filled by given values and the last will be filled
2. arrayName represents the name given to the array.
by 0.
It can be any string.
3. arraySize represents the number of elements the int age[5]= { };
array stores. It is showed in [].
Now array age is initialised with 0 at every
For example, an array of 10 integers can be defined as position.
follows:
int arr[10] 3.2.6.3 Address Calculation in an Array
Arrays are of the following two types:
The address can be calculated as follows:
1. One-dimensional arrays
2. Multi-dimensional arrays
One-Dimensional Arrays
Initialisation of One-Dimensional Array In one dimension, an array `A’ is declared as follows:
Arrays can be initialised at declaration time in this A[lb… …ub]
source code as follows (Fig. 3.4):
int age[5] = {2, 4, 35, 5, 8} where lb is the lower bound of the array and ub is the
upper bound of the array.
age[0] age[1] age[2] age[3] age[4]
Suppose we want to calculate the ith element address,
2 4 35 5 8 then
Figure 3.4 | Initialisation of one-dimensional array. Address (arr[i]) = BA + (i − lb) * c;
where BA is the base address of array, lb is the lower 3.2.7 Function and Recursion
bound of array and c is the size of each element.
A function is a group of statements, which is used to
Two-Dimensional Arrays perform a task and recursion is a programming tech-
nique, which is used to express operations in terms of
In two dimensions, an array `A’ is declared as follows: themselves.
A[lb1 … …ub1][lb2 … … ub2]
where lb1 is the lower bound for row, lb2 is the lower 3.2.7.1 Function
bound for column, ub1 is the upper bound for row and
ub2 is the upper bound for column. A function is a set of statements that together perform
a task. Every C program has at least one function which
1. Row Major Order: is main(), and programs can have additional functions.
Address (arr[i][j]) = BA+ [i-lb1) * Nc+ In other words, a function is a self-contained block,
(j-lb2)] * c which takes some input and gives output after processing
2. Column Major Order: (Fig. 3.5). A function is known with various names such
as a method or a sub-routine or a procedure, etc.
Address (arr[i][j]) = BA + [j - lb2) * Nr +
(i - lb1)] * c
Input x
where BA is the base address, Nr is the number of
rows = (lb2 − lb1 + 1) and Nc is the number of
columns = (ub2 − ub1 + 1). Function F
Output ƒ(x)
Problem 3.1: Consider the following array:
a[1 … … 500] Figure 3.5 | A view of function.
Base address = 1000
Size of each element = 3 bytes
Find address of a[397]. Example 3.1
Solution: intavg(inta,intb,intc){
float result;
Address (a[397]) = BA + (i − lb) * c result = (a+b+c)/3;
= 1000 + (397 − 1) * 3 return result;
}
= 1000 + 396 * 3
= 2188
Parts of a Function
A function has the following parts:
Problem 3.2: Consider the following array:
1. Function prototype
a[50 … … 299][299 … … 500] 2. Definition of a function
Base address = 0 3. Function call
4. Actual and formal arguments
Size of each element = 5 5. Return statement
Find the address of a[250][499] by row major order.
These parts have been discussed in detail as follows:
Solution: 1. Function prototype: Function prototype con-
Address(arr[i][j])= BA +[i−lb1)* Nc tains function declaration, which tells the compiler
+(j−lb2)]* c about a function name, return type, argument
Address(a[250][499])= BA +[(250−50)* 201 types and function calling. Function declaration
is necessary before calling it. A full declaration
+(499 − 299)] * 5
includes the return type and the type of arguments.
= 0 +(200 * 202 + 200)* 5 Function declaration will be as follows:
= 203000
return_type function_name (parameter list);
For the above definition of function, the avg() 5. Return statement: When a return statement
function declaration is as follows: gets executed, then the function returns the value
intavg(int a, int b, int c); and transfers the control to the calling function.
Execution continues in the calling function by
In function declaration, the arguments are not following the remaining statements. A return state-
important, only their type is required. So, the ment can also return a value to the calling function.
following declaration is also correct:
intavg(int, int, int); Types of C Functions
2. Definition of a function: Function definition The following are two types of functions in C on the
consists of the following parts: basis of whether it is defined by a user or not:
•• Function name: This is the actual name of the
1. Pre-defined function: The function whose
function. It is unique. Function signature is con-
definition is already stored in the library of the
stituted with the function name and parameter
respective language is called pre-defined func-
list together.
tion. These functions are provided in the system
•• Parameters: At the time of function declara-
or particular language library. For example, in C
tion, the parameters are passed into the func-
language, printf(), scanf(), gets(), puts() are avail-
tion. The parameter list shows the type, value
able in stdio.h header file. These functions are also
of parameter and number of arguments in the
called library functions or built-in functions.
function. Parameters field is optional so that a
2. User-defined function: User-defined functions
function may contain no parameters.
are functions created by the user at the time of
•• Function body: The function body contains a
writing the program for modularity purpose. For
collection of statements that defines what the
example,
task is performing by that function.
•• Return type: A function returns a value. The int max (int num1, int num2){
return type is that data type in which a function int result;
should return a value. Some functions perform if(num1 > num2)
the desired operations without returning a value. result = num1;
There are two possibilities, the function either else
returns a value or not. When the function does result = num2;
not return a value then the void data type used. return result;
}
In the above example, the function name is avg,
the function has three integer-type parameters and
the function calculates the average of those three Function Advantages
numbers. Function has the following advantages:
3. Function call: In function call, the control is 1. It provides the reusability of code in an easy manner.
transferred to the called function when the pro- 2. It makes debugging and editing easier.
gram calls the respective function. The name of 3. It reduces the size of a program.
the function must match with the function exactly 4. It makes the logic of the program easier to design
with the name defined in the function prototype. A and understand.
called function performs a defined task, and when
its return statement is executed, it returns program 3.2.8.2 Recursion
control back to the main program. To call the func-
tion, the first step is to pass the arguments with When the function calls itself then it is called recursion.
function name, and then the return value stores in In C language, there is provision for the function to call
a specific manner. itself. When using the recursion, it is necessary to have
4. Actual and formal arguments: A parameter is exit condition from the function; otherwise, the result
a special kind of variable used in a function to refer will be infinite.
to the data provided as input to the function. These
pieces of data are called arguments. Syntactically, Writing Recursive Functions
we can pass any number of parameters to a function.
Parameters are specified within a pair of parenthe- A recursive function has the following two parts:
sis. These parameters are separated by commas (,). 1. Base case: It is the non-recursive solution and a
Parameter written in a function definition is called stopping condition.
`formal parameter’. Parameter written in a func- 2. Recursive case: It is the recursive solution of the
tion call is called `actual parameter’. problem.
3.2.9 Parameter Passing In the call-by-value mechanism, only the formal argu-
ment (variables receiving value in called function from
There are various types of parameter-passing techniques calling function, that is, x and y in the above program)
in programming languages. The parameter passed is gets changed and do not reflect in actual argument (vari-
based on the program requirement. According to the able in function call, that is, a and b in function call to
parameter passing, the passing parameter depends on exchange(a, b)).
the way the calling function calls the called function.
The C programming language supports the following 3.2.9.2 Call-by-Reference Parameter-
two types of parameter-passing techniques: Passing Technique
1. Call by value In call by reference, the parameter is passing through the
2. Call by reference actual address of the value. The address of the variable
never changes throughout the execution of the program.
3.2.9.1 Call-by-Value Parameter-Passing There is a possibility to access and modify the value of
Technique the variable by using a pointer. In case of any changes
in the parameter inside the function, there is a change of
When we call a function, we pass the parameter to the the actual parameter. For example, the declaration of a
called function and it is by default passed by the value variable is as follows:
of variable in the calling function. This is called `call by
int x = 20; which tells the compiler:
value’.
1. To allocate 2-byte memory location on stack frame
of that particular function in which it is declared.
Example 3.4
2. To hold value of type integer and also associate
void exchange(int x, int y); this address with name x.
main() 3. This memory location is initialised with value 20.
Output
Figure 3.6 | Memory map in call by reference. a = 10 b = 20
a = 20 b = 10
The selection of address for a particular variable is com-
piler dependent and is always a whole number. In Fig. 3.6, Consider the declaration of a variable. int *x; does
the value 20 can be accessed by using variable name x not mean that x is going to hold integer value, rather it
and address 1000. The symbol `&’ is used to represent simply means it is going to hold address (memory loca-
the `address of’. tion) of integer type of variable. We are passing address
For example, expression &x in the above case returns of variables a, b to function exchange(), so while receiv-
address of variable x, which happens to be 1000. ing we are using two pointers to integer.
An address is always positive, we use operator %u for Generally, we use call-by-value mechanism if we do
unsigned integer. *’ is a special operator in C used as not need the changes made in calling function to reflect
`value at address’. It is also called indirection operator. in the called function. But if we require the changes to
For example, *(&x), which means value at reflect in the called function, we use the call-by-reference
address(&x), that is, value at address (1000). The exam- mechanism.
ple given below returns the address of a variable, the Also, if we want to return more than one value to the
value of the variable and the value of variable using called function from the calling function, we go for call-
indirection operator. by-reference value, which is not possible ordinarily.
3.2.12.1 Local Variables
3.2.10 Structures and Unions
A local variable is that variable which is declared in
Structures are used to represent a record (e.g. library). A the body of the main function. It can be used only by
union is a special data type in C, which is used to store the function in which it declares. Other function has no
different data types in the same memory location. Table information about local variable. Formal parameter of a
3.2 shows the comparison of the structures and union. function is also treated as a local variable to that func-
tion. In the following example, num, sum, r are local
Table 3.2 | Comparison between structure and union variables.
Structure Union
Example 3.6
1. T
o define a structure, 1. T
o define union, the
the `struct’ keyword `union’ keyword is #include<stdio.h>
is used. used. int main(){
/* Local Variable Declaration*/
2. W
hen a structure 2. W
hen a union int num,sum=0,r;
variable is created, variable is created, printf("Enter a number: ");
the compiler allocates the compiler allocates scanf("%d",&num);
memory for this memory for that while(num){
variable equal to variable equal to the r=num%10;
the sum of size of maximum size of num=num/10;
structure elements. union element. sum=sum+r;
3. E
ach structure element 3. Individual members }
within a structure is of the union share the printf("Sum of digits of number: %d",sum);
assigned to unique memory allocated. return 0;
}
memory location.
4. M
ore than one 4. O
nly one member
structure element can can be initialised at a Variables num, sum and r are local to the function main(),
be initialised at once. time. and cannot be accessible outside the main function.
5. Individual members 5. O
nly one member can
can be accessed at a be accessed at a time. 3.2.12.2 Global Variables
time.
Global variables are those variables which are defined
outside the body of the main function. The global
3.2.11 Enumerated Data Types variables will hold their value throughout the lifetime
of the program. They can be accessed inside any of the
Enumerated data types assume values which are previ- functions defined for the program. Following is an exam-
ously declared. For example, ple using local variable and global variable.
•• If there is more than one executable using the The basic operations on stack are as follows
module at the same time, then multiple copies 1. PUSH: To add an element to the stack.
of it are used in memory. 2. POP: To remove an element from the stack.
3.2.13.2 Late Binding
3.3.1 PUSH Operation on Stack
In late binding, the linker copies only a stub code for the
referenced module into the executable image. It is also When we try to add elements to the stack then
known as dynamic binding. The stub code loads the ref- the o peration is called PUSH operation on stack
erenced module into memory at load/run time. (Fig. 3.7). The element is placed only on the top of
the stack and then the stack position gets increased
1. Advantages of late binding: by 1.
•• The size of the executable image is small.
•• On changing the referenced module, re-link of
the executable is not required.
•• Most operating systems can share the referenced
module. D
2. Disadvantages of late binding: C D C
•• The executable is dependent on the shared B PUSH B
library at runtime. A A
•• Since the module is shared, it must be re-entrant STACK BEFORE STACK AFTER
and thread safe. Figure 3.7 | PUSH operation on stack.
EMPTY
STACK
TOP 15
12 TOP 12
10 10 10 TOP
5 5 5 5 TOP
Following are the applications on stack: (a) If the operator on the top of the stack has
lower precedence, then push the new opera-
1. Parsing: Stacks are used by compilers to check
tor onto the stack.
the syntax of a program and for generating execut-
(b) Else, pop the operator from the top of the
able code.
stack and append it to the output string.
2. Reversing a list: Stack can be used for reversing
Then push the new operator onto the
a list.
stack.
3. Calling function: When a function is called all
local storage for the function is allocated on the (c) Otherwise,
stack and return address is also stored on the stack. (i) If the token is an open parenthesis, then
4. Recursive function: Stack can be used for push it onto the stack.
implementing recursive functions. (ii) If the token is a close parenthesis, then
5. Expression conversion: pop and append the operators from
•• Infix: An infix expression is one in which opera- the stack until the open parenthesis is
tors are located between their operands. This is popped. Discard both parentheses.
Solution:
(A + B) * (C − D) Empty Initial
A + B) * (C − D) ( Push
+ B ) * (C − D) ( A Print
B) * (C − D) (+ A Push
) * (C − D) (+ AB Print
Infix to Prefix Conversion 3. Apply algorithm infix to postfix on the expression
that comes from step 2.
Algorithm for infix to prefix conversion:
4. And finally reverse the output of step 3.
1. Reverse the given infix expression.
2. Make every `(` as ’)’ and every `)’ as `(’.
Solution:
Step 1: Reverse the infix expression.
5 ∧E + D*) C ∧B + A (
Step 2: Make every `(` as ’)’ and every `)’ as `(’
5 ∧E + D * (C ∧B + A)
Step 3: Convert expression to postfix form.
Table | Continued
Expression Stack Output Comment
D * (C ∧B + A) + 5E ∧ Pop and push
∧ ∧
*(C B + A) + 5E D Print
(C ∧B + A) +* 5E ∧D Push
C ∧B + A) +*( 5E ∧D Push
∧ ∧
B + A) +*( 5E DC Print
∧ ∧
B + A) +*( 5E DC Push
∧ ∧
+ A) +*( 5E DCB Print
∧ ∧
A) +*(+ 5E DCB Pop and push
∧ ∧
) +*(+ 5E DCB A Print
∧ ∧
End +* 5E DCB A+ Pop until `(’
∧ ∧
End Empty 5E DCB A+*+ Pop every element
A D I
A
C E H
C X
F B G A D I C E H
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
E M S O Figure 3.17 | Storage representation.
3. Inorder V = {a, b, c, d, e} and E = {(a, b), (a, c), (a, d), (b, e),
•• Traverse the left-most subtree starting at the (c, d), (c, e), (d, e)}
left external node
•• Traverse the root
3.6.6.1 Basic Terminology
•• Traverse the right subtree starting at the left
external node Following are the basic terms used for graphs (see
figure 3.19):
Problem 3.6: Consider the given tree and find the 1. Undirected graphs: It consists of a set V
inorder, preorder and postorder of the tree. of vertices and a set E of edges, each of them
connecting to two different vertices.
9 2. Directed graph: In this, edges provide a
connection from one vertex to another, but not
4 17 necessarily in the opposite direction.
3. Adjacent vertices: Connected by an edge.
4. Degree of a vertex: It is defined as the number
3 6 22 of adjacent vertices.
5. Path: It is defined as a sequence of vertices such
5 7 20 that consecutive vertices are adjacent.
6. Simple path: Path with no repeated vertex.
7. Cycle: A simple path, where the first and last
Solution: vertex are same.
8. Connected graph: When any two vertices are
Inorder Traversal: connected by some path.
The inorder traversal of the above tree will output: 9. Subgraph: When a subset of vertices and edges
form a graph.
3, 4, 5, 6, 7, 9, 17, 20, 22
10. Tree: A connected graph without cycles.
Preorder Traversal: 11. Balanced binary tree: A binary tree in which no
The preorder traversal of the above tree will output: leaf is at much greater depth than any other leaf.
Example of balanced binary search trees are red-
9, 4, 3, 6, 5, 7, 17, 22, 20 black trees, AVL trees, etc. Examples of non-binary
Postorder Traversal: balanced search trees are B trees, B+ trees, etc.
The postorder traversal of the above tree will output:
3, 5, 7, 6, 4, 20, 22, 17, 9 3.6.6.2 Traversing a Graph
a b a b a b a b a b
c d c d c d c d
d e Connected Path Disconnected Tree
Figure 3.18 | A graph G = (V, E). Figure 3.19 | Examples showing connected, path, disconnected and tree graphs.
Example 3.9 2
b
1 c
b
a
c e
a h
e
d i
i
g
f
f
(iii)
2
b b
1
a
a c
e
Q = {a}
i
i
3 Q = {f,i,c,e}
f
f
(i) (iv)
b b
1
a
c
a
i
i
Q = {b,f,i} f g
3
(ii)
f
(v)
2 2
b b 5
1 c
c
1 a 6 h
8
e
a d
4
e
i 7
g
3
i
g f
3
(ix)
f
Q = {i,c,e,g}
(vi)
b
2
b 5
a c
c
1 h
e
a d
i
e d
g
4
i f
Q = {h}
g
3 (x)
f
(vii)
b
b c a c
e
e h
a d
i d
g f g
i
f Q = {e,g,d} {a,b,f,i,c,e,g,d,h}
(viii) (xi)
2. Depth first traversal: It is a preorder traversal before returning to the current node and then tra-
of an ordered tree. It first traverses one subtree verses another subtree. It uses stack.
Example 3.10 2
b
1
b
a c
a c e
e h i
i
d
g f
f (iii)
2
b b
1 1 3
a a c
i i
f f
(i) (iv)
2 2
b b
3
1 1 c
a a
e
d
i i
f
f
(ii) (v)
2 2
b b 3
3 c
1 1
a c h
a e
4
4
d
e
d
i i 5
g
f
f
(vi) (ix)
2 2
b b 3
3
1 c h
c 1 6 4
a h
a e d
e 4
d 5
i
i g
g
f f
(vii) (x)
2 2
b b 3
c h
1 3 1 6 4
a c a e
h d
4 5
e d
i g
i
5
g
7
f f
(viii) (xi)
2 Source
b 8 a
3
h 2
c 5
1 6 4 3
a e 6
d e b
5 10
1
i g 4
2
d c
7
2
Figure 3.20 | Graph for finding the shortest path.
f
(xii)
5 Source
g a
7
2
f 5
3
(xiii) 6
e b
10
b 1
4
2
a c h d c
2
e d
a
i g S = {a}
5
f 2
{a,b,c,d,g,e,f,h,i}
e b
(ix) d=2 d=5
3
3.6.6.3 Shortest Path
d c
For a given directed graph, where each edge has a non-
negative weight or cost, the shortest path problem is to d=∞ d=3
find a path of least total weight from the source to every
other vertex in the graph (Fig. 3.20). (i)
3.6.6.4 Spanning Tree
a
5 S = {a,e} A spanning tree of a graph G is a tree which contains all
2
3 the vertices of the graph G. See Fig. 3.21.
6
d=2 e b d=5 a b a b
10
4
c d e c d e
d c
Figure 3.21 | Spanning tree of a graph.
d=6 d=3
(ii)
Minimum Spanning Tree
a Minimum spanning tree in an undirected connected
S = {a,e,c} weighted graph is a spanning tree with minimum weight.
2 5
3 Prim’s algorithm:
e 1. Begin with all the vertices.
d=2 b d=4
2. Choose and draw any vertex.
3. Find the edge of least weight joining a drawn
4 vertex to a vertex not currently drawn. Draw the
1
weighted edge and the corresponding new vertex.
d c 4. Repeat step 3 until all the vertices are connected,
2
d=3 then STOP.
d=5
(iii)
Example 3.12
a S = {a,e,c,b}
b 10 e
2
4 8 7 6
e 3 b d
d=4
a 9 5 g
d=2 6 1 2 9
8 2
d c c 1 f
2
d=5 d=3 (i)
(iv)
Step 1
2
Closest
e b U V−U Low Cost
3 d=4
d=2 b A 4
1 c A 8
d A ∞
d c
2 e A ∞
d=5 d=3
f A ∞
(v) g A ∞
b 10 e 4 8 7 6
4 8 7 6 a 9 g
d 5
d 2 9
a 9 5 g 2
2 9 8
8 2 c 1 f
(iv)
c 1 f
Step 4
(ii)
U = {a, b, c, d}, V − U = {e, f, g}
Step 2 Closest
U = {a, b}, V − U = {c, d, e, f, g}
U V−U Low Cost
e D 7
Closest
f C 1
U V−U Low Cost
g A ∞
C A 8
D B 8 Select vertex f to include in U.
E B 10 b 10 e
F A ∞
4 8 7 6
G A ∞
d
a 9 5 g
Select vertex d to include in U. 2 9
8 2
b 10 e
c 1 f
4 8 7 6
(v)
d
a 9 g Step 5
5
2 9 U = {a, b, c, d, f }, V − U = {e, g}
8 2
Closest
c 1 f
U V−U Low Cost
(iii)
e F 5
Step 3 g F 2
Step 6 4
U = {a, b, c, d, f, g}, V − U = {e} 44
2 3
Closest 17 78
U V−U Low Cost 1 2 1
e F 5 32 50 88
1 1
48 62
Select vertex e to include in U.
b 10 e
Rotation
3.6.6.5 AVL Tree
It is the restructuring of the tree which maintains the
AVL tree is a binary tree which satisfies the height balance binary search tree property.
property (Fig. 3.22). It has a time complexity of O(log(n)). 1. Types of Rotation:
•• Single-Left rotation: Refer Fig. 3.23.
Z
Original tree
Y Y ZR
X Z Single-Left
X ZL
rotation
XL XR ZL ZR XL XR
Original tree XL Y
Y
Single-Right XR Z
X Z rotation
XL XR ZL ZR
ZL ZR
XL X ZR XL ZL ZR YR
Z
ZL ZR XL ZL
3.6.6.6 Binary Heap or equal to the root element. This binary heap (see
Fig. 3.27) is known as min-heap. In addition, if all the
A complete binary tree is said to be binary heap if all elements are lesser or equal to the root element, this is
the elements below in hierarchy are either greater than called max-heap.
1. The height of a binary heap is O(log n). The
runtime of deleteMin, insert and remove is
6
O(log n).
2. The root node is the highest priority element. To
remove the highest/lowest priority object (root),
7 12 heap data structure is preferred. Priority queue is
the best example to be implemented.
3. The running time of heap sort is O(nlog n).
10 15 17
IMPORTANT FORMULAS
1. Insertion/Deletion in array: O(n) where lb is the lower bound of array and ub is the
upper bound of array.
2. Split/Merge in array: O(n)
Suppose we want to calculate the ith element
3. Time complexity of Push(): O(1) address, then
4. Time complexity of Pop(): O(1) Address (arr[i]) = BA + (i − lb) * c
5. Time complexity of Enqueue(): O(1)
where BA is the base address of array and lb is
6. Time complexity of Dequeue(): O(1) the lower bound of array and c is the size of each
7. Number of elements in queue = element
8. Number of nodes in full binary tree: 2h+1 −1 A[lb1 … … ub1][lb2 … … ub2]
[h: levels] where lb1 is the lower bound for row, lb2 is the
9. Number of leaf nodes in full binary tree: 2h lower bound for column, ub1 is the upper bound for
row and ub2 is the upper bound for column.
10. Number of waste pointers in complete binary tree
of n nodes: n + 1 Row major order
Address (arr[i][j]) = BA + [i − lb1) * Nc +
11. Complexity of inorder, preorder and postorder tree
(j − lb2)] * c
traversal: O(n)
12. Minimum number of moves for tower of Hanoi:
2n − 1 Column major order
2n
13. Number of unique binary trees: n
C Address (arr[i][j]) = BA + [j − lb2) * Nr +
n +1 (i − lb1)] * c
14. One-dimensional arrays where BA is the base address, Nr is the number of
In one dimension, an array `A’ is declared as: rows = (lb2 − lb1 + 1), and Nc is the number of
A[lb … … ub] columns = (ub2 − ub1 +1).
SOLVED EXAMPLES
(c) Spanning tree cannot have at most two edges (a) Associativity
repeated. (b) Commutativity
(d) Spanning tree cannot be minimum and (c) Mathematical induction
maximum. (d) Factorial
Solution: A spanning tree is a subgraph of a given Solution: Mathematical induction is the method
graph G, which covers all the vertices of G and through which correctness of recursive function can
should be a tree. Spanning tree could be minimum be proved.
or maximum. Ans. (c)
Ans. (d)
11. In a doubly linked list, the number of pointers
9. Which of the following has compilation error in C? affected for an insertion operation will be:
(a) int n = 17; (a) 4
(b) char ch = 99; (b) 0
(c) float f = (float) 99.32; (c) 1
(d) #include<stdio.h> (d) Depends upon the nodes of the doubly linked
list.
Solution: The syntax for inclusion of header file
is #include <stdio.h>. There should be space Solution: Let a node X be inserted after node 1,
between #include and <stdio.h>. then both pointer of node X(Prv and Nxt) will be
Ans. (d) affected and node 1’s Nxt pointer will point to node
X and node 2’s Prv pointer will also point to node
10. is often used to prove the correctness X. So, total four pointers will be affected.
of a recursive function.
Ans. (a)
12. The queue data structure is to realised by using Solution: Let there are 6 elements (1, 2, 3, 4, 5
stack. The number of stacks needed would be: and 6). First we will push them in stack 1 and then
pop from stack 1 and push in stack2. The same
(a) It cannot be implemented.
behaviour will be observed when we will pop from
(b) 2 stacks.
stack2
(c) 4 stacks.
(d) 1 stacks.
Element6 Element1
Element5 Element2
Element4 Element3
Element3 Element4
Element2 Element5
Element1 Element6
Stack1 Stack2
Solution:
(A*B − (C *D))/(F/D + E)
*B − (C *D))/(F/D + E) A (
B − (C *D))/(F/D + E) A (*
− (C *D))/(F/D + E) AB (*
(C *D))/(F/D + E) AB* (−
*D))/(F/D + E) AB*C (−(
D))/(F/D + E) AB*C (−(*
/(F/D + E) AB*CD (−(*))
/(F/D + E) AB*CD*−
(F/D + E) AB*CD*− /
/D + E) AB*CD*−F /
D + E) AB*CD*−F /(/
+ E) AB*CD*−FD /(/
E) AB*CD*−FD/ /(+
AB*CD*−FD/E /(+)
AB*CD*−FD/E+/
Ans. (a)
14. There are six nodes. The different types of trees Solution: Passing an element of an array by call
that can be realised are . by name behaves similar to call by value. Therefore,
if array elements are passed as parameter then they
(a) 10 (b) 64
can produce different results for call-by-reference
(c) 58 (d) 65
and call-by-name parameter passing.
Solution: 58 trees can be realized. Ans. (d)
Ans. (c)
16. A variant record in Pascal is defined by
15. In which of the following case(s) is it possible to
obtain different results for call-by-reference and typevarirec = record
number: integer;
call-by-name parameter passing
case (var1, var2) of
(a) Passing an expression as a parameter var1; (x, y : integer)
(b) Passing an array as a parameter var2: (p,q: real)
(c) Passing a pointer as a parameter end
(d) Passing an array elements as a parameter end
Suppose an array of 100 records was declared on a {float y (4 bytes) and long z(8 bytes)} 12 bytes.
machine which uses 6 bytes for an integer and 10 So, total size will be 22 bytes (10 + 12).
bytes for a real. How much space would the com- Ans. (a)
piler have to reserve for the array
(a) 3800 (b) 3200 19. In a compact single-dimensional array represen-
(c) 2800 (d) 4000 tation for lower triangular matrices (i.e. all the
elements above the diagonal are zero) of size n × n,
Solution: There are 100 records non-zero elements (i.e. elements of the lower
So 600 B for `record no’: [100 × 6] triangle) of each row are stored one after another,
starting from the first row, the index of the (i,j)th
1200 B for var(x, y): [so, (6 + 6)*100] element of the lower triangular matrix in this new
2000 B for var(p, q) : [so, (10 + 10)*100] representation is
Ans. (a) (a) i + j (b) i + j −1
17. What is the result of the following program? i −1 j ( j − 1)
(c) ( j − 1) + (d) i +
Program side-effect (input, output) 2 2
var x, result: integer;
Function f (var x: integer): integer; Solution: To find location in lower triangular
begin matrix formula is given as
x: x+1;
f:=x; i (i − 1)
LOC (i,j ) = ( j − 1) +
end 2
begin
x:=5; Ans. (c)
result:=f(x)*f(x);
writeln (result) 20. The following sequence of operation is performed
end on a stack:
(a) 5 (b) 25 PUSH(10), PUSH(20), POP, PUSH(10),
(c) 36 (d) 42 PUSH(20), POP, POP, POP, PUSH(20), POP
Solution: Function `f ’ uses `x ’ as local variable. The sequence of values popped out is
So value of `x’ does not change globally and both
(a) 20, 10, 20, 10, 20 (b) 20, 20, 10, 10, 20
the time x = 5 is passed to the function `f ’.
(c) 10, 20, 20, 10, 20 (d) 20, 20, 10, 20, 10
Ans. (c)
Solution:
18. Consider the following C declaration
struct { Operation Stack Popped
short s [5] Elements List
union{
float y; Push 10
long z; Push 10, 20
}u;
Pop 10 20
}t;
Push 10, 10 20
Assume that objects of the type short, float and
Push 10, 10, 20 20
long occupy 2 bytes, 4 bytes and 8 bytes, respec-
tively. The memory requirement for variable t, Pop 10, 10 20, 20
ignoring alignment considerations, is Pop 10 20, 20, 10
(a) 22 bytes (b) 18 bytes Pop 20, 20, 10, 10
(c) 14 bytes (d) 10 bytes Push 20 20, 20, 10, 10
Solution: The structure is created with total Pop 20, 20, 10, 10, 20
size of `short and union’ short have size of 2 byte,
as it is an array of five elements so it will take So, option (b) is correct.
10 bytes. Union will consider the maximum of Ans. (b)
21. The postfix expression for the infix expression Postfix conversion steps
A + B * (C + D)/F + D * E is A + B * CD + F/+ DE*
(a) AB + CD +* F/D + E* A + BCD +*F/DE*+
(b) ABCD + *F/DE *++ ABCD +*F/DE*++
(c) A * B + CD/F * DE++
(d) A + * BCD/F * DE++ So, option (b) is correct.
Ans. (b)
Solution: Given expression A + B * (C + D)/F
+D*E
1. Consider the following C function. Solution: B[1] is address of second one dimen-
float f(float x, int y) { sional array. Address can not be assigned to simple
float p, s; int i; variable. So it will produce compile time error.
for (s=1,p=1,i=1; i<y; i++) { Ans. (a)
p *= x/i;
3. Let T(n) be the number of different binary
s+=p;
search trees on n distinct elements. Then T(n) =
} n
return s; ∑T (k − 1) T (x), where x is
} k =1
For large values of y, the return value of the func- (a) n − k + 1 (b) n − k
tion f best approximates (c) n − k − 1 (d) n − k − 2
(a) xy (b) ex (c) ln(1 + x) (d) xx (GATE 2003: 1 Mark)
(GATE 2003: 1 Mark)
Solution:
Solution: n
Applying iterative method: T(n) = ∑ T (k − 1) T (x)
k =0
i=1 p = x/1 s=1+x T(n) = T(x) [T(0) + … + T(n−1)]
i =2 p = x * x/2 s = 1 + x + x2/2 x=n−k+1
i=3 p = x3/ 6 s = 1 + x + x2/2 + x3/ 6 Ans. (a)
I. Deletion of the smallest element to the start of the pop operation that removes m
II. Insertion of an element if it is not already from S. The average stack-life of an element of this
present in the set stack is
Which of the following data structures can be used (a) n(X + Y). (b) 3Y + 2X.
for this purpose? (c) n(X + Y) −X. (d) Y + 2X
(a) A heap can be used but not a balanced binary (GATE 2003: 2 Marks)
search tree.
(b) A balanced binary search tree can be used but
Solution : Time taken by Pop and Push
not a heap.
opé rations : X + X = 2X
(c) Both balanced binary search tree and heap can
be used. Time delay between two stack operations = Y
(d) Neither balanced binary search tree nor heap Total time taken = 2X + Y
can be used. Ans. (d)
(GATE 2003: 2 Marks)
7. Consider the following 2−3−4 tree (i.e. B-tree with
a minimum degree of two) in which each data item
Solution: Time taken by heap to insert and
is a letter. The usual alphabetical ordering of let-
delete n elements is O(n). Only balanced binary
ters is used in constructing the tree.
search tree takes O(log n) time for insertion and
deletion.
Ans. (b)
(a) P (b) P
GL U HL U
B HI N QT VXZ BG I N QT VXZ
(a) (b)
BGH L N Q T VXZ
Solution: 2-3-4 B tree has minimum degree 2 and maximum 4. According to max degree, atmost 3 elements can
be there in node.
L P U L P
G
VXZ VXZ
BHI BGH
N QT N Q
I P U
BGH L N Q T VXZ
Ans. (c)
Common Data Questions 8 and 9: The following Solution: In dynamic scoping, the variables and
program fragment is written in a programming values are resolved at run time.
language that allows global variables and does not P(100 + 5) = P(105)
allow nested declarations of functions. First Print x + 10 will print 115
global int i = 100, j = 5; Second Print x will update x = 200 + 20 = 220 and
void P(x) { will print 220
int i = 10; Ans. (a)
print(x + 10);
i = 200; 10. In the following C program fragment, j, k, n and
j = 20; TwoLog_n are integer variables, and A is an array
print (x); of integers.
}
The variable n is initialised to an integer ≥ 3,
main() {P(i + j);}
and TwoLog_n is initialised to the value of n
8. If the programming language uses static scoping 2*log2(n)
and call by need parameter passing mechanism, for (k=3; k <= n; k++)
the values printed by the above program are A[k] = 0;
(a) 115, 220. (b) 25, 220. for (k=2; k <= TwoLog_n; k++)
(c) 25, 15. (d) 115, 105. for (j=k+1; j <= n; j++)
A[j] = A[j] || (j%k);
(GATE 2003: 2 Marks) for (j=3; j <= n; j++)
if (!A[j]) printf("% d", j);
Solution: In static scoping, the variables and
values are resolved at compile time. The set of numbers printed by this program frag-
P(100 + 5) = P(105) ment is
Print x + 10 will print 115 (a) {m m ≤ n, (∃i) [m = i!]}
Print x will print 105 (b) {m m ≤ n, (∃i) [m = i2]}
Ans. (d) (c) {m m ≤ n, m is prime}
(d) {}.
9. If the programming language uses dynamic scoping (GATE 2003: 2 Marks)
and call-by-name parameter-passing mechanism,
the values printed by the above program are Solution: The condition ! A[j] is equivalent to A[j] =
(a) 115, 220. (b) 25, 220. = 0. But in array A no element is zero. So it will
(c) 25, 15. (d) 115, 105. print nothing.
(GATE 2003: 2 Marks) Ans. (d)
11. Consider the C program shown below. (a) The list is empty or has exactly one element.
(b) The elements in the list are sorted in non-
#include <stdio.h>
decreasing order of data value.
#define print(x) printf("% d —, x)
int x; (c) The elements in the list are sorted in non-
void Q(int z) { increasing order of data value.
z += x; print(z); (d) Not all elements in the list have the same data
} value.
void P(int *y) { (GATE 2003: 2 Marks)
int x = *y+2;
Q(x); *y = x-1; Solution: The given function returns 1 if the
print(x); elements are unique and are sorted increasing
} order.
main(void) {
x = 5; Ans. (b)
P(&x)
print(x); 13. Consider the following class definitions in a
} hypothetical object oriented language that sup-
ports inheritance and uses dynamic binding. The
The output of this program is language should not be assumed to be either Java
(a) 12 7 6 (b) 22 12 11 or C++, though the syntax is similar.
(c) 14 6 6 (d) 7 6 6
class P Class Q subclass of
(GATE 2003: 2 Marks) { P
void f(int i) {
Solution: { void f(int i)
P(&x) where x = 5 print(i); {
} print(2*i);
x = *y + 2 = 5 + 2 = 7 } }
Q(x) = Q (7) }
→ Here z = 7 Now consider the following program fragment:
→ z = z + x = 7 + 5 = 12 Px = new Q();
→ Print 12 Qy = new Q();
*y = x − 1 = 7 − 1 = 6 Pz = new Q();
print(x) = print 7 x.f(1); ((P)y).f(1); z.f(1);
Value returned by function P is 6. So main will where ((P)y) denotes a typecast of y to P. The
print 6. output produced by executing the above program
So, answer is 12 7 6 fragment will be
14. Which of the following is NOT an advantage ends of the array. Variables top 1 and top 2 (top
of using shared, dynamically linked libraries as 1 < top 2) point to the location of the topmost
opposed to using statically linked libraries? element in each of the stacks. If the space is to be
used efficiently, the condition for `stack full’ is
(a) Smaller sizes of executable files
(b) Lesser overall page fault rate in the system (a) ( top 1 = MAXSIZE/2) and (top 2 =
(c) Faster program startup MAXSIZE/2 + 1)
(d) Existing programs need not be re-linked to take (b) top 1 + top 2 = MAXSIZE
advantage of newer versions of libraries (c) (top 1 = MAXSIZE/2) or (top 2 = MAXSIZE)
(GATE 2003: 2 Marks) (d) top 1 = top 2 − 1
(GATE 2004: 1 Mark)
Solution: The shared, dynamic linked libraries
use smaller sizes of executable files, lesser overall Solution: If we are to use space efficiently then
page fault rate and faster startup of programs. size of any stack can be more than MAXSIZE/2.
Ans. (d) Both stacks will grow from both ends and if any
of the stack top reaches near to the other top then
15. The goal of structured programming is to
stacks are full. So the condition will be top1 =
(a) Have well-indented programs. top2 −1 (given that top1 < top2)
(b) Be able to infer the flow of control from the Ans. (d)
compiled code.
18. The following numbers are inserted into an empty
(c) Be able to infer the flow of control from the
binary search tree in the given order: 10, 1, 3, 5,
program text.
15, 12, 16. What is the height of the binary search
(d) Avoid the use of GOTO statements.
tree (the height is the maximum distance of a leaf
(GATE 2004: 1 Mark) node from the root)?
Solution: The goal of structured programming is (a) 2 (b) 3
that the user can control the flow according his (c) 4 (d) 6
requirement. (GATE 2004: 1 Mark)
Ans. (c)
Solution:
16. Consider the following C function
10
void swap (int a, int b)
{ 1 15
int temp;
temp = a ;
3 12 16
a=b;
b= temp ;
} 5
Ans. (b)
In order to exchange the values of two variables x
and y: 19. Given the following input (4322, 1334, 1471, 9679,
1989, 6171, 6173, 4199) and the hash function x mod
(a) Call swap(x, y)
10, which of the following statements are true?
(b) Call swap(&x, &y)
(c) swap(x, y) cannot be used as it does not return I. 9679, 1989, 4199 hash to the same value.
any value. II. 1471, 6171 hash to the same value.
(d) swap(x, y) cannot be used as the parameters III. All elements hash to the same value.
are passed by value. IV. Each element hashes to a different value.
(GATE 2004: 1 Mark) (a) I only (b) II only
(c) I and II only (d) III or IV
Solution: The value will not be interchanged. The
(GATE 2004: 1 Mark)
values are passed by value, not by reference.
Ans. (d) Solution:
17. A single array A[1..MAXSIZE] is used to implement Mod 10 of all the elements in the list is given below:
two stacks. The two stacks grow from opposite
Solution: Stack is used to check balancing of Solution: A loop invariant is a condition that must
parenthesis. be true before and after each iteration of a loop. So
Ans. (b) n = d1d2…dm−1 and rev = dmdm−1…dm−1+1 pro-
21. Level order traversal of a rooted tree can be done vides the correct loop invariant condition.
by starting from the root and performing Ans. (a)
(a) Preorder traversal. (b) Inorder traversal. 24. Consider the following C program segment:
(c) Depth first search. (d) Breadth first search. char p [20]
(GATE 2004: 1 Mark) char * s = "string";
int length = strlen (s);
Solution: Breath first search gives the level order for (i = 0 ; i < length; i++)
traversal. p[i] = s[length - i];
Ans. (d) print f("%",p);
22. Consider the following C function: The output of the program is
int f(int n) (a) gnirts. (b) String.
{ staticint i = 1 ; (c) gnirt. (d) No output is printed.
if (n >= 5) return n;
(GATE 2004: 2 Marks)
n = n+i;
i++; Solution: In C value of pointer variable cannot be
return f(n); assigned to normal character variable.
} Ans. (d)
The value returned by f(1) is
25. A circularly linked list is used to represent a queue.
(a) 5. (b) 6. A single variable p is used to access the queue.
(c) 7. (d) 8. To which node should p point such that both the
(GATE 2004: 2 Marks) operations enqueue and dequeue can be performed
Solution: in constant time?
Iteration n i
0 1 1
1 1+1=2 2
2 2+2=4 3 Front Rear
3 4+3=7 4
4 7 ≥ 5 Return 7
P ?
Ans. (c)
36. A program P reads in 500 integers in the range 38. Consider the following C program:
[0, 100] representing the scores of 500 students. It double foo(double); /* Line 1 */
then prints the frequency of each score above 50. int main() {
What would be the best way for P to store the double da, db;
frequencies? // input da
(a) An array of 50 numbers db = foo(da);
}
(b) An array of 100 numbers
double foo(double a) {
(c) An array of 500 numbers
return a;
(d) A dynamically allocated array of 550 numbers
}
(GATE 2005: 1 Mark)
The above code compiled without any error or
Solution: We need to know the frequency of num- warning. If line 1 is deleted, the above code will
bers above 50. So, array of size 50 will be sufficient. show:
Ans. (a)
(a) No compile warning or error.
37. Consider the following C program: (b) Some compiler warnings not leading to unin-
tended results.
void foo (int n, int sum 0) {
(c) Some compiler warnings due to type-mismatch
int k = 0, j = 0;
if (n==0) return;
eventually leading to unintended results.
k = n % 10; j = n / 10; (d) Compiler errors.
sum = sum + k; (GATE 2005: 2 Marks)
foo (j, sum);
printf ("%d,", k); Solution: Compilation error will be thrown
} by deleting Line1. Function is called before it is
int main () { declared anywhere.
int a = 2048, sum = 0; Ans. (c)
foo (a, sum);
printf("%d\n", sum); 39. Postorder traversal of a given binary search tree T
} produces the following sequence of keys
What does the above program print? 10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29
Which one of the following sequences of keys can 43. Consider line number 3 of the following C program:
be the result of an inorder traversal of the tree T ?
int min ( ) { /* Line 1 */
(a) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95 int I, N; /* Line 2 */
(b) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29 fro (I =0, I<N, I++); /* Line 3 */
(c) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95 }
(d) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29 Identify the compiler’s response about this line
(GATE 2005: 2 Marks) while creating the object-module:
46. In a binary max-heap containing n numbers, the Solution: Best algorithm to find leader is pass the
smallest element can be found in time array from right side. With each traversal of node,
maximum will be updated. Hence leader can be
(a) O(n) (b) O(log n)
updated in O(n). So, option (b) is correct.
(c) O(log log n) (d) O(1)
Ans. (b)
(GATE 2006: 1 Mark)
50. An implementation of a queue Q, using two stacks
Solution: In max heap smallest element will be S1 and S2, is given below:
present in the leaf node. To get it, n nodes need to
void insert (Q, x) {
be traversed.
push (S1, x);
Ans. (b)
}
47. Let T be a depth first search tree in an undirected void delete (Q) {
graph G. Vertices u and v are leaves of this tree T. if (stack-empty(S2)) then
The degrees of both u and v in G are at least 2. if (stack-empty(S1)) then {
Which one of the following statements is true? print("Q is empty");
return;
(a) There must exist a vertex w adjacent to both }
u and v in G else while (!(stack-empty(S1))){
(b) There must exist a vertex w whose removal x=pop(S1);
disconnects u and v in G push(S2,x);
(c) There must exist a cycle in G containing u• }
and v x=pop(S2);
(d) There must exist a cycle in G containing u and }
all its neighbours in G. Let n insert and m (≤ n) delete operations be
(GATE 2006: 1 Mark) performed in an arbitrary order on an empty
queue Q. Let x and y be the number of push and
Solution: There must exist a vertex w adjacent to pop operations performed, respectively, in the pro-
both u and v in G. So, option (a) is true. cess. Which one of the following is true for all m
Ans. (a) and n?
48. A scheme for storing binary trees in an array X is (a) n + m ≤ x < 2n and 2m ≤ y ≤ n + m
as follows. Indexing of X starts at 1 instead of 0. (b) n + m ≤ x < 2n and 2m ≤ y ≤ 2n
The root is stored at X[1]. For a node stored at (c) 2m ≤ x < 2n and 2m ≤ y ≤ n + m
X[i], the left child, if any, is stored in X[2i] and the (d) 2m ≤ x ≤ 2n and 2m ≤ y ≤ 2n
right child, if any, in X[2i + 1]. To be able to store (GATE 2006: 2 Marks)
any binary tree on n vertices, the minimum size of
Solution:
X should be
Number of push operation = insert operation +
(a) log2 n (b) n delete operation
(c) 2n + 1 (d) 2n − 1 ⇒n + m
(GATE 2006: 1 Mark) ⇒n + m ≤ x
⇒ n + m ≤ x < 2n and 2m ≤ y ≤ n + m
Solution: In case of right skewed tree, the size of Ans. (a)
array will be 2n − 1.
Ans. (d) 51. Consider the following C function in which a[n] and
b[m] are two sorted integer arrays and c[n + m]
49. An element in an array X is called a leader if it is be another integer array.
greater than all elements to the right of it in X.
The best algorithm to find all leaders in an array void xyz(int a[], int b [], int c []){
int i,j,k;
(a) Solves it in linear time using a left to right pass i=j=k=0;
of the array while ((i<n) && (j<m))
(b) Solves it in linear time using a right to left pass if(a[i] < b[j])
of the array c[k++] = a[i++];
(c) Solves it using divide and conquer in time else c[k++] = b[j++];
Θ(n log n) }
(d) Solves it in time Θ(n2) Which of the following condition(s) hold(s) after
(GATE 2006: 1 Mark) the termination of the while loop?
(i) j < m, k = n + j − 1 and a[n − 1] < b[j] if i = n (c) S1 is true and S2 is false
(ii) i < n, k = m + i − 1 and b[m − 1] ≤ a[i] if j = m (d) S1 is true and S2 is true
(a) Only (i) (GATE 2006: 2 Marks)
(b) Only (ii)
(c) Either (i) or (ii) but not both Solution:
(d) Neither (i) nor (ii) S1: True, both work1 and work2 perform the same
task
(GATE 2006: 2 Marks)
S2: True, work2 will improve the performance
Solution: because it reduces calculations using temporary
x[i] ∧ ~y[i]) = only 1’s in x where corresponding variables to store results.
entry in y is 0 → x − y S1 and S2 are correct statements.
~x[i] ∧ y[i] = only 1s in y where corresponding Ans. (d)
entry in x is 0 → y − x. 54. Consider the following code written in a pass-by-
The operator “V” results in union of the above two sets. reference language such as FORTRAN and these
Ans. (c) statements about the code.
52. Given two arrays of numbers a1, ..., an and subroutine swap(ix,iy)
b1, ..., bn where each number is 0 or 1, the fastest it = ix
algorithm to find the largest span (i, j) such that L1 : ix = iy
ai + ai+1 + … + aj = bi + bi+1 + … + bj, or report L2 :iy = it
end
that there is not such span,
ia = 3
(a) Takes O(3n) and Ω(2n) time if hashing is permitted. ib = 8
(b) Takes O(n3) and Ω(n2.5) time in the key call swap (ia, 1b+5)
comparison model. print *, ia, ib
(c) Takes Θ(n) time and space. end
(d) Takes O(√n) time only if the sum of the 2n S1: The compiler will generate code to allocate a
elements is an even number. temporary nameless cell, initialise it to 13 and pass
(GATE 2006: 2 Marks) the address of the cell swap
S2: On execution, the code will generate a runtime
Solution: To find the largest span (i, j), average error on line L1
Θ(n) time and space is required. S3: On execution, the code will generate a runtime
Ans. (c) error on line L2
53. Consider these two functions and two statements S4: The program will print 13 and 8
S1 and S2 about them: S5: The program will print 13 and −2
Exactly the following set of statement(s) is correct:
int work1(int *a, int work2(int *a, int (a) S1 and S2 (b) S1 and S4
int i, int j) i, int j)
(c) S3 (d) S1 and S5
{ {
int x = a[i+2]; int t1 = i+2; (GATE 2006: 2 Marks)
a[j] = x+1; int t2 = a[t1];
return a[i+2] a[j] = t2+1; Solution: S1 and S2 are correct statements.
– 3; return t2 – 3; Ans. (a)
} }
55. Consider this C code to swap two integers and
S1: The transformation from work 1 to work 2 is these five statements: the code
valid, that is, for any program state and input argu- void swap (int *px, int *py) {
ments, work 2 will compute the same output and *px = *px - *py;
have the same effect on program state as work 1. *py = *px + *py;
S2: All the transformations applied to work 1 to get *px = *py - *px;
work 2 will always improve the performance (i.e }
reduce CPU time) of work 2 compared to work 1.
S1: Will generate a compilation error
(a) S1 is false and S2 is false S2: May generate a segmentation fault at runtime
(b) S1 is false and S2 is true depending on the arguments passed
56. Which one of the following is a valid sequence of Solution: Maximum number of binary trees = 2n
elements in an array representing 3-ary max-heap? − n = 23 − 3 = 5
(a) 1, 3, 5, 6, 8, 9 (b) 9, 6, 3, 1, 8, 5 Ans. (b)
(c) 9, 3, 6, 8, 5, 1 (d) 9, 5, 6, 8, 3, 1 60. The height of a binary tree is the maximum number
(GATE 2006: 2 Marks) of edges in any root to leaf path. The maximum
number of nodes in a binary tree of height h is:
Solution: The 3-ary max heap can be formed by (GATE 2007: 1 Mark)
(a) 2h− 1 (b) 2h−1−1 (c) 2h+1− 1 (d) 2h+1.
9, 5, 6, 8, 3, 1.
9
Solution: Maximum number of node with height
h = 1 + 2 + 4 + ….. + 2h = 2h+1 − 1
56 8 Ans. (c)
3 1 61. The following postfix expression with single-digit
Ans. (d) operands is evaluated using a stack:
∧
823 /23*+51*−
57. Suppose the elements 7, 2, 10 and 4 are inserted, in
∧
that order, into the valid 3-ary max-heap found in Note that is the exponentiation operator. The
the above question Q.56. Which one of the follow- top two elements of the stack after the first * is
ing is the sequence of items in the array represent- evaluated are:
ing the resultant heap?
(a) 6, 1 (b) 5, 7
(a) 10, 7, 9, 8, 3, 1, 5, 2, 6, 4 (c) 3, 2 (d) 1, 5
(b) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 (GATE 2007: 2 Marks)
va
lue = value + GetValue 69. Which combination of the integer variables x, y
(ptr->leftChild) + GetValue and z makes the variable a get the value 4 in the
(ptr->rightChild); following expression?
}
return(value); a = (x > y) ? ((x > z) ? x :z):((y > z) ? y :z)
} (a) x = 3, y = 4, z = 2
The value returned by GetValue when a pointer (b) x = 6, y = 5, z = 3
to the root of a binary tree is passed as its argu- (c) x = 6, y = 3, z = 5
ment is: (d) x = 5, y = 4, z = 5
(GATE 2008: 1 Mark)
(a) The number of nodes in the tree
Solution: In option A, 3 > 4 is false so it moves
(b) The number of internal nodes in the tree
to else part. In else condition, 4 > 2 is true and 4
(c) The number of leaf nodes in the tree
(d) The height of the tree
will be printed.
(GATE 2007: 2 Marks) Ans. (a)
Solution: As we can see in else part of given 70. The breadth first search algorithm has been
program, left and right subtrees are traversed implemented using the queue data structure. One
recursively and value is incremented if they have possible order of visiting the nodes of the following
leaf nodes. graph is
Ans. (c)
Insertion of 7th key 78. The running time of f1(n) and f2(n) are
To maximize splits, let us insert a value in a node
(a) Θ(n) and Θ(n) (b) Θ(2n) and Θ(n)
that has key in access. Let us insert 15
(c) Θ(n) and Θ(2n) (d) Θ(2n) and Θ(2n)
8*30 (GATE 2008: 2 Marks)
79. f1(8) and f2(8) return the values 82. Consider the program below:
(a) 1661 and 1640 (b) 59 and 59 # include <stdio.h>
(c) 1640 and 1640 (d) 1640 and 1661 int fun(int n, int * f_p) {
int t, f;
(GATE 2008: 2 Marks)
if (n <= 1) {
Solution: Implementing the code will give the * f_p =1;
output 1640, 1640. return 1;
}
Ans. (c) t = fun (n - 1, f_p);
Common Data for Questions 80 and 81: Consider f = t+ * f_p;
the following C program that attempts to locate an * f_p = t;
return f;
element x in an array Y[ ] using binary search. The
}
program is erroneous.
int main() {
1. f(int Y[10], int x) { int x = 15;
2. int u, j, k; printf (" % d\ n", fun(5, & x));
3. i = 0; j = 9; return 0;
4. do { }
5. k = (i + j) / 2; The value printed is
6. if(Y[k] < x) i = k;
else j = k; (a) 6 (b) 8 (c) 14 (d) 15
7. } while ((Y[k]! = x) && (GATE 2009: 1 Mark)
(i < j));
8. if(Y [k] == x) print f ("x is in Solution:
the array");
Iteration n *f_p t f
9. else print f ("x is not in the
array"); 5 15 ® 3 5 8 ® Ans
10. }
4 15 ® 2 3 5
80. On which of the following contents of Y and x does 3 15 ® 1 2 3
the program fail? 2 15 ® 1 1 2
(a) Y is [1 2 3 4 5 6 7 8 9 10] and x < 10. 1 15
(b) Y is [1 3 5 7 9 11 13 15 17 19] and x < 1.
(c) Y is [2 2 2 2 2 2 2 2 2 2] and x > 2. The function will return 8.
(d) Y is [2 4 6 8 10 12 14 16 18 20] and 2 < x < 20 Ans. (b)
and x is even. 83. What is the maximum height of any AVL tree with
(GATE 2008: 2 Marks) 7 nodes? Assume that the height of a tree with a
Solution: Binary search fails for Y [2 2 2 2 2 2 2 single node is 0.
2 2 2] and x > 2 (a) 2 (b) 3 (c) 4 (d) 5
Ans. (b)
(GATE 2009: 2 Marks)
81. The correction needed in the program to make it
work properly is Solution: The height of an AVL tree storing n
items is O(log(n)).
(a) Change line 6 to: if (Y[k] < x) i = k + 1; else Ans. (b)
j = k − 1;
Linked Answer Questions 84 and 85: Consider a
(b) Change line 6 to: if (Y[k] < x) i = k − 1; else
binary max-heap implemented using an array.
j = k + 1;
(c) Change line 6 to: if (Y[k] <= x) i = k; else 84. Which one of the following array represents a
j = k; binary max-heap?
(d) Change line 7 to:} while ((Y[k] == x) && (i < j));
(a) {25,12,16,13,10,8,14}
(GATE 2008: 2 Marks) (b) {25,14,13, 16,10,8,12}
Solution: Change line 6 according to option A to (c) {25,14,16,13,10,8,12}
correct the program. (d) {25,14,12,13,10,8,16}
Ans. (c) (GATE 2009: 2 Marks)
/
/
{
8 10
if (n<= 0)return 0;
Ans. (d) el
se if(*a% 2= = 0)
86. In a binary tree with n nodes, every node has an return * a + f(a
odd number of descendants. Every node is consid- +1,n - 1);
ered to be its own descendant. What is the number el
se return * a -
of nodes in the tree that has exactly one child? f(a + 1, n - 1);
}
(a) 0 (b) 1 int main( )
(c) (n − 1)/2 (d) n − 1 {
(GATE 2010: 1 Mark) in
t a[ ] = {12, 7,
13, 4, 11, 6};
Solution: The given tree is called full binary printf("%d",
f(a,6));
tree which has 0 or 2 children. No node will have return 0;
exactly one child node. }
Ans. (a)
(a) −9 (b) 5 (c) 15 (d) 19
87. What does the following program print?
(GATE 2010: 2 Marks)
#include <stdio.h>
void f (int *p, int * g) { Solution:
p = q;
*p = 2; f(a,6) 12 + f(7,5)
}
int i = 0, j =1; f(7,5) 12 + 7 − f(13,4)
int main ( ){
f(13,4) 12 + 7 −(13 − f(4,3))
f(&i, & j);
print f ("%d%d / n", i, j ; f(4,3) 12 + 7 −(13 − ( 4 + f(11,2)))
return 0;
} f(11,2) 12 + 7 − (13 − (4 + 11 − f(6,1)))
(d) (c)
5
2 8
2
3
1 4 6 10
3 4
(GATE 2011: 1 Mark)
Ans. (b) 2
Solution:
Given expression is:
7
Precedence of ↑ is higher, so first the sub-expres-
sion (3↑ 4 ↑3) will be solved. In this 4 ↑ 3 will be
solved first because ↑ is right to left associative. So,
the expression will be solved as ((7 ↓(3↑(4 ↑3))).
3
↓ operator is left to right associative, so ((7 ↓(3↑(4
↑3))) will be solved first. Build the in order expres-
4 sion considering operator precedence.
((7 ↓(3↑(4 ↑3)))↓2
3 2 Ans. (b)
Common Data Questions 94 and 95: Consider the
following recursive C function that takes two
(b) arguments:
unsigned int foo (unsigned int n,
2 unsigned int r) {
if (n>0) return ((n% r) + foo (n/r, r) );
else return 0;
7 }
Solution: The above pseudocode is traversing tree 100. What output will be generated by the given code
to calculate the tree height. segment if:
Box 1: it should be replaced with the code that will
Line 1 is replaced by autoint a = 1;
traverse the right sub tree, so
Line 2 is replaced by registerint a = 2;
B1: (1 + height(n → right))
Box2: Now both left and right sub tree height is (a) (b)
calculated. 3 1 42
So the maximum out of both will be chosen.
4 1 61
B2: (1 + max(h1, h2)).
Ans. (a) 4 2 61
99. What output will be generated by the given code (a) 1/8 (b) 1 (c) 7 (d) 8
segment? (GATE 2013: 1 Mark)
(a) (b) Solution: P(e) = (1/2)
31 42 Number of ways vertices can be chosen of cycle
three = 8C3 × (1/2)3 = 7
41 61
Ans. (c)
42 61
102. Which of the following statements is/are TRUE
(c) (d) for undirected graphs?
42 31
P : Number of odd degree vertices is even.
62 52
Q: Sum of degrees of all vertices is even.
20 52 (GATE 2013: 1 Mark)
(GATE 2012: 2 Marks) (a) P only (b) Q only
(c) Both P and Q (d) Neither P nor Q
Solution: A is static variable, its value will be
preserved between different function calls. Solution: Both statements P and Q are correct.
First call to prtFun ( ): a = 2 and b = 1
a = 2 +2 = 4 Ans. (c)
Print 4 2 103. What is the return value of f(p, p), if the value of
Second call to prtFun ( ): a = 4 and b = 1 p is initialised to 5 before the call? Note that the
a=4+2=6 first parameter is passed by reference whereas the
Print 6 2 second parameter is passed by value.
Main printf function prints : 2 0 int f (int&x, int c) {
Ans. (c) c = c - 1;
PRACTICE EXERCISES
Set 1
(a) Will execute successfully (a) ascending order. (b) descending order.
(b) Incorrect syntax (c) random order. (d) none of these.
(c) May execute on some compiler
(d) Will result in execution error 22. Which of the following is not an application of
binary search trees?
12. Global variables in different files are checked
(a) Finding a particular alphabet in a given string
(a) at load time. (b) Sorting of characters in a string
(b) at assembly time. (c) Faster searching as compared to linear search
(c) at linking time. (d) Minimising the length of a string
(d) during execution time.
23. Which of the following is known as two-way list?
13. Indirect addressing uses:
(a) Grounded header list
(a) Arrays (b) Pointers (b) Circular header list
(c) Structures (d) Array with pointers (c) Linked list with header and trailer
14. typedef char *ch; (d) None of the above
const ch P; 24. Which of the following operators cannot be over-
In this code, what is P? loaded in C++?
(a) P is a constant. (a) + (b) ?
(b) P is a character constant. (c) = = (d) : :
(c) P is a character type.
(d) P is a pointer of character type. 25. The correct way to round off a floating number x
to an integer value is
15. Which of the following will have efficient space
complexity and lesser time complexities? (a) y = (int) (x + 0.5)
(b) y = int (x − 0.5)
(a) Incomplete binary tree
(c) y = int (x + 0.5)
(b) Complete binary tree
(d) y = (int) ((int)x + 0.5)
(c) B+ tree
(d) Left-inclined binary tree 26. Given two sorted list of size `m’ and `n’, respec-
16. Binary tree can be represented as tively. The number of comparison needed in the
worst case by the merge sort algorithm will be
(a) Linked list and graph. (b) Array and tree.
(c) Array and linked list. (d) Stack and queue. (a) m * log n (b) min (m, n)
(c) avg (m, n) (d) m + n − 1
17. The worst case height of AVL tree with n nodes is
27. Consider a forest of t-trees having n vertices. The
(a) 1.44 log(n) (b) 1.44 log(n + 1)
number of edges will be:
(c) 1.44 log(n + 2) (d) 1.44 nlogn
(a) nlog t (b) n − t
18. Which of the following sorting algorithm has almost (c) n * t (d) (n * t)/2
the same worst case and best case complexity?
28. Consider a binary search tree, traversal
(a) Quick sort (b) Merge sort
will result in nodes arranged in ascending order?
(c) Heap sort (d) Shell sort
(a) Inorder (b) Polish
19. Which of the following is max-heap property if A is
(c) Reverse polish (d) Depth first search
an array and i is the index of the array?
(a) A[Parent(i) ≥ A[i]]
29. The balance factor of height balance trees is:
(b) A[A[i]>Parent(i)]
(c) A[Parent(i) ≤ A[i]] (d) A[A[i]<Parent(i)] (a) −1, 0, 1 (b) 1, 0, 1
(c) −1, 2, −1 (d) 1, 2, 1
20. Complete binary tree can be implement by making
use of 30. The term `push’ and `pop’ is related to the
(a) array. (b) dequeue. (a) array. (b) linked list.
(c) priority queue. (d) stack. (c) queue. (d) stack.
21. If a binary search tree traversed in inorder then the 31. A digraph when represented in an adjacency
number of nodes will be printed in matrix, the matrix is a
2. FORTRAN implementation do not permit recur- (a) An array, each element of which is a pointer to
sion because a structure of type node.
(b) A structure of 2 fields, each field being a pointer
(a) They use static allocation for variables
to an array of 10 elements.
(b) They use dynamic allocation for variables
(c) A structure of 3 fields: an integer, a float and
(c) Stacks are not available on all machines
an array of 10 elements.
(d) It is not possible to implement recursion on all
(d) An array, each element of which is a structure
machines
of type node.
3. An unrestricted use of the `goto’ statement is 7. Aliasing in the context of programming language
harmful because refers to
(a) It makes it more difficult to verify programs. (a) multiple variables having the same memory
(b) It increases the running time of the programs. location.
(c) It increases the memory required for the (b) multiple variables having the same value.
programs. (c) multiple variables having the same identifier.
(d) It results in the compiler generating longer (d) multiple uses of the same variable.
machine code.
8. Consider the following three C functions:
4. What is the value of X printed by the following
[P1] int* g(void)
program? {
Program COMPUTE (input, output); int x = 10;
Var X: integer return (&x);
Procedure FIND (X: real) }
Begin X: sqrt(X); end [P2] int* px;
begin {
X:=2 int *px;
Find (X) *px= 10
Writeln(X) return px;
end }
[P3] int* g(void)
(a) 2 (b) 4
{
(c) Runtime error (d) None of the above
int *px;
px = (int*)malloc(size of (int));
5. Consider the following C function definition *px =10;
int Trial (int a, int b, int c) return px;
{ }
if ((a>=b)&& (c <b) return b;
el
se if (a >=b) Which of the above three functions is likely to
return Trial (a, c, b); cause problems with pointers?
else return Trial (b, a, c); (a) Only P3 (b) Only P1 and P3
} (c) Only P1 and P2 (d) P1, P2 and P3
The function trial: 9. The value of j at the end of the execution of the
(a) Finds the maximum of a, b and c. following C program
(b) Finds the minimum of a, b and c. int incr (int i)
(c) Finds the middle number of a, b and c. {
(d) None of these. staticint count = 0;
count = count + i
6. The following C declarations return (count);
}
struct node {
main (){
int i;
int i, j;
float j;
for (i=0; i<=4; i++)
};
j =incr(i)
struct node *s[10];
}
Define s to be is
21. In the balanced binary tree in the figure given of a complete n-ary tree, the number of leaves in it
below, how many nodes will become unbalanced is given by
when a node is inserted as a child of the node `g’?
(a) x(n − 1) + 1 (b) xn − 1
(c) xn +1 (d) x(n + 1)
a
27. Let LASTPOST, LASTIN and LASTPRE denote
the latest vertex visited in a postorder, inorder
b e and preorder traversal, respectively, of a complete
binary tree. Which of the following is always true?
c d (a) LASTIN = LASTPOST
f (b) LASTIN = LASTPRE
(c) LASTPRE = LASTPOST
g (d) None of these
31. Consider the following code segment. What is the final value of x in both call by value
void foo(int x, int y) and call by reference, respectively?
{ (a) 5 and 16 (b) 5 and 12
x+=y;
(c) 5 and 20 (d) 12 and 20
y+=x;
} 32. What is the maximum height of any AVL tree with
main() 7 nodes? Assume that the height of a tree with a
{ single node is 0.
int x=5.5;
foo(x,x);
}
Set 1
Set 2
1. (a) The given program is for swapping values of 6. (a) S is an array, each element of which is a pointer
two variables. to a structure of type node.
2. (a) In recursion, stack is used to store the latest 7. (a) Aliasing describes a situation in which a data
value of variables, means value of variables change location in memory can be accessed through differ-
with the recursive call. But FORTRAN uses ent symbolic names in the program.
static allocation for variables which does not allow 8. (c) In P1, there is no parameter passing and type
changes in every different function call. casting so it is wrong.
3. (a) A goto statement does not increase the running In P2, pointer is defined as pointer function which
time or memory requirement of the program. It is wrong.
also does not contribute to longer machine code. 9. (a) Count is declared as static variable in incr( ).
But the use of goto can result in unstructured So, statement static int count = 0 will assign count
code with multiple entry and exit points which can to 0 only in the first incr call. Remaining calls to
cause an issue for program verification. incr function will use old values of count.
4. (b) Global variable value not changed because of at first incr(0) call count will become 0
static scoping. after incr(1) call count will become 1
after incr(2) call count will become 3
5. (d) Just take a = 21, b = 8 and c = 14 and verify after incr(3) call count will become 6
the options.
after incr(4) call count will become 10
10. (c) Initial value of x and y will be 10, 3 and address fun (101)
are 1000, 2000, respectively. Then after first state- fun = 101−10 = 91
ment execution in the function, value at address
1000 will be {(10 as old value) + (4) = 14} because Return value of fun is 91. So, option (c) is correct.
y at the called function refers to address of x. After
16. (b) If a record is inserted in the circular-linked list
second statement execution in the function, value
at address 1000 will be {3 + 14 + 14 = 31} because
then two pointers have to be modified. Let a record
k be inserted between the node m and n, then
`x’ at called function refers to y in the calling func-
tion and `z’ at the called function refers to address (a) A
ddress field of node m contains address of
of x. So final values will be node x.
x(address = 1000) = 31 (b) Address field of node x contains address of
node n.
y(address = 2000) = 3
11. (a) To find location of an element in a two- 17. (b) With linked list binary search will take O(n)
dimensional array by row-major order is: time to sort the element list. Thus, binary search
performs worst with linked list.
A[i][j] = Base address + (i − 1)*r + (j − 1), where
r = no. of rows. 18. (d) On linked list we can perform only linear
Given base address = 100 and number of rows = 15 search. The number of comparisons required using
= 100 + (i − 1) × 15 + (j − 1) linear search is O(n).
= 100 + 15i − 15 + j − 1
= 100 + 15i + j − 16 19. (b) In a binary tree, two nodes are connected by a
= 84 + 5i + j single node to having degree 2. If a tree has n leaf
nodes, then the number of nodes with degree 2 will
11. (a) Let an array S[1 … 8] always be less than n. So option (b) is the strong
answer.
1 2 3 4 5 6 7 8
20. (b)
S = 7, k = 3 1
a
reverse (S, 1, 3) we get [3, 2, 1, 4, 5, 6, 7, 8]
reverse (S, 4, 8) we get [3, 2, 1, 8, 7, 6, 5, 4] 1
b e 1
reverse (S, 1, 8) we get [4, 5, 6, 7, 8, 1, 2, 3]
after performing above three reverse, we can see it d
1 c
is equivalent to the option (a). f
0
12. (b) Take a stack and perform push and pop opera- 0
0 g
tion to verify the given options.
21. (b) The binary search tree is as follows: In postorder traversal, root node is traversed in the
end. So we can remove option (a) and (c).
50 Let us take an example for option (b).
15 62
4
5 20 58 91
5 6
3 8
37 60
7 8 9
24
Inorder: 7 5 8 4 9 6
In the above binary tree, number of nodes in the
left sub-tree of root is 7 and in the right sub-tree Preorder: 4 5 7 8 6 9
of the root is 4. When a tree is a complete binary tree with full
at last level, then only last-visited node will
22. (b) Not possible always be same for inorder traversal and preorder
(b) 2 3 50 40 0 43 traversal.
23. (d) Inorder sequence: 53124768 Ans. (d)
3 Given n = 4i + 1
7
Total nodes = internal nodes (i) + leaf nodes (l)
n=i+l
i=n−l
1 4
6 8
n = 4(n − l) + 1
2 n = 4n − 4l + 1
4l = (2n + 1)
24. (b) A labelled rooted binary tree cannot be con- l = (2n + 1)/4
structed uniquely when inorder traversal is given
along with postorder or preorder traversal. 28. (c) According to program,
F(n) = n + 2F(n − 1) for n ≥ 2
25. (a) Total number of nodes in n-ary tree = ni + 1,
= 0 for n = 1
where i is internal nodes 1
F(4) = 4 + 2(3 + 2(2 + 2(0)))) = 18
Total nodes = internal nodes (i) + leaf nodes (l ) F(3) = 3 + 2(2 + 2(0)))) = 7
2 Ans. (c)
From 1 and 2
29. (c) 0, 1, 8, 9, 100, 101, 110 is an octal number
i + l = ni + 1
format.
l = (n − 1)I + 1
Replace I with x, because in question internal node 30. (b) B tree of order k, every internal node must
is given as x. have k/2 to k children and number of keys will be
So number of leaf nodes in n-ary tree with x inter- one less than the children.
nal nodes is (n − 1)x + 1.
31. (c) In call by value, there is no change in the value
26. (d) In the question, it is given that the tree is a com- of x because function foo( ) operates on copy of x.
plete binary tree. For a complete binary tree, the In call by reference, first value of x changes to 5 + 5
last visited node will always be the same for inorder and then it changes to 10 + 10 = 20.
traversal and preorder traversal because in both the
traversal right child is traversed in the last. 32. (3) Draw AVL tree to find the height.