0% found this document useful (0 votes)
99 views70 pages

ESP V-Programming & Data Structure

Programming and Data Structure notes for ESP V for 5th Semester of B Tech Computer Science Engineering.

Uploaded by

Ahana Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
99 views70 pages

ESP V-Programming & Data Structure

Programming and Data Structure notes for ESP V for 5th Semester of B Tech Computer Science Engineering.

Uploaded by

Ahana Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 70

CHAPTER 3

PROGRAMMING AND DATA STRUCTURES

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.

3.1  INTRODUCTION worked in an appropriate manner. Usually, efficient data


structures are a key in designing efficient algorithms. In
programming, efficient data structures are used to design
A computer is a machine that manipulates information. efficient programs, both in terms of time and memory.
Computer science is the study of how information is In the following text, the programming part is discussed
organised, manipulated and can be utilised. Data struc- followed by data structure.
ture is a way of organising data in computer’s memory
or disk so that it can be used efficiently. Examples of
several common data structures are arrays, linked lists, 3.2  BASIC TERMINOLOGY
queues, stacks, binary trees and hash tables. Different
kinds of data structures are suited to different kinds
This section defines the basic terms used in computer
of applications, and some are highly specialised to spe-
programming.
cific tasks. Different types of data structures are used
in different types of applications, which are specialised
to perform the specific task. Data structures provide a 3.2.1  Programming Languages
means to manage large amounts of data efficiently, such
as large databases and Internet indexing services. Data A computer performs the tasks commanded by the user.
structures are designed to manage a large amount of data The command is given through a sequence of lines of
to suit a specific purpose so that it can be accessed and code that are understood by the computer. The art of

Chapter 3.indd 105 4/9/2015 9:51:28 AM


106     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

Chapter 3.indd 106 4/9/2015 9:51:29 AM


3.2  BASIC TERMINOLOGY     107

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)

Chapter 3.indd 107 4/9/2015 9:51:29 AM


108     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

Table 3.1 |   Continued

Type Storage Size Value Range (Depends on Compiler Type)


short 2 bytes −32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes −2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 3.4E − 38 to 3.4E + 38
double 8 bytes 1.7E − 308 to 1.7E + 308
long double 10 bytes 3.4E − 4932 to 1.1E + 4932

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).

3.2.5  Control Flow Statements 3.2.5.1 Conditional Statements

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

unsigned long long

float

double

long double

Figure 3.2 |   Type conversion in C.

Chapter 3.indd 108 4/9/2015 9:51:29 AM


3.2  BASIC TERMINOLOGY     109

Control statements

Sequenital Branch Iterative or loop


statements statements statements

Conditional/ Unconditional
while
Decision control branch

if goto for

if-else break do-while

nested if continue

else-if return

switch

Figure 3.3 |   Control flow statements.

  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.

Chapter 3.indd 109 4/9/2015 9:51:30 AM


110     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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;

Chapter 3.indd 110 4/9/2015 9:51:30 AM


3.2  BASIC TERMINOLOGY     111

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);

Chapter 3.indd 111 4/9/2015 9:51:30 AM


112     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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.

Chapter 3.indd 112 4/9/2015 9:51:30 AM


3.2  BASIC TERMINOLOGY     113

It is simply a specification of the general recursive func- 3.2.8  Pointers


tion we have seen many times.
A pointer is a variable which stores the address of some
return_typefunction_name(Pass appropriate
other variables. The declaration of a pointer is done as
arguments)
{ follows:
if a simple case, return the simple value Data type *variable_name;
/* base case or stopping condition*/
else call function itself with simpler
version of problem Example 3.3
} int *p; /* pointer to an integer */
int b = 20;
Example 3.2 p = &b; /* address of variable b is stored
in p */
int sum(int n){
if(n==0) /* base case or stopping printf ("Address of variable b is: %d", &b);
condition */ printf ("Address of variable b is: %d, p);
return n; printf ("Value of variable b is: %d", *p);
else /* *p displays the value at stored address */
returnn+sum(n-1); /*self-call to function
sum() */
} The operating systems may stop to access memory and
cause the program to crash. To avoid such problem,
pointers should always be initialized before use. These
In this program, sum() function is called itself in else are initialized using free memory in the following way:
condition. If n is equal to 0 then the function returns the
value passing in the argument, but if n is not equal to   1.  Memory allocation to pointers:
0 then the function calls itself. Let n = 5 initially, then int *p = malloc (sizeof (*p));
next time 4 is passed to the function and the value of   2.  De-allocating memory of pointer:
the parameter is decreased by 1 until the condition is
free (p);
satisfied. At the end, when n becomes 0, the value of n
is returned, which is from 5 to 1.   3.  Pointer to pointer:
sum(5)
Address Address Value
= 5 + sum(4)
= 5 + 4 + sum(3)
int *p    /* pointer to an integer */
= 5 + 4 + 3 + sum(2) int **ptr  /* pointer to pointer */
= 5 + 4 + 3 + 2 + sum(1) int b = 20;
= 5 + 4 + 3 + 2 + 1 + sum(0) p = &val;  /* address of variable b is
stored in p */
=5+4+3+2+1+0 ptr = &p;  /* address of pointer is
=5+4+3+2+1 stored in ptr */
=5+4+3+3 To print value of b:
=5+4+6 *p = 20;
**ptr = 20;
= 5 + 10
= 15 Pointer Arithmetic
  1.  Incrementing a pointer: Incrementing a
Advantages of Recursion
pointer variable depends on data type of the
Recursion has the following advantages: pointer ­variable. It is generally used in array in
  1.  Unnecessary calling of functions is avoided. which ­elements are stored at contiguous memory
  2.  In recursion, the function calls anywhere in the locations. For example,
program so it if flexible in nature. ptr ++ = ptr + 1 = ++ ptr = ptr + 1 *
  3.  In some situations, the recursion is compulsory in size_of(data type);
a programming. For example, to find the factorial (address + 1= ++ address = address++
of a given number. gives an address value)

Chapter 3.indd 113 4/9/2015 9:51:31 AM


114     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

#include<stdio.h> Actual Result = (ptr2 - ptr1) / Size


int main(){ of Data Type
int *ptr=(int *)200; /*Assume integer
takes 4 bytes*/ Suppose the address of variable n is
ptr=ptr+1; 200 and integer takes 4 bytes.
printf("New Value of ptr : %u",ptr); #include<stdio.h>
return 0; int main()
} {
  int n, *ptr1, *ptr2;
Output   ptr1 = &n;
New Value of ptr: 204   ptr2 = ptr1 + 2;
  printf("Difference is: %d",ptr2 –
  2.  Decrementing a pointer: Decrementing a
ptr1);
pointer to a data variable will cause its value to be
  return 0;
decremented by size of variable because memory }
required to store a variable (integer) varies from
compiler to compiler.Example Output
ptr-- = ptr - 1 = --ptr = ptr - 1 * Difference is 2
size_of(data type); ptr1 = 200
(address - 1= --address = address-- ptr2 = 200 + 2 * 4 = 208
gives an address value) ptr2-ptr1 = (208-200)/4 = 2
Both pointers numerically differ by 8
  3.  Adding an integer value with pointer: In C
and technically by 2 objects
Programming, it is legal to add any integer number
to pointer variable.
ptr + n = (ptr) + (n * size of data type); 3.2.8.1 Dangling Pointer

#include<stdio.h> Dangling pointer arises when an object is deleted or de-


int main() allocated, without modifying the value of pointer, so that
{ the pointer still points to the memory location of the de-
int *ptr=(int *)100; allocated memory. In other words, a pointer pointing to
ptr=ptr+3; a non-existing memory location is known as a dangling
printf("New Value of ptr : %u",ptr); pointer. For example,
return 0;
} void main ()
{
Output
int *p;
New Value of ptr : 112 {
  4.  Subtracting an integer value from pointer: int i=10; //This is a Block.
In C programming, it is legal to subtract any inte-  p=
&i;//Variable i is local
so i’s lifetime is only
ger number from pointer variable.
within the block.
ptr - n = (ptr) - (n * size of data type) }
#include<stdio.h> pr
intf ("%d", *p); //p will point to
int main() de-allocated memory.
{ *p=*p+100;
int *ptr=(int *)100;   printf ("%d",*p);
ptr=ptr - 3; }
printf("New Value of ptr : %u",ptr);
return 0; This program is perfectly running and giving output as
} 100 200. Actually this should not have happened because
in this program p points to a location i which has been
Output deleted from the memory so p becomes a dangling
New Value of ptr : 88 pointer but still the program is running.
  5.  Subtracting two pointers: It means ­subtracting Sometimes, the dangling pointer constitutes an unde-
two pointers and it gives total number of two fined behaviour as may be the reason that memory has
objects between them. not been overwritten by anything else. For example,

Chapter 3.indd 114 4/9/2015 9:51:31 AM


3.2  BASIC TERMINOLOGY     115

int *demoFun()//returns the address of {


variable i int a = 10, b = 20;
{ printf("\na = %d b = %d", a, b);
int i=10; exchange(a, b);
return &i; printf("\na = %d b = %d", a, b);
} }
int main()
{ exchange(int x, int y)
int *p; {
p=demoFun(); /*function returning int t;
address is assigning to pointer t = x;
variable.*/ x = y;
printf("%d",*p); //10 y = t;
*p=*p+20; printf("\nx = %d y = %d", x, y);
printf("%d",*p); // Garbage Value }
}

Output Before calling the function exchange(), values of a and


- 10 b are 10 and 20, respectively. After calling exchange(), x
and y also receive 10 and 20, respectively. In exchange(),
Some Garbage Value
we are interchanging values of x and y. So, the new values
According to the program, variable i have been deleted of x and y are 20 and 10, respectively. After successful
after completion of demoFun() function but still the execution of the function exchange(), control transfers to
pointer is able to access the memory location of i because the main function, but in the main function, values of a
this memory is not overwritten by another variable. It and b remain unchanged, that is, 10 and 20, respectively.
must be the same reason that dangling pointer consti- So, the output of the above program is as follows:
tutes an undefined behaviour. But when we perform
another operation, complier gives some garbage value a=10 b=20
because base pointer p does not get any data to that x=20 y=10
particular location. a=10 b=20

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.

Chapter 3.indd 115 4/9/2015 9:51:31 AM


116     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

printf("\na = %d b = %d", a, b);


}
void exchange(int *x, int *y)
X Location name
{
int t;
20 Location value t = *x;
*x = *y;
*y = t;
1000 Address
}

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.

Problem 3.3: Find the output of the following


Example 3.5 programs
#include<stdio.h>
void main( ) (a)
{ #include<stdio.h>
int x = 20; void main()
printf("\nAddress of x = %u", &x); {
printf("\nValue of x = %d", x); int a=3, *b;
printf("\nValue of x = %d", *( &x )); b = &a;
} printf("%d\n", a**b*a+*b);
}
Output (b)
Address of x = 1000 #include<stdio.h>
Value of x = 20 int main()
Value of x = 20 {
int a=10, *b, *c;
/* Call by Reference Parameter passing b=
&a; /* Assume address of a is 100
technique */ and integer is 4 byte size */
#include<stdio.h> c=b;
void exchange(a,b); *b++=*c++;
void main( ) a++;
{ pr
intf("a=%d, b=%d, c=%d\n", a,
int a = 10, b = 20; b, c);
printf("\na = %d b = %d", a, b); return 0;
exchange(&a, &b); }

Chapter 3.indd 116 4/9/2015 9:51:32 AM


3.2  BASIC TERMINOLOGY     117

enum month {jan, feb, mar, apr, may, jun,


(c) jul, aug, sep, oct, nov, dec};
#include<stdio.h> enum month this_month;
int main()
{ this_month = apr;
char s[10] = "Point";
char *const p=s; 3.2.12  Scoping
*p=’J’;
printf("%s\n", s); The scope is a part of a program where the identifier
return 0; may have direct access, and beyond that scope, a vari-
}
able cannot be accessed. In programming, variables can
be declared in the following three ways:
Solution:
  1.  Inside the main function
The outputs of the programs are:   2.  Outside the main function
(a) 30   (b) a=11, b=104, c=104   (c) Point   3.  Function parameter definition

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.

Chapter 3.indd 117 4/9/2015 9:51:32 AM


118     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

Example 3.7   1.  Register


  2.  Auto
#include<stdio.h>   3.  Static
/* Global Variable Declaration*/   4.  Extern
int r;
int main(){ Storage, default value, scope and life of these four stor-
/* Local Variable Declaration*/ age classes are given in Table 3.3.
int num,sum=0;
printf("Enter a number: ");
scanf("%d",&num); Table 3.3 |   Storage, default value, scope and life of
while(num){ the storage classes
r=num%10; Class Auto Register Static Extern
num=num/10;
sum=sum+r; Storage Memory CPU Memory Memory
} registers
printf("Sum of digits of number: %d",sum); Default Garbage Garbage Zero Zero
return 0; value value
}
Scope Local to Local to Local Global
block block
Variables num, sum are local to the function main(), Life Until Until Persists Till the
and cannot be accessible outside the main function. block block between end of
But the variable r is declared outside the main as a different program
global variable, it can be accessed by any function in function
this program. calls
If local variable and global variable have the same
name, then preference will be given to the value of the
local variable inside the function. 3.2.13  Binding

It is an association of an attribute with a program


Example 3.8 ­component in a program. For example, the data type of
the value of a variable is an attribute, which is associ-
#include<stdio.h>
ated with the variable name. The binding time for an
/* Global Variable Declaration*/
attribute is the time at which the binding occurs.
int a=10;
int main(){ In C programming, the binding time for a vari-
/* Local Variable Declaration*/ able type is when the program is compiled, but the
int a=5,b=20,sum; value of the variable is not bound until the program
sum= a+b; executes.
printf("Sum of number: %d",sum);
return 0;
} 3.2.13.1 Early Binding

In early binding, the linker copies the referenced module


into the executable image of the program at compila-
In the above example, variable `a’ is declared as global tion/link time. The referenced module is a part of the
and local both. And variable `b’ is declared as local to executable image.
the main function. When the sum of `a’ and `b’ are cal-
culated by a compiler then priority is given to that `a’   1.  Advantages of early binding:
which is declared as local. So the program will print 25 •• It is simple and the best performer.
as the sum of the variables. •• It is at least twice as fast as late binding.
•• The executable is stand alone.
3.2.12.3 Storage Classes
  2.  Disadvantages of early binding:
A storage class defines the scope and visibility of vari- •• The executable image is large.
ables and functions in C program. The following four •• If the referenced module changes then each
types of storage classes are available: ­executable must be re-linked.

Chapter 3.indd 118 4/9/2015 9:51:32 AM


3.3  STACK     119

•• 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.

3.2.14  Abstract Data Types


3.3.1.1 Code for PUSH Operation
An abstract data type is an object with a specification
of the components. It is independent of implementation void push(int token)
details. {
Examples: char a;
if(top==MAX-1)
  1.  Stack: Operations such as push an item onto
{
printf("Stack full"); ® 
the stack, pop an item from the stack, ask if the
is Full Condition
stack is empty; implementation may be as array or check
return;
linked list. }
  2.  Queue: Operations such as add to the end of the do
queue, delete from the beginning of the queue, ask {
if the queue is empty; implementation may be as
printf("\nEnter the token to be inserted:");
array or linked list or heap.
scanf("%d",&token);
  3.  Search structure: Operations such as insert an top=top+1;
item, ask if an item is in the structure and delete stack[top]=token;
an item; implementation may be as array, linked printf("do you want to continue insertion
list or tree. Y/N");
a=getch();
}
3.3  STACK while(a==’y’);
}
A stack is an ordered collection of items in which the
item is added and removed in order. In stack, the
­element is added on the top of the stack. Only one ele-
3.3.2  POP Operation on Stack
ment, which is placed on the top, is removed from the
Whenever we try to remove an element from the stack
top of the stack. The stack is called last-in first-out
then the operation is called POP operation on stack
(LIFO) ­structure. Stack can be implemented by linked
(Fig. 3.8).
list and array.

Chapter 3.indd 119 4/9/2015 9:51:33 AM


120     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

EMPTY
STACK

TOP 15
12 TOP 12
10 10 10 TOP
5 5 5 5 TOP

STACK INITIALLY POP POP POP POP


Figure 3.8 |   POP operation on stack.

3.3.2.1 Code for POP Operation how we are accustomed to writing expressions


in standard mathematical notation.
The following is the code of POP function in which we •• Postfix: In postfix notation, the operator imme-
use the return statement to send the result back to the diately follows its operands.
calling function •• Prefix: In prefix notation, operands immediately
follow operator.
int pop()
{
int t; Infix to Postfix Conversion
if(top==-1)
Algorithm for infix to postfix conversion:
{
printf("Stack empty"); ® 
Is Empty Condition   1.  You create a stack and an output string.
return -1; check   2.  Then you read the infix string one token at a time,
} each token is either an identifier or an operator:
t=stack[top];
•• If the token is an identifier (e.g. a variable or a
top=top-1;
constant), then you append it onto the end of
return t; the output string.
} •• If the token is an operator, then you compare its
precedence with the precedence of the operator
3.3.3  Application of Stack on the top of the stack.

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.

Chapter 3.indd 120 4/9/2015 9:51:33 AM


3.3  STACK     121

Problem 3.4: Convert the given expression into postfix.


Expression = (A + B) * (C − D)

Solution:

Expression Stack Output Comment

(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

* (C − D) AB+ Pop until ( and print


(C − D) * AB+ Push
C − D) *( AB+ Push
− D) *( AB + C Print
D) *(− AB + C Push
) *(− AB + CD Print
End * AB + CD− Pop until (
End Empty AB + CD− Pop every element

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 `(’.

Problem 3.5: Convert the given expression into prefix:


Expression = (A + B ∧ C) * D + E ∧ 5

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.

Expression Stack Output Comment


∧ ∧
5 E + D * (C   B + A) Empty − Initial
∧ ∧
E + D * (C   B + A) Empty 5 Print
∧ ∧
E + D * (C   B + A) 5 Push
∧ ∧
+D * (C   B + A) 5E Push
(Continued)

Chapter 3.indd 121 4/9/2015 9:51:33 AM


122     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

Step 4: Reverse the expression.


+*+A ∧BCD ∧E5

3.4  QUEUE printf("\n Queue Overflow ");


}
elseif(front==-1&&rear==-1)
Queue is a special abstract data type storage structure. {
The access to elements in a queue is restricted, unlike front=rear=0;
queue[rear]=x;
arrays. Enqueue and dequeue are two main operations
used for the insertion of element in a queue and removal
}
of an element from a queue, respectively. An item can else
be inserted at the end known as rear of the queue and {
removed from the end known as front of the queue. It is rear++;
also called a first-in first-out (FIFO) list. queue[rear]=x;
It has the following five properties: }
}
  1.  Capacity: It stands for the maximum number of
elements a queue can hold.   2.  Dequeue: Removes the front element from q and
  2.  Size: It stands for the current size of the queue. returns its value. It can be declared as follows:
  3.  Elements: It is the array of elements.
voidDequeue(queue)
  4.  Front: It is the index of the first element (the {
index at which the element has been removed). intx;
  5.  Rear: It is the index of the last element (the index if(front==-1)
at which the element has been inserted). {
printf("\n Underflow");
3.4.1  Basic Operations on Queue }
x=queue[front];
Queue has the following basic operations: if(front==rear)
{
  1.  Enqueue: Inserts item x at the rear of the queue q.
front=rear=-1;
Queue can be declared as follows:
}
voidEnqueue(queue, x) else
{ {
if(front==0&& rear==MAX-1) if(front==MAX-1)
{ front=0;

Chapter 3.indd 122 4/9/2015 9:51:33 AM


3.5  LINKED LIST     123

else 3.4.3  Applications of Queues


front++;
pr
intf("\n The deleted element Queues have many applications in computer systems:
is: %d", x);
}   1.  Jobs in a single-processor computer
  2.  Print spooling
}   3.  Information packets in computer networks

3.4.2  Types of Queue 3.5  LINKED LIST


Queue is of the following types:
  1.  Simple queue or linear queue: In this data Linked list is a dynamic data structure whose length
structure, operations, such as, insertion and dele- can be increased or decreased at runtime. Linked list
tion occurs at the rear and front of the list, respec- basically consists of memory blocks that are located at
tively (Fig. 3.9). random memory locations. Node of a linked list consists
of two parts, one is value or data and the other is pointer
Deletion Insertion to the next node.

3.5.1  Basic Operations


Front Rear Basic operations of a singly-linked list are as follows:
Figure 3.9 |   Simple queue.   1.  Create: Creates an empty node of linked list.
  2.  Insert: Inserts a new element at the end of the list.
  2.  Circular queue: A circular queue is a queue
  3.  Delete: Deletes any node from the list.
where all nodes are treated as circular (Fig. 3.10).
  4.  Find: Finds any node in the list.
The first node follows the last node.
  5.  Print: Prints the list.
Functions of these operations are listed as follows:
  1.  Insert: It takes the start node and data to be
Front Rear
inserted as arguments. The new node is inserted
Figure 3.10 |   Circular queue. at the end of the linked list, till it reaches the last
node. Allocate the memory for the new node and
  3.  Priority queue: It contains items which have put data in it. Store the address in the next field of
some preset priority (Fig. 3.11). When an element the new node as NULL.
has to be removed from a priority queue; the item   2.  Delete: It takes the start node (as pointer) and
with the highest priority is removed first. data to be deleted as arguments. Reach the node
for which the node next to it has to be deleted.
Assumption
•• If that node points to NULL (i.e. pointer →
30,40 highest priority
Priority next = NULL) then the element to be deleted is
11, 22,33,next priority
30 40 NULL 88,99,least priority not present in the list.
•• Else, the pointer points to a node, whose next
0
1 11 22 33 NULL node has to be removed, declare a temporary
node (temp), which points to the deleted node.
2 88 99 NULL Store the address of the node next to the tem-

Figure 3.11 |   Priority queue.


porary node in the next field of the node pointer
(pointer → next = temp → next).
Break the link of the node which is next to the
  4.  Dequeue (double-ended queue): In this,
pointer (which is also temp). Function free() will
insertion and deletion occur at both the ends, that
deallocate the memory.
is, front and rear of the queue (Fig. 3.12).
  3.  Find: It takes the start node (as pointer) and data
Deletion value of the node (key) to be found as arguments.
Insertion
The first node is dummy node, so start with the
Rear Insertion second node. Iterate through the entire linked list
Deletion Front
and search for the key. Until next field of the pointer
Figure 3.12 |   Double-ended queue. is equal to NULL, check if pointer → data = key.

Chapter 3.indd 123 4/9/2015 9:51:34 AM


124     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

•• If the condition holds, then the key is found. Start=temp->next;


•• Else, move to the next node and search (pointer = free(temp);
pointer → next). return 1;
•• If key is not found return 0, else return 1. }
else
  4.  Display: Function takes the start node (as pointer) {
as an argument. If pointer = NULL, then there is prev->next=temp->next;
no element in the list. Else, print the data value of free(temp);
the node (pointer → data) and move to the next return 1;
node by recursively calling the print function with }
pointer → next sent as an argument. }
else
3.5.2  Linked List Implementation {
prev=temp;
Linked list is implemented as follows: temp=temp->next;
}
  1.  Node Structure of Linked List:
}
structnode return 0;
{ }
int data;
structnode *next;   4.  Find a Node in Linked List:
}*Start; int find (Struct node *Start,x)
  2.  Insert Node in Linked List: {
struct node *temp;
void insert(Start,x) temp=start;
{ if(temp==NULL)
structnode *temp,*New_Node; {
Ne
w_Node=(structnode *) printf("List is empty");
malloc(sizeof (structnode)); exit();
New_Node->data=num; }
New_Node->next=NULL;
else
temp=Start; {
if(temp==NULL) while(temp->data!=x && temp->
{ next!=NULL)
Start=New_Node; {
exit(1) temp=temp->next;
} }
else if(temp->data==x)
{ {
while(temp->next!=NULL) printf(" Node is found at address
{ %u",temp);
temp=temp->next; return 1;
} }
Start=New_Node; else
} {
} printf(" Node is not found ");
return 0;
  3.  Delete Node in Linked List: }
int delete(int num) }}
{
  5.  Display Linked List:
structnode *temp, *prev;
temp=Start; void display(start)
while(temp!=NULL) {
{ r=start;
if(temp->data==num) if(r==NULL)
{ {
if(temp==Start) return;
{ }

Chapter 3.indd 124 4/9/2015 9:51:34 AM


3.6  TREES     125

while(r!=NULL)   6.  Children: It is a set of nodes (S ), which have


{ incoming edges from the same node. In Fig. 3.13, 2
printf("\n%d ",r->data); and 6 are the children of node 7.
r=r->next;   7.  Parent: It is the parent of all the nodes that are
} connected to the outgoing edges. In Fig. 3.13, node
printf("\n"); 5 is parent of node 9.
}   8.  Sibling: The nodes in the tree having the same
parent are said to be siblings. The nodes 2 and 6
3.6  TREES are siblings in the tree shown in Fig. 3.13.
  9.  Subtree: It is a set of nodes and edges ­comprised
of a parent and all the descendants of that parent.
A tree is a collection of nodes and edges. When we con- 10. Leaf node: It is a node that has no children. For
nect each node with the help of edges then it constructs example, node 5 and node 11 are the leaf node in
a tree. The following has the properties of a tree: Fig. 3.13.
  1.  Starting node is called the root node. 11. Level: The level of a node (n) is the number of
  2.  Except the root node every other node(n) in a tree is edges on the path from the root node to (n). For
surely connected by an edge from another node(y), example, the level of node 4 in Fig. 3.13 is three.
the other node(y) is called the parent node of n. 12. Height: It is equal to the maximum level of any
There is unique path from start node to end node. node in the tree. The height of the tree in Fig. 3.13
is three.
3.6.1  Binary Tree

A binary tree is a tree data structure. In a binary tree,


3.6.2  Types of Binary Trees
any node in the tree can have at most two children.
Binary trees are of the following types:
Binary tree are used to construct binary search trees
and binary heap. An example of a binary tree is shown   1.  Strictly binary tree: Figure 3.14 shows the
in Fig. 3.13. Strictly binary tree. It has the following properties:
•• If in a tree, non-leaf nodes have exactly two
2 ­children then that tree is called strictly binary
tree.
7 5 •• In strictly binary tree, every leaf nodes have
degree 0 and every non-leaf nodes have degree 2.
•• A strictly binary tree with n leaf nodes has (2n − 1)
2 6 9 total number of nodes. Thus, strictly binary tree
always have odd number of nodes.
5 11 4

Figure 3.13 |   Binary tree.


A Root

  1.  Vocabulary and definitions: We will formally


define a tree and its components. C
B
  2.  Node: A node is an important part of a tree. It
can have a name, which we call the `key’. It may
also have additional information.
  3.  Edge: An edge is another important part of a D E F G
tree. It connects two nodes to show a relation-
ship between them. Every node (except the root)
is connected with exactly one incoming edge from H I
another node. Each node may have several outgo-
ing edges. Figure 3.14 |   Strictly binary tree.
  4.  Root: The root of the tree does not have incoming
edges.
  5.  Path: A path is an ordered list of nodes, which are   2.  Complete binary tree: Figure 3.15 shows
connected by edges. For example, 2 → 7 → 6 → the strictly binary tree. It has the following
11 is a path. properties:

Chapter 3.indd 125 4/9/2015 9:51:35 AM


126     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

•• A complete binary tree of depth d is strictly a


binary tree having all the leaves at level d. F
•• The total number of nodes in a complete binary
tree of depth d equals (2d + 1 − 1). B G

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.

Figure 3.15 |   Complete binary tree. 3.6.4  Tree Applications

The following are common uses of a tree:


  3.  Almost complete binary tree: A binary tree   1.  Manipulate hierarchical data
of depth d is an almost complete binary tree (see   2.  Make information easy to search
Fig. 3.16) if:   3.  Manipulate sorted lists of data
•• Each leaf in the tree is at either level d or level   4.  As a workflow for compositing digital images for
d − 1. visual effects
•• For any node nd in the tree with a right descen-   5.  Router algorithms
dant at level d, all the left descendants of nd
that are leaves are also at level d. 3.6.5  Binary Search Tree
•• An almost complete binary tree with N leaves
that is not strictly binary has 2N nodes. Binary search tree is a node-based binary tree data
structure with the following properties:
  1.  The left subtree contains the nodes with keys less
A than the node’s key.
  2.  The right subtree contains the nodes with keys
greater than the node’s key.
C X   3.  Both the right and left subtree should also be
binary search tree.
  4.  There should not be any duplicate nodes.
E M S O
3.6.5.1 Tree Traversal in Binary Search
Tree
K W N
There are three types of traversal techniques for tree:
Figure 3.16 |   Almost complete binary tree.   1.  Preorder:
•• Traverse the root
•• Traverse all the left external nodes starting with
3.6.3  Array Representation of Binary Trees the left-most subtree
•• Traverse the right subtree starting at the left
An array can be used to store a binary tree using the external node
following mathematical relationships.   2.  Postorder
•• Traverse all the left external nodes starting with
If root data is stored at index n, then left child is
the left-most subtree
•• Traverse the right subtree starting at the left
stored at index 2*n and right child is stored at index
2*n + 1.
external node
Figure 3.17 demonstrates the storage representation. •• Traverse the root

Chapter 3.indd 126 4/9/2015 9:51:36 AM


3.6  TREES     127

  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

There are two types of traversal techniques for graph:


3.6.6  Graphs   1.  Breadth first traversal: It is a level-by-level
traversal of an ordered tree. It starts with vertex
A graph G = (V, E) is composed of V (set of vertices) I, then it traverses to neighbours of vertex i, then
and E (set of edges), where edges connect the vertices. neighbours of neighbours of vertex i and so on. It
For example, see Fig. 3.18. uses a queue.

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.

Chapter 3.indd 127 4/9/2015 9:51:37 AM


128     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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)

Chapter 3.indd 128 4/9/2015 9:51:38 AM


3.6  TREES     129

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.

Chapter 3.indd 129 4/9/2015 9:51:40 AM


130     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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)

Chapter 3.indd 130 4/9/2015 9:51:41 AM


3.6  TREES     131

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)

Chapter 3.indd 131 4/9/2015 9:51:43 AM


132     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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)

2 To find the shortest path, an approach known as Greedy


method is used. The method is as follows:
b
1 Choose the vertex with smallest weight and mark the
3 path from source to the chosen vertex. Next, mark the
a
c 8 same for other vertices.
9 6 4 h
i e d Example 3.11

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)

Chapter 3.indd 132 4/9/2015 9:51:44 AM


3.6  TREES     133

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

a S = {a,e,c,b,d} U = {a}, V − U = {b, c, d, e, f, g}

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 ∞

Chapter 3.indd 133 4/9/2015 9:51:46 AM


134     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

Select vertex b to include in U. b 10 e

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

U = {a, b, d}, V − U = {c, e, f, g}


Select vertex g to include in U.
b 10 e
Closest
U V−U Low Cost 4 7 6
8 d
c D 2
a 5 g
e D 7 9 9
2
f D 9 8 2
g A ∞ c 1 f
Select vertex c to include in U. (vi)

Chapter 3.indd 134 4/9/2015 9:51:47 AM


3.6  TREES     135

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

4 8 7 6 Figure 3.22 |   AVL tree.


d
a g AVL has the following properties:
9 5
2 9   1.  Balance Factor of a Node: It is the difference
8 2 in heights of its two subtrees (hR − hL).
  2.  Balanced Node: Node with  BF ≤ 1; if  BF > 1,
c 1 f the node is unbalanced.
(vii)   3.  Balance Factor of Binary Trees: It corre-
sponds to the balance factor of its root node.
•• Tree is `left-heavy’ if BF ≤ −1
Step 7
•• Tree is `equal-height’ if BF = 0
U = {a, b, c, d, e, f, g}, V − U = {} •• Tree is `right-heavy’ if BF ≥ +1
  4.  Balance Factor of AVL Trees: BF of each
MST Complete
node in an AVL tree can only ∈ {−1, 0, 1}.

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

XL, X, XR, Y, ZL, Z, ZR XL, X, XR, Y, ZL, Z, ZR


Figure 3.23 |   Single-Left rotation.

Chapter 3.indd 135 4/9/2015 9:51:48 AM


136     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

•• Single-Right rotation: Refer Fig. 3.24.

Original tree XL Y

Y
Single-Right XR Z
X Z rotation

XL XR ZL ZR
ZL ZR

XL, X, XR, Y, ZL, Z, ZR XL, X, XR, Y, ZL, Z, ZR


Figure 3.24 |   Single-Right rotation.

•• Double left-right rotation: Refer Fig. 3.25.

Original tree After Single-Left rotation Double Left-Right rotation


Y Y
Z
X YR Z YR X Y

XL X ZR XL ZL ZR YR
Z

ZL ZR XL ZL

XL, X, ZL, Z, ZR, Y, YR XL, X, ZL, Z, ZR, Y, YR XL, X, ZL, Z, ZR, Y, YR


Figure 3.25 |   Double left-right rotation.

•• Double right-left rotation: Refer Fig. 3.26.

Original tree After Single-Right rotation Double Right-Left rotation


Y
Y
Z
YL X YL Z
Y X
Z XR ZL X
YL ZL ZR YR
ZR XR
ZL ZR

YL, Y, ZL, Z, ZR, X, XR YL, Y, ZL, Z, ZR, X, XR YL, Y, ZL, Z, ZR, X, XR

Figure 3.26 |   Double right-left rotation.

Chapter 3.indd 136 4/9/2015 9:51:49 AM


IMPORTANT FORMULAS     137

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

Figure 3.27 |   Binary heap.

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

 rear − front + 1, if rear = front 15. Two-dimensional arrays



rear − front + n, otherwise In two dimensions, an array `A’ is declared as:

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).

Chapter 3.indd 137 4/9/2015 9:51:50 AM


138     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

SOLVED EXAMPLES

1. Variables of function call are allocated in (a) 70 (b) 50


(c) 46 (d) 69
(a) registers and stack. (b) cache and heap.
(c) stack and heap. (d) registers and heap. Solution:  m=2*f(3,g(4,5));
The function g(4,5) will return 20 by performing
Solution:  The variables of function call can be
multiplication operations. Then function f (3,20)
stored in stack and heap.
will return 23 by performing addition operation.
Ans. (c)
In the last output of function f (3,20) is multiplied
2. Predict the output of: with 2. So, the final answer will be 46.
Ans. (c)
void main()
{ 5. A program to find the factorial of a given number
float x=1.1; is written (a) using recursion and (b) without using
double y= 1.1; recursion. Which of these will result in stack over-
if(x==y)
flow for a given number?
printf("I see You");
else (a) Only first program with recursion
printf("I hate You"); (b) Both may result for the same number
} (c) Only second program
(a) I see You (d) None of these
(b) I hate You
Solution:  When the factorial program is written
(c) Cannot compare double and float
using recursion only then will it use stack, so stack
(d) Run time error
overflow will occur in recursive program only.
Solution:  The stored value may or may not be Ans. (a)
exact, the precision of the value depends upon
6. If two strings are identical then strcmp() returns:
the number of bytes. Double stores value 1.1 with
more precision than float because double takes (a) True (b) 1
8 bytes, whereas float takes 4 bytes. (c) −1 (d) 0
Ans. (b)
Solution:  strcmp() is a pre-defined function
3. Global variable conflicts due to multiple file occur- of C library which returns value by calculating
rence is resolved during value=(second string length — first string length).
Hence, if both the strings are identical then it will
(a) load time.
return 0.
(b) execution time.
Ans. (d)
(c) link time.
(d) parsing phase of compiler. 7. In tree construction, which one will be suitable and
efficient data structure?
Solution:  A global variable provides access from
multiple files. Due to merging of one file code to (a) Queue (b) Linked list
another code, conflict occurs in the variable names (c) Heap (d) String
and this cause an error at link time.
Ans. (c) Solution:  Linked list is the best suitable and effi-
cient data structure for constructing a tree because
4. #define f(a,b) a+b an item can be inserted and deleted from linked list
#define g(a,b)a*b with less cost.
main() Ans. (b)
{
8. Which of the following is not true about spanning
int m;
m=2*f(3,g(4,5)); tree?
printf("\n m is %d", m); (a) It is a tree derived from a graph.
} (b) All the nodes of a network appear on the tree
What is the value of m? only once.

Chapter 3.indd 138 4/9/2015 9:51:50 AM


SOLVED EXAMPLES     139

(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.

Node 1 Node 2 Node 3


Prv data Nxt Prv data Nxt Prv data Nxt

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

So, only 2 stacks are required. So, option (b) is correct.


Ans. (b)

Chapter 3.indd 139 4/9/2015 9:51:51 AM


140     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

13. Postfix expression for the infix expression


(A*B − (C*D))/(F/D + E)
(a) AB*CD* − FD/E+/ (b) AB*CD − *FDE//+
(c) AB*CD − FD*E//+ (d) AB*CD − *FDE/+/

Solution:

Infix Expression Postfix Expression Stack

(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

Chapter 3.indd 140 4/9/2015 9:51:51 AM


SOLVED EXAMPLES     141

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)

Chapter 3.indd 141 4/9/2015 9:51:52 AM


142     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

GATE PREVIOUS YEARS’ QUESTIONS

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)

from above iterations: s = 1 + x + x2/2 + x3/ 6 + ….. 4. Suppose the numbers 7, 5, 1, 8, 3, 6, 0, 9, 4, 2


s = 1 + x + x2/2! + x3/ 3! + x4/ 4! + …. = ex
are inserted in that order into an initially empty
binary search tree. The binary search tree uses
Ans. (b) the usual ordering on natural numbers. What is
the inorder traversal sequence of the resultant
2. Assume the following C variable declaration tree?
int * A[10], B[10][10];
(a) 7 5 1 0 3 2 4 6 8 9 (b) 0 2 4 3 1 6 5 9 8 7
Of the following expressions (c) 0 1 2 3 4 5 6 7 8 9 (d) 9 8 6 4 2 3 0 1 5 7
I. A[2] II. A[2][3] (GATE 2003: 1 Mark)
III. B[1] IV. B[2][3]
Solution:  In-order traversal of a binary search
which will not give compile-time errors if used as
tree arrange elements in increasing order.
left-hand sides of assignment statements in a C
Ans. (c)
program?
(a) I, II and IV only (b) II, III and IV only 5. A data structure is required for storing a set of inte-
(c) II and IV only (d) IV only gers such that each of the following ­operations can
be done in O(log n) time, where n is the number of
(GATE 2003: 1 Mark) elements in the set.

Chapter 3.indd 142 4/9/2015 9:51:52 AM


GATE PREVIOUS YEARS’ QUESTIONS     143

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)

6. Let S be a stack of size n ≥ 1. Starting with the


L P U
empty stack, suppose we push the first n natu-
ral numbers in sequence, and then perform n pop
operations. Assume that Push and Pop operations VXZ
BHI N QT
take X seconds each, and Y seconds elapse between
the end of one such stack operation and the start of
the next operation. For m = 1, define the stack-life
of m as the time elapsed from the end of Push(m) What is the result of inserting G in the above tree?

(a) P (b) P

GL U HL U

B HI N QT VXZ BG I N QT VXZ

(a) (b)

(c) (d) None of the above


I P U

BGH L N Q T VXZ

(c) (GATE 2003: 2 Marks)

Chapter 3.indd 143 4/9/2015 9:51:53 AM


144     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

This node will split due to 4 elements


Result will be

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)

Chapter 3.indd 144 4/9/2015 9:51:54 AM


GATE PREVIOUS YEARS’ QUESTIONS     145

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

Ans. (a) (a) 1 2 1   (b) 2 1 1   (c) 2 1 2   (d) 2 2 2


(GATE 2003: 2 Marks)
12. Consider the function f defined below:
Solution:
struct item {
int data; Px = newQ();
struct item * next; Qy = newQ();
}; Pz = newQ();
int f(struct item *p) {
x : f(1); print 2 * i = 2
re
turn ((p == NULL) || (p ->next ==
NULL) || ((P)y) : f(1);
((
p->data <= p -> next -> data) && z : f(1) print 2 * i = 2
f(p-> next)));
} It will print 2 because typecast to parent class
cannot prevent overriding. So, function f(1) of class
For a given linked list p, the function f returns 1 if Q will be called not f(1) of class P.
and only if Ans. (d)

Chapter 3.indd 145 4/9/2015 9:51:54 AM


146     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

Chapter 3.indd 146 4/9/2015 9:51:54 AM


GATE PREVIOUS YEARS’ QUESTIONS     147

4322 mod 10 = 2 23. Consider the following program fragment for


1334 mod 10 = 4 reversing the digits in a given integer to obtain a
1471 mod 10 = 1 new integer. Let n = d1 d2 … dm.
9679 mod 10 = 9
int n, rev;
1989 mod 10 = 9 rev = 0;
6171 mod 10 = 1 while (n > 0) {
6173 mod 10 = 3 rev = rev * 10 + n % 10;
4199 mod 10 = 9 n = n / 10 ;
From the list, it is clearly seen that 9679, 1989 and }
4199 have same hash values 9. But, 1471 and 6171
The loop invariant condition at the end of the i
have hash value of 1. So, options I and II are correct.
iteration is:
Ans. (c)
20. The best data structure to check whether an arith- (a) n = d1d2…dm−1 and rev = dmdm−1…dm−1+1
metic expression has balanced parentheses is a (b) n = dm+1…dm−1dm or rev = dm−1…d2d1
(c) n ≠ rev
(d) n = d1d2…1dm or rev = dm…d2d1
(a) queue. (b) stack.
(c) tree. (d) list.
(GATE 2004: 1 Mark) (GATE 2004: 2 Marks)

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)

Chapter 3.indd 147 4/9/2015 9:51:55 AM


148     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(a) Rear node The postfix expression corresponding to the infix


(b) Front node expression a + b × c − d ∧ e ∧ f is
(a) abc × + def ∧ ∧− (b) abc × + de ∧ f ∧−
(c) Not possible with a single pointer
(c) ab + c × d − e f (d) − + a × bc ∧ ∧ def
∧ ∧
(d) Node next to front
(GATE 2004: 2 Marks)
(GATE 2004: 2 Marks)
Solution:  Required condition is not possible with
Solution:
single pointer.
∧ ∧
Ans. (c) a + b × c−d e f
∧ ∧
26. The elements 32, 15, 20, 30, 12, 25, 16 are inserted a+b×c−d ef
∧ ∧
one by one in the given order into a maxHeap. The a+b×c−def
∧ ∧
resultant maxHeap is a+bc×−def
∧ ∧
abc×+−def
32 32 ∧ ∧
abc×+def −
Ans. (a)
30 25 25 30 28. Consider the following C program:
main ( )
{ int x, y, m, n;
15 12 20 16 12 15 20 16 scanf ("%d %d", &x, &y);
/ *Assume x > 0 and y > 0 */
(a) (b) m = x; n = y;
while (m! = n)
{ if (m > n)
32 32
m = m - n;
else
n = n - m;
30 25 25 30 }
printf("%d",n);
}

15 12 16 20 12 15 16 20 The program computes

(c) (d) (a) x + y using repeated subtraction.


(b) x mod y using repeated subtraction.
(GATE 2004: 2 Marks) (c) The greatest common divisor of x and y.
(d) The least common multiple of x and y.
Solution:  Root is greater than both left and right
(GATE 2004: 2 Marks)
children.
Solution:  The given program finds greatest
common divisor of x and y.
32 Ans. (c)
29. What does the following algorithm approximate?
(Assume m > 1, ε > 0)
30 25
x = m;
y = 1;
while (x - y > ε)
15 12 16 { x = (x + y)/2;
20
y = m/x;
}
Ans. (a) print(x);
27. Assume that the operators +, −, × are left asso- (a) log m (b) m2
ciative and ∧ is right associative. The order of pre- (c) m1/2 (d) m1/3
cedence (from highest to lowest) is ∧, × , +, −. (GATE 2004: 2 Marks)

Chapter 3.indd 148 4/9/2015 9:51:55 AM


GATE PREVIOUS YEARS’ QUESTIONS     149

Solution:  The given program finds the square


Group 1 Group 2
root of program.
Ans. (c) III. Object-oriented C. Side-effect free,
declarative, expression
30. Consider the following C program segment: evaluation
struct CellNode{ IV. Imperative D. Declarative, clausal
structCellNode representation, theorem
*leftChild; proving
int element;
(a) I-B, II-C, III-D, IV-A
structCellNode
*rightChild; (b) I-D, II-C, III-B, IV-A
};
(c) I-C, II-D, III-A, IV-B
intDosomething (structCellNode *ptr) (d) I-C, II-D, III-B, IV-A
{ (GATE 2004: 2 Marks)
int value = 0;
Solution:  Functional languages have no side
if (ptr ! = NULL)
effects and follow the declarative approach. Logic
{ 
if (ptr -> leftChild ! = NULL)
languages are declarative and used for theorem
value = 1 + DoSomething (ptr - proving. Object-oriented languages use abstract
>leftChild);
data types. Imperative languages are command
if (ptr -> rightChild ! = NULL)
based and procedural.
value = max(value,1 + Ans. (d)
DoSomething (ptr->rightChild));
} 32. What does the following C-statement declare?
return (value); int (*f) (int * );
}
(a) A function that takes an integer pointer as
The value returned by the function DoSomething argument and returns an integer.
when a pointer to the root of a non-empty tree is (b) A function that takes an integer as argument
passed as argument is and returns an integer pointer.
(c) A pointer to a function that takes an integer
(a) The number of leaf nodes in the tree. pointer as argument and returns an integer.
(b) The number of nodes in the tree. (d) A function that takes an integer pointer as
(c) The number of internal nodes in the tree. argument and returns a function pointer.
(d) The height of the tree.
(GATE 2005: 1 Mark)
(GATE 2004: 2 Marks)
Solution: 
Solution:  DoSomething( ) returns max(height of ⇒ int ( * f) (int * )
left child + 1, height of left child + 1). So given that ⇒ return type is int, (*f) means pointer to function
pointer to root of tree is passed to DoSomething( ), with argument as integer pointer.
it will return height of the tree. Note that this Ans. (c)
implementation follows the convention where
height of a single node is 0. 33. An abstract data type (ADT) is:
Ans. (d) (a) Same as an abstract class.
31. Choose the best matching between the program- (b) A data type that cannot be instantiated.
ming styles in Group 1 and their characteristics in (c) A data type for which only the operations
Group 2. defined on it can be used, but none else.
(d) All of the above.
Group 1 Group 2 (GATE 2005: 1 Mark)

I. Functional A. Command-based, Solution:  ADT is user-defined data type that


procedural specifies the set of operations.
Ans. (c)
II. Logic B. Imperative, abstract
data types 34. A common property of logic programming lan-
guages and functional languages is:

Chapter 3.indd 149 4/9/2015 9:51:55 AM


150     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(a) Both are procedural languages. (a) 8, 4, 0, 2, 14 (b) 8, 4, 0, 2, 0


(b) Both are based on l calculus. (c) 2, 0, 4, 8, 14 (d) 2, 0, 4, 8, 0
(c) Both are declarative. (GATE 2005: 2 Marks)
(d) Both use Horn-clauses.
(GATE 2005: 1 Mark) Solution: 
Solution:  Both are declarative because we declare Iteration k j foo(n, sum)
variable before use.
Ans. (c) 1, n = 2048, 8 204 foo(204,8)
Sum = 0
35. Which one of the following are essential features of
2, n = 204, 4 20 foo(20, 12)
an object-oriented programming language?
Sum = 8
I Abstraction and encapsulation 3, n= 20, 0 2 foo(2,12)
II Strictly typedness Sum = 12
III Type-safe property coupled with sub-type rule 4, n = 2, 2 0 foo(0,14), for
IV Polymorphism in the presence of inheritance Sum = 12 this call function
(a) I and II only (b) I and IV only will return.
(c) I, II and IV only (d) I, III and IV only
For recursive function calls, stack is used to store
(GATE 2005: 1 Mark)
values. So the values will be printed as 2 0 4 8. And
Solution:  Common property of OOP is abstrac- value of sum is 0. Because sum is passed by value
tion and encapsulation and polymorphism in the not by reference. Changes are not reflected back to
presence of inheritance. the main program.
Ans. (b) Ans. (d)

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

Chapter 3.indd 150 4/9/2015 9:51:56 AM


GATE PREVIOUS YEARS’ QUESTIONS     151

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:

Solution:  Inorder traversal is always sorted in (a) No compilation error


increasing order. (b) Only a lexical error
Ans. (a) (c) Only syntactic errors
(d) Both lexical and syntactic errors
40. A priority queue is implemented as a max-heap. (GATE 2005: 2 Marks)
Initially, it has five elements. The level-order tra-
versal of the heap is given below: Solution:  Misspellings of int keyword in line 2 and
there should be `for’ instead of `fro’ in line 3.
10, 8, 5, 3, 2 Ans. (c)
Two new elements `1’ and `7’ are inserted in the Linked Answer Questions 44 and 45: Let s and t
heap in that order. The level-order traversal of the be two vertices in a undirected graph G = (V, E)
heap after the insertion of the elements is: having distinct positive edge weights. Let [X, Y  ]
(a) 10, 8, 7, 5, 3, 2, 1 (b) 10, 8, 7, 2, 3, 1, 5 be a partition of V such that s ∈ X and T ∈ Y.
(c) 10, 8, 7, 1, 2, 3, 5 (d) 10, 8, 7, 3, 2, 1, 5 Consider the edge e having the minimum weight
amongst all those edges that have one vertex in X
(GATE 2005: 2 Marks)
and one vertex in Y.
Solution:  44. The edge e must definitely belong to:
10 10 (a) the minimum weighted spanning tree of G
10 10
/ / /
/

/ (b) the weighted shortest path from s to t


/

8 5 5 8 (c) each path from s to t


8 8 5 7
(d) the weighted longest path from s to t
/ / / / / / /
/

3 2 3 2 1 3 2 1 7 3 2 1 5 (GATE 2005: 2 Marks)

Level order traversal is 10, 8, 7, 3, 2, 1, 5 Solution:  Minimum weight edge is included in


Ans. (d) minimum spanning tree.
Ans. (a)
41. How many distinct binary search trees can be
­created out of 4 distinct keys? 45. Let the weight of an edge e denote the congestion
on that edge. The congestion on a path is defined
(a) 5    (b) 14    (c) 24    (d) 42 to be the maximum of the congestions on the edges
(GATE 2005: 2 Marks) of the path. We wish to find the path from s to
t having minimum congestion. Which one of the
Solution:  Number of distinct binary trees = following paths is always such a path of minimum
1/1+n (2nCn) = 14 congestion?
Ans. (b)
(a) a path from s to t in the minimum weighted
42. In a complete k-ary tree, every internal node has spanning tree
exactly k children. The number of leaves in such a (b) a weighted shortest path from s to t
tree with n internal nodes is: (c) an Euler walk from s to t
(a) nk (b) (n − 1)k + 1 (d) a Hamiltonian path from s to t
(c) n(k − 1) + 1 (d) n(k − 1) (GATE 2005: 2 Marks)
(GATE 2005: 2 Marks)
Solution:  Path from s to t in the minimum
Solution:  If there are n internal nodes, then weighted spanning tree is the path of minimum
number of leave nodes will be n(k−1) + 1 congestion.
Ans. (c) Ans. (a)

Chapter 3.indd 151 4/9/2015 9:51:56 AM


152     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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?

Chapter 3.indd 152 4/9/2015 9:51:56 AM


GATE PREVIOUS YEARS’ QUESTIONS     153

(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

Chapter 3.indd 153 4/9/2015 9:51:56 AM


154     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

 3: Correctly implements the swap procedure for


S (c) 10, 9, 4, 5, 7, 6, 8, 2, 1, 3
all input pointers referring to integers stored in (d) 10, 8, 6, 9, 7, 2, 3, 4, 1, 5
memory locations accessible to the process
(GATE 2006: 2 Marks)
S4: Implements the swap procedure correctly for
some but not all valid input pointers Solution:  After inserting 7, 2, 10, 4, the heap
S5: May add or subtract integers and pointers sequence will be 10, 7, 9, 8, 3, 1, 5, 2, 6, 4.
(a) S1 (b) S2 and S3 Ans. (a)
(c) S2 and S4 (d) S2 and S5
58. Consider the following segment of C code:
(GATE 2006: 2 Marks)
int j, n;
Solution:  j = 1;
S2: May generate segmentation fault if value at while (j <=n)
pointers px or py is constant or px or py points to
j = j*2;
a memory location that is invalid.
S4: May not work for all inputs as arithmetic over- The number of comparisons made in the execution
flow can occur. of the loop for any n > 0 is:
Ans. (c)
(a) [log2n] + 1 (b) n
Common Data Questions 56 and 57: A 3-ary max- (c) [log2n] (d) [log2n] + 1
heap is like a binary max-heap, but instead of 2
(GATE 2007: 1 Mark)
children, nodes have 3 children. A 3-ary heap can
be represented by an array as follows: The root Solution:  Check using values n = 3,4,5….
is stored in the first location, a[0], nodes in the Ans. (d)
next level, from left to right, are stored from a[1]
to a[3]. The nodes from the second level of the 59. The maximum number of binary trees that can be
tree from left to right are stored from a[4] location formed with three unlabeled nodes is:
onward. An item x can be inserted into a 3-ary
(a) 1 (b) 5
heap containing n items by placing x in the loca-
(c) 4 (d) 3
tion a[n] and pushing it up the tree to satisfy the
heap property. (GATE 2007: 1 Mark)

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)

Chapter 3.indd 154 4/9/2015 9:51:57 AM


GATE PREVIOUS YEARS’ QUESTIONS     155

Solution:  64. Consider the following C function:


Expression TOS int f(int n)
{static int r = 0;
8 8
if (n <= 0) return 1;
2 8,2 if (n > 3)
3 8,2,3 {r = n;
∧ return f(n-2)+2;
8,8 }
/ 1 return f(n-1)+r;
2 1,2 }

3 1,2,3 What is the value of f (5)?


* 1,6 (a) 5    (b) 7    (c) 9    (d) 18
Top of stack contain 1,6. (GATE 2007: 2 Marks)

Ans. (a) Solution: 


62. The inorder and preorder traversal of a binary tree f(5) r = 5 , 2 + f(3)
are d b e a f c g and a b d e c f g, respectively. The
postorder traversal of the binary tree is: f(3) 2 + 5 + f(2)
f(2) 7 + 5 + f(1)
(a) d e b f g c a (b) e d b g f c a
(c) e d b f g c a (d) d e f g b c a f(1) 12 + 5 + f(0)
(GATE 2007: 2 Marks) f(0) 17 + 1 = 18
Ans. (d)
Solution:  Construct equivalent tree from inorder
and preorder traversal. 65. A complete n-ary tree is a tree in which each node
a has n children or no children. Let I be the number
/ / of internal nodes and L be the number of leaves in
b c a complete n-ary tree. If L = 41, and I = 10, what
/ / / / is the value of n?
d e f g
(a) 3    (b) 4    (c) 5    (d) 6
Postorder traversal is: d e b f g c a
Ans. (a) (GATE 2007: 2 Marks)

63. Consider a hash table of size seven, with starting Solution: 


index zero, and a hash function (3x + 4) mod 7. I [n − 1] + 1 = L
Assuming the hash table is initially empty, which N = (L − 1)/I + 1 = 40/10 + 1= 5
of the following is the contents of the table when Ans. (c)
the sequence 1, 3, 8, 10 is inserted into the table
using closed hashing? Note that - denotes an empty 66. Consider the following C program segment where
location in the table. CellNode represents a node in a binary tree:
(a) 8, - , - , - , - , - , 10 (b) 1, 8, 10, - , - , - , 3 structCellNode {
(c) 1, - , - , - , - , - , 3 (d) 1, 10, 8, - , - , - , 3 structCellNode *leftChild;
(GATE 2007: 2 Marks) int element;
structCellNode *rightChild;
Solution: };
Hash function is: (3x + 4) mod 7 intGetValue (structCellNode *ptr) {
X = 1 7 mod 7 = 0 int value = 0;
X = 3 13 mod 7 = 6 if (ptr != NULL) {
X = 8 28 mod 7 = 0 since 0 occupied, it will be if((ptr->leftChild ==
on 1st position NULL) &&
X = 10 34 mod 7 = 6 since 6,0,1 is occupied it 
(ptr->rightChild
will at 2nd position  == NULL))
So 1 8 10 - - - 3 value = 1;
else
Ans. (b)

Chapter 3.indd 155 4/9/2015 9:51:57 AM


156     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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)

67. Consider the process of inserting an element into M N O


a max-heap, where the max-heap is represented
by an array. Suppose we perform a binary search
on the path from the new leaf to the root to find
the position for the newly inserted element, the
number of comparisons performed is:
R Q P
(a) Θ (log2n) (b) Θ (log2log2n)
(c)   Θ (n) (d) Θ (nlog2n)
(a) MNOPQR (b) NQMPOR
(GATE 2007: 2 Marks) (c) QMNPRO (d) QMNPOR

Solution:  Inserting an element in binary tree (GATE 2008: 1 Mark)


takes Θ(1) and binary search takes Θ(logn).
Solution:  In BFS, all the children of node will be
Ans. (a) traversed first.
68. An array of n numbers is given, where n is an even Ans. (a)
number. The maximum as well as the minimum of 71. You are given the postorder traversal, P, of a
these n numbers need to be determined. Which of binary search tree on the n elements 1, 2, …, n.
the following is TRUE about the number of com- You have to determine the unique binary search
parisons needed? tree that has P as its postorder traversal. What is
(a) At least 2n − c comparisons, for some constant, the time complexity of the most efficient algorithm
c are needed. for doing this?
(b) At most 1.5 − 2 comparisons are needed. (a) Θ (logn)
(c) At least nlog2n comparisons are needed. (b) Θ (n)
(d) None of the above. (c) Θ (n log n)
(GATE 2007: 2 Marks) (d) None of the above, as the tree cannot be
uniquely determined
Solution:  Using divide and conquer technique
problem is divided into two parts of n/2. (GATE 2008: 2 Marks)

T(n) = 2 T(n/2) + 2 Solution: 


Solution of this equation is 3/2 n − 2 comparisons Step 1: The last element in the postorder traversal
Ans. (b) P will act as the root element.

Chapter 3.indd 156 4/9/2015 9:51:58 AM


GATE PREVIOUS YEARS’ QUESTIONS     157

Step 2: Now in P the elements that are smaller main () {


than root will form the left subtree pr
int f ("Enter Text");
Step 3: The elements in P that are greater than print f ("\ n");
root will form the right subtree  
reverse ();
Step 4: Binary search could be used to find the left print f ("\ n");
and right tree elements }
Ans. (c) (a) ? 1 is (getchar ( )! = ‘n’)
? 2 isgetchar (c);
72. We have a binary heap on n elements and wish to
insert n more elements (not necessarily one after (b) ? 1 is (c = getchar ( ) )! = ‘n’)
another) into this heap. The total time required for ? 2 isgetchar (c);
this is (c) ? 1 is (c ! = ‘n’)
(a) Θ (log n) (b) Θ (n) ? 2 isputchar (c);
(c)   Θ (nlog n) (d) Θ (n2) (d) ? 1 is ((c = getchar ( ) )! = ‘n’)
? 2 isputchar (c);
(GATE 2008: 2 Marks)
(GATE 2008: 2 Marks)
Solution:  Time require to re-heapify is O(n).
Ans. (c) Solution:  ?1 checks the end of string, if not end of
string it calls reverse function.
73. What is printed by the following C program? ?2 prints the reverse string.
int f(int x, int *py, int **ppz) Ans. (d)
{
int y, z; 75. The following C function takes a single-linked
**ppz + = 1; z = *ppz; list of integers as a parameter and rearranges the
*py + = 2; y = *py; elements of the list. The function is called with
x + = 3; the list containing the integers 1,2,3,4,5,6,7 in the
return x + y + z: given order. What will be the contents of the list
} after the function completes execution?
void main()
{ struct node {
int c, *b, **a; int value;
c = 4; b = &c; a = &b; struct node * next;
print f("%d", f(c, b, a)); };
} Void rearrange (struct node * list) {
struct node * p, * q;
(a) 18 (b) 19 int temp;
(c) 21 (d) 22 if (!list || !list ® next) return;
(GATE 2008: 2 Marks) p = list; q = list ®> next;
while q {
Solution:  mp = p ® value; p ®> value
te
** ppz = 4 +1 = 5 = q ®value;
z=5 q ®value = temp; p = q ® next
y=5+2=7 q = p? p ® next : 0;
x = 7 + 3 = 10 }
x + y + z = 10 + 7 + 5 = 22 }
Ans. (d) (a) 1,2,3,4,5,6,7 (b) 2,1,4,3,6,5,7
74. Choose the correct option to fill ? 1 and ? 2 so that (c) 1,3,2,5,4,7,6 (d) 2,3,4,5,6,7,1
the program below prints an input string in reverse
(GATE 2008: 2 Marks)
order. Assume that the input string is terminated
by a newline character. Solution:  The program is simply swapping two
void reverse (void) { consecutive numbers.
int c; Here, input: 1,2,3,4,5,6,7
if (?1) reverse (); Output: 2,1,4,3,6,5,7
?2
} Ans. (b)

Chapter 3.indd 157 4/9/2015 9:51:58 AM


158     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

76. P and Q are two propositions. Which of the follow- 8*12*30


ing logical expressions are equivalent?
I. P ∨ ~ Q 5 10 15*20 40
II. ~ (~ P ∧ Q)
III. (P ∧ Q) ∨ (P ∧ ~ Q) ∨ (~ P ∧ ~ Q)
Insertion of 9th key
IV. (P ∧ Q) ∨ (P ∧ ~ Q) ∨ (~ P ∧ Q)
To maximize splits, let us insert a value in a node
that has key in access. Let us insert 17
(a) Only I and II (b) Only I, II and III
(c) Only I, II and IV (d) All of I, II III and IV 8*12*30
/ / /
(GATE 2008: 2 Marks) 5 10 15*17*20 40
Solution:  IV represent P ∨ Q. Assuming values of
Insertion of 10th key (4th and 5th Splits)
P and Q can provide us the solution.
To maximize splits, let us insert a value in a node
Ans. (b)
that has key in access. Let us insert 13
77. A B-tree of order 4 is built from scratch by 10 suc-
12
cessive insertions. What is the maximum number
/ /
of node splitting operations that may take place?
8 15*30
(GATE 2008: 2 Marks) / / / //
5 1 0 1 3 1 7 * 2 0 40
(a) 3    (b) 4    (c) 5    (d) 6
Ans. (a)
Solution:  Insertion of 3 keys
Common Data Questions 78 and 79: Consider the
10 20 30 following C functions:
Insertion of 4th key (1st split)
int f1 (int n)
30 {
/ / if (n == 0 | | n == 1)
10*20 40 return n;
else
Insertion of 5th key no split return (2* f1 (n - 1) + 3 * f1 (n - 2))
To maximize splits, let us insert a value in a node }
that has key in access. Let us insert 5 int f2 (int n)
{
30 int i:
/

int X[N], Y[N], Z[N];


5*10*20 40
X[0] = Y[0] = Z[0] = 0;
Insertion of 6th key (2nd Split) X[1] = 1; Y[1] = 2; Z[1] = 3;
To maximize splits, let us insert a value in a node for (i = 2; i <= n; i ++) {
that has key in access. Let us insert 6 X[i] = Y[i - 1] + Z[i - 2];
Y[i] = 2 * X[i];
8 *30 Z[i] = 3 * X[i];
}
5 10 * 20 40 return X[n];
}

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)

5 10 *15* 20 40 Solution:  For f1 recurrence relation is,


T (n) = T(n −1) + T(n −2)
Insertion of 8th key (3rd Split) This type of relations has non-polynomial
To maximize splits, let us insert a value in a node complexity.
that has key in access. Let us insert 12 Ans. (b)

Chapter 3.indd 158 4/9/2015 9:52:00 AM


GATE PREVIOUS YEARS’ QUESTIONS     159

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)

Chapter 3.indd 159 4/9/2015 9:52:00 AM


160     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

Solution:  Solution:  i and j are passed by address, any modi-


Conditions for max heap: fication by function will be reflected back.
•• Data at every node should be greater than its When p = q means address of q is changed.
children nodes *p = 2 will modify value of q to 2.
•• Left child is at 2i+1 and right at 2i+2 Ans. (d)
Ans. (c)
88. Which languages necessarily need heap allocation
85. What is the content of the array after two delete oper- in the runtime environment?
ations on the correct answer to the previous question?
(a) Those that support recursion
(a) {14, 13,12,10, 8} (b) {14,12,13, 8,10} (b) Those that use dynamic scoping
(c) {14,13, 8, 12,10} (d) {14,13,12, 8,10} (c) Those that allow dynamic data structures
(GATE 2009: 2 Marks) (d) Those that use global variables

Solution:  (GATE 2010: 1 Mark)


Deletion can be done by following steps:
•• Replace the root with last node Solution:  Runtime environment require dynamic
•• Re-heapify the tree memory allocation. Heap data structure is used for
dynamic memory allocation.
14
/ Ans. (a)
/

/
/

89. What is the value printed by the following C


13 12 program?
/ #include <stdio.h>
/

/ int f(int * a, int n)


/

{
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)))

(a) 2 2    (b) 2 1    (c) 0 1    (d) 0 2 f(6,1) 12 + 7 − (13 − (4 + 11 − 6 )) = 15


(GATE 2010: 1 Mark) Ans. (c)

Chapter 3.indd 160 4/9/2015 9:52:00 AM


GATE PREVIOUS YEARS’ QUESTIONS     161

90. The following C function takes a simply linked Solution: 


list as input argument. It modifies the list by Let base address is 100
moving the last element to the front of the list So, 100 + E − A = 104
and returns the modified list. Some part of the
code is left blank. 100 101 102 103 104 105 106 107
typedefstruct node { G A T E 2 0 1 1
int value;
struct node *next;
} Node; 2011 will be printed.
Node *move_to_front(Node *head) { Ans. (c)
Node *p, *q;
if 
((head = = NULL: || (head->next =
= NULL)) return head; 92. A max-heap is a heap where the value of each
q = NULL; p = head; parent is greater than or equal to the value
while (p-> next !=NULL) { of its children. Which of the following is a
q=P; max-heap?
p=p->next;
} (a)
10
_______________________________
return head;
}
8 6
Choose the correct alternative to replace the blank
line.
(a) q = NULL; p → next = head; head = p;
(b) q → next = NULL; head = p; p → next = head;
4 5 2
(c) head = p; p → next = q; q → next = NULL;
(d) q → next = NULL; p → next = head; head = p; 1
(GATE 2010: 2 Marks)

Solution:  When the while loop ends, q contains


(b)
address of second last node and p contains address 10
of last node. So, we need to do the following things
after while loop.

  (i) Set next of q as NULL (q->next = NULL). 8 6


(ii) Set next of p as head (p->next = head).
(iii) Make head as p ( head = p)
Step (ii) must be performed before step (iii). If we
4 5 1 2
change head first, then we lose track of head node
in the original linked list.
Ans. (d)
(c) 10
91. What does the following fragment of C program
print?
char c [] = “GATE2011”;
char *p = c; 5 6
printf(”%s”, p + p[3] — p[1]):

(a) GATE2011 (b) E2011


(c) 2011 (d) 011 4 8 2 1
(GATE 2011: 1 Mark)

Chapter 3.indd 161 4/9/2015 9:52:01 AM


162     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(d) (c)
5

2 8
2

3
1 4 6 10

3 4
(GATE 2011: 1 Mark)

Solution:  Heap is also complete binary tree. (d)

Ans. (b) 2

93. Consider two binary operators ” and `↓’ with the


precedence of operator ↓ being lower than that of 3
the operator . Operator is right associative while
operator ↓ is left associative. Which one of the
4
following represents the parse tree for expression
(7↓343↓2)?
7 3

(a) (GATE 2011: 2 Marks)

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 }

94. What is the return value of the function foo when


3 it is called foo(345, 10)?
(a) 345    (b) 12    (c) 5    (d) 3
4 3 (GATE 2011: 2 Marks)

Chapter 3.indd 162 4/9/2015 9:52:03 AM


GATE PREVIOUS YEARS’ QUESTIONS     163

Solution:  index variables, respectively. Initially, REAR =


FRONT = 0. The conditions to detect queue full
n = 345 and r = 10 345 % 10 + foo(34,10) = and queue empty are
5 + ….
(a) full: (REAR+1) mod n == FRONT
n = 34, r = 10 5 + 4 + foo(3,10) empty: REAR == FRONT
n = 3, r = 10 9 + 3 + foo (0,10) (b) full: (REAR+1) mod n == FRONT
n = 0, r = 10 12 + 0 = 12 empty: (FRONT+1) mod n == REAR
Ans. (b) (c) full: REAR == FRONT
empty: (REAR+1) mod n == FRONT
95. What is the return value of the function foo when
(d) full: (FRONT+1) mod n == REAR
it is called foo(513, 2)?
empty: REAR == FRONT
(a) 9    (b) 8    (c) 5    (d) 2 (GATE 2012: 2 Marks)
(GATE 2011: 2 Marks)
Solution: 
Solution:  Condition for queue full:
(Rear + 1) mod n = = front
n = 513 and r = 2 513 % 2 + foo(256, 2) = 1
Condition for queue free:
+ ….
Rear = = front
n = 256, r = 2 1 + 0+ foo(128, 2) Ans. (a)
n = 128, r = 2 1 + foo (64, 2) 98. The height of a tree is defined as the number of
n = 64, r = 2 1 + foo(32, 2) edges on the longest path in the tree. The func-
….. n = 2, r = 2 …. 1 + foo(1, 2)
tion shown in the pseudocode below is invoked as
height(root) to compute the height of a binary tree
n = 1, r = 2 1+1+0=2 rooted at the tree pointer root.
Ans. (d) int height (treeptr n)
{ if (n == NULL) return -1;
96. What will be the output of the following C pro- if (n ® left == NULL)
gram segment? if (n ® right == NULL) return 0;
char inChar = ‘A’ ;
switch(inChar) { else return B1 ; // Box 1
case ‘A’ : printf("Choice A\ n") ;
case ‘B’ : else { h1 = height (n ® left);
case ‘C’ : printf("Choice B") ; if(n ® right == NULL)
case ‘D’ : return (1+h1);
case ‘E’ : else { h2 = height (n ® right);
         
default :printf("No Choice") ; } return B2 ; // Box 2
}
(a) No choice }
(b) Choice A }
(c) Choice A choice B no choice
(d) Program gives no output as it is erroneous The appropriate expressions for the two boxes B1
(GATE 2012: 1 Mark) and B2 are
(a) B1: (1 + height (n → right))
Solution:  No break statement is available, it will B2: (1 + max (h1, h2))
execute all the cases.
Choice A (b) B1: (height (n → right))
Choice B No Choice B2: (1 + max (h1,h2))
Ans. (c) (c) B1: height (n → right)
97. Suppose a circular queue of capacity (n − 1)
B2: max (h1, h2)
elements is implemented with an array of n elements. (d) B1: (1 + height (n → right))
Assume that the insertion and deletion operations B2: max (h1, h2)
are carried out using REAR and FRONT as array (GATE 2012: 2 Marks)

Chapter 3.indd 163 4/9/2015 9:52:03 AM


164     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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

Common Data Questions 99 and 100: Consider the (c) (d)


following C code segment: 4 2 42
int a, b, c = 0; 6 2 42
void prtFun(void);
2 0 20
main( )
{ staticint a = 1; /*Line 1*/ (GATE 2012: 2 Marks)
prtFun( );
a += 1; Solution:  Line 2 is replaced with register storage
prtFun( ); class, the values will not be preserved.
printf(" \n %d %d ", a, b); So it will print
} 4 2
4 2
voidprtFun(void) 2 0
{ staticint a = 2; /*Line 2*/ Ans. (d)
int b = 1;
101. Consider an undirected random graph of eight ver-
a += ++b;
printf(" \n %d %d ", a, b);
tices. The probability that there is an edge between
a pair of vertices is 1/2. What is the expected
} number of unordered cycles of length three?

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;

Chapter 3.indd 164 4/9/2015 9:52:03 AM


PRACTICE EXERCISES     165

if(c==0) return 1; (a) Q(n) (b) Q(n + k)


x = x + 1; (c) Q(nk) (d) Q(n2)
return f(x,c) * x;
} (GATE 2013: 2 Marks)
(a) 3024 (b) 6561
Solution:  Any combination of n Enqueue and
(c) 55440 (d) 161051
Dequeue operations will take Q(n)
(GATE 2013: 2 Marks)
Ans. (a) 
Solution:  For p = 5,
f(6, 4) * 6 = 9 * 8 * 7 * 6 = 3024 106. Suppose depth first search is executed on the
graph below starting at some unknown vertex.
Ans. (b) Assume that a recursive call to visit a vertex is
104. The preorder traversal sequence of a binary search made only after first checking that the vertex
tree is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one has not been visited earlier. Then the maximum
of the following is the postorder traversal sequence possible recursion depth (including the initial call)
of the same tree? is .

(a)  10, 20, 15, 23, 25, 35, 42, 39, 30


(b) 15, 10, 25, 23, 20, 42, 35, 39, 30
(c)    15, 20, 10, 23, 25, 42, 35, 39, 30
(d) 15, 10, 23, 25, 20, 35, 42, 39, 30
(GATE 2013: 2 Marks)

Solution:  Postorder traversal: Left Right Root


15, 10, 23, 25, 20, 35, 42, 39, 30 is the correct order.
Ans. (d) (a) 17 (b) 18
105. Consider the following operation along with (c) 19 (d) 20
enqueue and dequeue operations on queues, where
k is a global parameter. Solution:  By following the given path in graph,
maximum possible depth is 19.
MultiDequeue(Q){
m = k;
while (Q is not empty) and (m > 0) {
Dequeue(Q);
m = m – 1;
}
}

What is the worst case time complexity of a


sequence of n queue operations on an initially
empty queue? Ans. (c)

PRACTICE EXERCISES

Set 1

1. Predict the output of: (a) 5 (b) 6


(c) Compile time error (d) Runtime error
void main()
{ 2. Declaration of a pointer is given as (*ptr)[10]. Pick
int const*p=5; the correct answer.
printf("%d",++(*p));
(a)  ptr is a pointer to an integer quantity.
}
(b) ptr is a pointer to a 10-element integer array.

Chapter 3.indd 165 4/9/2015 9:52:03 AM


166     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(c)  ptr is a 10-element array of pointers to integer 7. char func(intval)


quantities.
{
(d) ptr is a pointer to an 11-element integer array.
char ch=val;
3. struct a return ch;
{ }
int a; void main()
char b; {
int c; float a=115.76;
}; printf("%d",func(a));
Union b }
{
The output will be:
char a;
int b; (a) 0 (b) 115.76
int c; (c) 116 (d) Runtime error
};
8. staticint func(intval)
Which of these is correct?
{
(a)  Size of a is always different from size of b.
staticint sum;
(b) Size of a is always same as size of b. sum+=val;
(c)    a and b cannot be same because of non- return sum;
homogeneity. }
(d) It might result in runtime error.
void main()
4. char a[5]=“hello” which of the following is {
correct? int i, n=9;
(a)  In array we cannot do the operation for(i=1;i<n--;i++)
(b) Size of a is too small func(i*2);
printf("%d", func(0));
(c)   Size of a is too large
}
(d) Runtime error
5. void f(int i) What is the output?
{ (a) 18 (b) 20
int j; (c) 10 (d) 22
for(j=0; j<16; j++)
{ 9. A variable P is called a pointer if
if(i & (0x8000>>j))
printf("1"); (a)   P contains the address of an element in DATA.
else (b)  P points to the address of first element in
printf("0"); DATA.
} (c)  P points to the address of last element in
} DATA.
(d) P contains the DATA and the address of
What is the purpose of this program?
DATA.
(a)  Its output is hex representation of i.
(b) Its output is octal representation of i. 10. Size of (int) is
(c)   Its output is decimal representation of i. (a)  always 2 bytes.
(d) Its output is binary representation of i. (b) depends on compiler being used.
6 . What is the meaning of this pointer declaration: (c)    depends on computer hardware being used.
char ptr(int(*a)[ ]); (d) always 32 bits.

(a)  Invalid statement 11. Predict the output of:


(b) ptr is a function that accepts an argument main()
which is a pointer to an integer array and {
returns a character quantity. char s[]="man";
(c)   ptr is a function that accepts an argument int i;
which is an array of pointers to integers and for(i=0;s[i];i++)
returns a character of integer representation. printf("\n%c%c%c%c",*(s+i),i[s]);
(d) Compile time error }

Chapter 3.indd 166 4/9/2015 9:52:04 AM


PRACTICE EXERCISES     167

(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

Chapter 3.indd 167 4/9/2015 9:52:04 AM


168     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(a) weight matrix. (b) asymmetric matrix. (a) A (b) B


(c) symmetric matrix. (d) unit matrix. (c) H (d) G
32. The merge sort algorithm is based upon 40. If Inorder = EDFBGAJHCI, and Preorder =
(a) divide and conquer technique. ABDEFGCHJI, the root is
(b) 0/1 knapsack technique. (a) A (b) I
(c) optimisation technique. (c) J (d) B
(d) simulated annealing technique.
41. A graph having n vertices and k components can
33. A linked list is a kind of data structure.
have at most:
(a)  Static
(a) n + k/2 edges
(b) Dynamic
(b) n*k/2 edges
(c)   Static as well as dynamic
(c) (n − k)(n − k + 1)/2 edges
(d) Neither dynamic nor static
(d) (n − k)(n − k + 2)/2 edges
34. When the stack is empty, the value of the top of
stack(TOS) pointer is 42. A graph in which all nodes have the same degree is
called
(a) 1
(b) 0 (a) Euler graph. (b) Complete graph.
(c)  −1 (c) Regular graph. (d) Colour graph.
(d) depends on the memory address
43. The time complexity of hashing is
35. In an empty circular queue, the front and rear are?
(a) O(n) (b) O(n log (n − 1))
(a) −1, −1 (b) 0, 0 (c) O(n3 − 1) (d) O(n2log (n − 1))
(c) 0, 1 (d) 1, 1
44. The number of fields required in a doubly linked is
36. Which of the following data structures is non- .
linear type?
(a) 7 (b) 2
(a) Queue (b) Lists (c) 3 (d) 1
(c) String (d) Graph
45. The runtime complexity of building max-heap is
37. A full binary tree has a height of 3, then the
number of nodes of such a tree is . (a) O(n) (b) O(log n)
(c) O(nn − 1) (d) O(n2log n/2)
38. For the following tree, give the postorder traversal
46. A binary tree is of level 7, the maximum number of
(a) 2465371 (b) 2456371 nodes can be
(c) 4257631 (d) 7654321
(a) 129 (b) 128
(c) 255 (d) 256
1
Set 2

2 3 1. What does the following code do?


Var a, b, c; integer
begin
6
4 5 a: = a+b;
b: =a-b;
c: =a-b
7 end
(a)  Exchanges (a) and (b)
(b) Doubles (a) and stores in (b)
39. Find the root in the given preorder traversal (c)  Doubles (b) and stores in (a)
ABDFGECH (d) Leaves (a) and (b) unchanged

Chapter 3.indd 168 4/9/2015 9:52:04 AM


PRACTICE EXERCISES     169

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

Chapter 3.indd 169 4/9/2015 9:52:04 AM


170     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

(a) 10 (b) 4 14. Which of the following is essential for convert-


(c) 6 (d) 7 ing an infix expression to the post-fix form
efficiently?
10. What is printed by the print statements in the
program P1, assuming call-by-reference parameter (a)  An operator stack
passing? (b) An operand stack
(c)  An operand stack and an operator stack
Program P1()
(d) A parse tree
{
x = 10; 15. A priority queue Q is used to implement a stack
y = 3; that stores characters. PUSH(C) is implemented
func1 (y, x, x); INSERT(Q, C, K) where K is an appropriate inte-
print x;
ger key chosen by the implementation. POP is
print y;
implemented as DELETEMIN(Q). For a sequence
}
Func1(x, y, z)
of operations, the keys chosen are in
{ (a)  non-increasing order.
y = y+4; (b) non-decreasing order.
z = x + y +z (c)  strictly increasing order.
} (d) strictly decreasing order.
(a) 10, 3 (b) 27, 7
16. What value would the following function return for
(c) 31, 3 (d) None of these
the input x = 95?
11. Let A be a two-dimensional array declared as Function fun (x: integer): integer;
follows: Begin
A: array [1…10] [1..15] of integer if x > 100 then fun = x - 10
Assuming that each integer takes one memory loca- else fun: = : fun (fun(x+11))
End
tion, the array is stored in row-major order and the
first element of the array is stored at location 100. (a) 89 (b) 90
What is the address of the element A[i][j]? (c) 91 (d) 92
(a) 15i + j + 84 (b) 15j + i + 84 17. In a circular-linked list organisation, insertion of a
(c) 10i + j + 89 (d) 10j + i + 89 record involves modification of
12. Suppose you are given an array s[1 … n] and a (a) one pointer. (b) two pointer.
­procedure reverse (s, i, j) which reverses the order (c) multiple pointer. (d) no pointer.
of elements in between positions i and j (both inclu-
sive). What does the following sequence do, where 18. Linked lists are not suitable data structures of
1≤k≤n which one of the following problems?
reverse (s, 1, k); (a)  Insertion sort
reverse (s, k + 1, n); (b) Binary search
(c)  Radix sort
reverse (s, 1, n)
(d) Polynomial manipulation
(a)  Rotates s left by k position
(b) Leaves s unchanged 19. In the worst case, the number of comparisons
(c)  Reverses all elements of s needed to search singly linked list of length n for a
(d) None of the above given element is
(a)  log2 n (b) n/2
13. Which of the following permutations can be
(c)   log2 n − 1 (d) n
obtained in the output (in the same order) using a
stack assuming that the input is the sequence 1, 2, 20. A binary tree T has n leaf nodes. The number of
3, 4, 5 in that order? nodes of degree 2 in T is
(a) 3, 4, 5, 1, 2 (b) 3, 4, 5, 2, 1 (a) log2 n (b) n − 1
(c) 1, 5, 2, 3, 4 (d) 5, 4, 3, 1, 2 (c)  n (d) 2n

Chapter 3.indd 170 4/9/2015 9:52:04 AM


PRACTICE EXERCISES     171

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

(a) 1 (c) 7 28. The number of leaf nodes in a rooted tree of n


(a) 1 (b) 3 nodes with each node having 0 to 4 children is
(b) 3
(c) 7 (d)(d)
8 8
(a) n/2 (b) (2n − 1)/4
22. A binary search tree is generated by inserting in (c) (n + 1)/4 (d) (2n + 1)/4
order of the following integers: 50, 15, 62, 5, 20,
58, 91, 3, 8, 37, 60, 24. The number of nodes in the 29. Consider the following program:
left sub-tree and right sub-tree of the root, respec- #define funct(x) x*x+x
tively, are int main()
(a) (4, 7) (b) (7, 4) {
(c) (8, 3) (d) (3, 8) int x;
x=23+funct(4)*funct(3);
23. A binary search tree is used to locate the number printf(“%d”,x);
43. Which one of the following sequences is not return 0;
possible? }

(a) 61 52 14  17 40 43 What will be the output of the above program?


(b) 2  3   50 40   60 43 (a) 126 (b) 196
(c) 10 65  31 48   37 43 (c) 149 (d) 132
(d) 81 61 52   14 41 43
Output of the following program will be
24. A binary search tree contains the values 1, 2, 3, int main
4, 5, 6, 7, 8. The tree is traversed in preorder and {
the values are printed out. Which of the following int i, a[6]= 000, 001, 010, 011, 100,
sequences is a valid output? 101, 110, 111;
(a) 53124786 (b) 53126487 for i=0;i<6;i++
(c) 53241678 (d) 53124768 printf"%d", a[i];
return0;
25. Which of the following statements is false? }
(a)  A tree with n nodes has (n − 1) edges. (a) 0, 1, 2, 3, 4, 5
(b) A labelled rooted binary tree can be uniquely (b) 0, 1, 10, 11, 100, 101
constructed given its postorder and preorder (c) 0, 1, 8, 9, 100, 101
traversal results. (d) None of these
(c)  A complete binary tree with n internal nodes
has (n + 1) leaves. 30. The minimum and maximum number of keys
(d) The maximum number of nodes in a binary tree in the internal nodes of B tree with order 4 is,
of height h is (2h+1 − 1) respectively
26. A complete n-ary tree is one in which every node (a) 1, 3 (b) 2, 4
has 0 or n sons. If x is the number of internal nodes (c) 1, 4 (d) 2, 3

Chapter 3.indd 171 4/9/2015 9:52:05 AM


172     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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);
}

ANSWERS TO PRACTICE EXERCISES

Set 1

1. (c) 11. (a) 21. (a) 31. (b) 41. (d)


2. (b) 12. (c) 22. (d) 32. (a) 42. (c)
3. (a) 13. (b) 23. (d) 33. (b) 43. (a)
4. (b) 14. (a) 24. (d) 34. (c) 44. (c)
5. (a) 15. (b) 25. (a) 35. (a) 45. (b)
6. (b) 16. (c) 26. (d) 36. (d) 46. (b)
7. (a) 17. (c) 27. (b) 37. (3)
8. (b) 18. (c) 28. (a) 38. (c)
9. (a) 19. (a) 29. (a) 39. (a)
10. (b) 20. (a) 30. (d) 40. (a)

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

Chapter 3.indd 172 4/9/2015 9:52:05 AM


ANSWERS TO PRACTICE EXERCISES     173

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.

13. (a) During the conversion of infix to postfix expres-


sion, operands do not change their position. So, After a node h is added as a child of g
only operator stack is needed.
2 a
14. (d) Stack works on concept of first-in last-out.
But according to the question, it should work like
queue means first-in first-out. For that, we give the Unbalanced 2 b e 1
higher priority to the first element. So, all elements nodes
should form strictly decreasing order. 2 d
c
f
15. (c) fun (98) 0
0
    fun fun(109) 1 g
    fun (99)
      fun (fun (200)) h
0
      fun (100)
        fun (fun(111)) Nodes a, b and c become unbalanced.

Chapter 3.indd 173 4/9/2015 9:52:06 AM


174     Chapter 3:  PROGRAMMING AND DATA STRUCTURES 

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)

5 27. (d) Total number of nodes in n-ary tree = n(internal


nodes) + 1

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.

Chapter 3.indd 174 4/9/2015 9:52:07 AM

You might also like