You are on page 1of 114

Biyani's Think Tank

A concept based exclusive material

Algorithms and
Application Programming
M.Sc. I.T.

Deptt. of Information Technology


Biyani Girls College, Jaipur

Biyani's Think Tank

Published by :

Think Tanks
Biyani Group of Colleges

Concept & Copyright :

Biyani Shikshan Samiti


Sector-3, Vidhyadhar Nagar,
Jaipur-302 023 (Rajasthan)
Ph : 0141-2338371, 2338591-95 Fax : 0141-2338007
E-mail : acad@biyanicolleges.org
Website :www.gurukpo.com; www.biyanicolleges.org

First Edition : 2009

While every effort is taken to avoid errors or omissions in this Publication, any mistake or
omission that may have crept in is not intentional. It may be taken note of that neither the
publisher nor the author will be responsible for any damage or loss of any kind arising to
anyone in any manner on account of such errors and omissions.

Leaser Type Setted by :


Biyani College Printing Department

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

Preface

am glad to present this book, especially designed to serve the needs of the

students. The book has been written keeping in mind the general weakness in
understanding the fundamental concepts of the topics. The book is self-explanatory and
adopts the Teach Yourself style. It is based on question-answer pattern. The language
of book is quite easy and understandable based on scientific approach.
This book covers basic concepts related to the microbial understandings about
diversity, structure, economic aspects, bacterial and viral reproduction etc.
Any further improvement in the contents of the book by making corrections,
omission and inclusion is keen to be achieved based on suggestions from the readers
for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay Biyani,
Director (Acad.) Biyani Group of Colleges, who are the backbones and main concept
provider and also have been constant source of motivation throughout this Endeavour.
They played an active role in coordinating the various stages of this Endeavour and
spearheaded the publishing work.
I look forward to receiving valuable suggestions from professors of various
educational institutions, other faculty members and students for improvement of the
quality of the book. The reader may feel free to send in their comments and suggestions
to the under mentioned address.
Author

Biyani's Think Tank

Syllabus
M.Sc.-IT (Sem.-I)

111 : ALGORITHMS AND APPLICATION


PROGRAMMING
Algorithmic Methodology : Basic Concepts and Notation, Understanding the Problem,
Plan the Logic, Code the Program, Pseudocode and Flowchart, Efficiency of
Algorithms. Complexity Measures, Basic Time Analysis of an Algorithm, Space
Complexity.
Conditionals : Control Structures and Program Writing.
Looping : Repetitions.
Abstract Data Types : Data Abstraction and Basic Data Structures, Data Types, Abstract
Data Types.
Recursion : Characteristics of Recursive Functions, Mathematical Induction
Propositional Logic, First Order Predicate Calculus : Introduction to Formal Logic,
Propositions, Conditional Propositions, Proofs, Resolution Proofs, Rules of Inference
Program Specification : Problem Solving, Variables, Selection, Modules and Repetitions.
Arrays : Storage Allocation Functions, Linked Allocation, Hashed Allocation
Techniques, Sorting Searching Sequential, Binary and Hashed Searching, Internal and
External Sorting Techniques, Bubble Sort, Insertion Sort, Selection Sort, Merge Sort,
Radix Sort and Quick Sort Comparisons and String Conversions, Representations of
Variable-Length Strings, Examples of Operations on Strings.
Data Structures and File Handling : File Organisation, Text and Binary Files, Opening
and Closing Files.
Advanced Programming Concepts : (Introduction Only) : Recursion, Dynamic Memory
Management and Allocation, Operating System Calls, Inner Process Communication,
Advanced File Handling and Indexing.
Language : C (Examples using C wherever required).

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

Content
S.No.
Name of Topic
1. Algorithmic Methodology
1.1
Understanding the Problem
1.2
Plan the Logic
1.3
Code the Program
1.4
Pseudocode
1.5
Flowchart
1.6
Time & Space Complexity
2. Conditionals & Looping
2.1
Control Structure
2.2
Looping
3. Abstract Data Types & Recursion
3.1
Basic Data Structure
3.2
Characteristics of Recursion Functions
4. Searching & Sorting Techniques
4.1
Bubble Sort
4.2
Selection Sort
4.3
Insertion Sort
4.4
Merge Sort
4.5
Radix Sort
4.6
Quick Sort
4.7
Binary Sort
4.8
Internal & External Sorting

Biyani's Think Tank

5. Arrays
5.1
Storage Allocation Functions
5.2
Hashed Allocation Techniques
5.3
Linked Allocation Techniques

28-31

6. String Manipulations
6.1
String Manipulations
6.2
Representations of Strings

32-33

7. Data Structures & File Handling


7.1
Text of Binary Files
7.2
Opening & Closing Files

34-36

8. Advanced Programming Concepts


8.1
Operating System Cells
8.2
Dynamic Memory Management
8.3
Inner Process Communication
8.4
Indexing

37-47

9. First Order Predicate Calculus


9.1
Introduction to Formal Logic
9.2
Propositional Logic
9.3
Conditional Propositions
9.4
Proofs
9.5
Resolution Proofs
9.6
Rules of Inference Program

48-62

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

CHAPTER-1

Algorithmic Methodology
Q.1

What are the various steps to plan Algorithm ?

Ans.: Following steps must be followed to plan any algorithm :


(1)

Device Algorithm : Creating an algorithm is an art in which may never be


fully automated. When we get the problem, we should first analyse the
given problem clearly and then write down some steps on the paper.

(2)

Validate Algorithm : Once an algorithm is devised , it is necessary to


show that it computes the correct answer for all possible legal inputs .
This process is known as algorithm validation. The algorithm need not as
yet be expressed as a program. It is sufficient to state it in any precise way.
The purpose of validation is to assure us that this algorithm will work
correctly independently of the issues concerning the programming
language it will eventually be written in. Once the validity of the method
has been shown, a program can be written and a second phase begins.
This phase is referred to as program proving or program verification.

(3)

Analyse Algorithm : As an algorithm is executed , it uses the computers


central processing unit to perform operations and its memory ( both
immediate and auxiliary) to hold the program and data. Analysis of
algorithm or performance analysis refers to the task of determining how
much computing time and storage an algorithm requires. An important
result of this study is that it allows you to make quantitative judgments
about the value of one algorithm over another. Another result is that it
allows you to predict whether the software will meet any efficiency
constraints that exist. Analysis can be made by taking into consideration.

(4)

Test A Program : Testing a program consists of 2 phases : debugging and


performance management. Debugging is the process of executing
programs on sample data sets to determine whether results are incorrect if
so corrects them. Performance management is the process of executing a
correct program on data sets and measuring the time and space it takes to
compute the results. These timing figures are useful in that they may

Biyani's Think Tank


confirm a previously done analysis and point out logical places to perform
useful optimization.

Q.2

What is Pseudocode? What are its benefits?

Ans.: An outline of a program, written in a form that can easily be converted into real
programming statements.
Some examples of pseudocode are :
1.

If student's grade is greater than or equal to 60


Print "passed"
else
Print "failed"

2.

Set total to zero


Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.
Print 'no grades were entered'

3.

The pseudocode for a bubble sort might be written :


while not at end of list
compare adjacent elements
if second is greater than first
switch them
get next two elements
if elements were switched
repeat for entire list

Pseudocode cannot be compiled nor executed, and there are no real formatting
or syntax rules. It is simply one step - an important one - in producing the final
code. The benefit of pseudocode is that it enables the programmer to concentrate

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

on the algorithms without worrying about all the syntactic details of a particular
programming language. In fact, you can write pseudocode without even
knowing what programming language you will use for the final implementation.
Q.3

What is Flowchart? What are various symbols of Flowchart?

Ans.: A flowchart is a diagrammatic representation that illustrates the sequence of


operations to be performed to get the solution of a problem. Flowcharts are
generally drawn in the early stages of formulating computer solutions.
Flowcharts facilitate communication between programmers and business people.
These flowcharts play a vital role in the programming of a problem and are quite
helpful in understanding the logic of complicated and lengthy problems. Once
the flowchart is drawn, it becomes easy to write the program in any high level
language. Often we see how flowcharts are helpful in explaining the program to
others. Hence, it is correct to say that a flowchart is a must for the better
documentation of a complex program.
Example of a simple flowchart: a flowchart to find the sum of first 50 natural
numbers.

10

Biyani's Think Tank

Various symbols used in flowchart are :


Flowcharts use special shapes to represent different types of actions or steps in a
process. Lines and arrows show the sequence of the steps, and the relationships
among them.
Start/End : The terminator symbol marks the starting or ending
point of the system. It usually contains the word "Start" or "End."
Action or Process : A box can represent a single step ("add two cups
of flour"), or and entire sub-process ("make bread") within a larger process.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

11

Document : A printed document or report.


Decision : A decision or branching point. Lines representing
different decisions emerge from different points of the diamond.
Input/Output : Represents material or information entering or
leaving the system, such as customer order (input) or a product (output).
Connector : Indicates that the flow continues where a matching symbol
(containing the same letter) has been placed.
Flow Line : Lines indicate the sequence of steps and the direction of
flow.
Database : Indicates a list of information with a standard structure
that allows for searching and sorting.
Display : Indicates a step that displays information.
Q.4

What are the advantages and disadvantages of using Flowcharts?

Ans.: Advantages of using Flowcharts : The benefits of flowcharts are as follows :


(1)

Communication : Flowcharts are better way of communicating the logic


of a system to all concerned.

(2)

Effective Analysis : With the help of flowchart, problem can be analysed


in more effective way.

(3)

Proper Documentation : Program flowcharts serve as a good program


documentation, which is needed for various purposes.

(4)

Efficient Coding : The flowcharts act as a guide or blueprint during the


systems analysis and program development phase.

(5)

Proper Debugging : The flowchart helps in debugging process.

12

Biyani's Think Tank


(6)

Efficient Program Maintenance : The maintenance of operating program


becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part

Limitations of using Flowcharts :

Q.5

(1)

Complex Logic : Sometimes, the program logic is quite complicated. In


that case, flowchart becomes complex and clumsy.

(2)

Alterations and Modifications : If alterations are required the flowchart


may require re-drawing completely.

(3)

Reproduction : As the flowchart symbols cannot be typed, reproduction


of flowchart becomes a problem.

(4)

The essentials of what is done can easily be lost in the technical details of
how it is done.

What is Time Complexity & Space Complexity measures of Algorithm?

Ans.: The time complexity of a problem is the number of steps that it takes to solve an
instance of the problem as a function of the size of the input (usually measured in
bits), using the most efficient algorithm. To understand this intuitively, consider
the example of an instance that is n bits long that can be solved in n steps. In this
example we say the problem has a time complexity of n. Of course, the exact
number of steps will depend on exactly what machine or language is being used.
To avoid that problem, the Big O notation is generally used (sometimes
described as the "order" of the calculation, as in "on the order of"). If a problem
has time complexity O(n) on one typical computer, then it will also have
complexity O(n) on most other computers, so this notation allows us to
generalize away from the details of a particular computer.
Example : Mowing grass has linear time complexity because it takes double the
time to mow double the area. However, looking up something in a dictionary has
only logarithmic time complexity because a double sized dictionary only has to
be opened one time more (i.e. exactly in the middle, then the problem size is
reduced by half).
The space complexity of a problem is a related concept, that measures the
amount of space, or memory required by the algorithm. An informal analogy
would be the amount of scratch paper needed while working out a problem with
pen and paper. Space complexity is also measured with Big O notation.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

13

CHAPTER-2
C

Conditionals & Looping


Q.1

What is Control Structures?


Ans.: A program is usually not limited to a linear sequence of instructions.
During its process it may bifurcate, repeat code or take decisions. For that
purpose, C++ provides control structures that serve to specify what has to be
done by our program, when and under which circumstances.
With the introduction of control structures we are going to have to introduce a
new concept: the compound-statement or block. A block is a group of statements
which are separated by semicolons (;) like all C++ statements, but grouped
together in a block enclosed in braces: { }:
{ statement1; statement2; statement3; }
Most of the control structures that we will see in this section require a generic
statement as part of its syntax. A statement can be either a simple statement (a
simple instruction ending with a semicolon) or a compound statement (several
instructions grouped in a block), like the one just described. In the case that we
want the statement to be a simple statement, we do not need to enclose it in
braces ({}). But in the case that we want the statement to be a compound
statement it must be enclosed between braces ({}), forming a block.
Conditional structure : if and else
The if keyword is used to execute a statement or block only if a condition is
fulfilled. Its form is :
if (condition) statement
Where condition is the expression that is being evaluated. If this condition is
true, statement is executed. If it is false, statement is ignored (not executed) and
the program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored
in the x variable is indeed 100:

14

Biyani's Think Tank

if (x == 100)
cout << "x is 100";
If we want more than a single statement to be executed in case that the condition
is true we can specify a block using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
We can additionally specify what we want to happen if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and
only if not- it prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a
range of values. The following example shows its use telling if the value
currently stored in x is positive, negative or none of them (i.e. zero):

if (x > 0)
cout << "x is positive";
else if (x < 0)

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

15

cout << "x is negative";


else
cout << "x is 0";

Q.2

What are the different types of Loops?

Ans.: Iteration Structures (Loops) : Loops have as purpose to repeat a statement a


certain number of times or while a condition is fulfilled.
The while loop
Its format is :
while (expression) statement
and its functionality is simply to repeat statement while the condition set in
expression is true. For example, we are going to make a program to countdown
using a while-loop:
The do-while loop
Its format is :
do statement while (condition);
The for loop
Its format is :
for (initialization; condition; increase) statement;

16

Biyani's Think Tank

CHAPTER-3
C

Abstract Data Types & Recursion


Q.1

What is Abstract Data Structure ? Give some examples.

Ans.: An abstract data structure is an abstract storage for data defined in terms of the
set of operations to be performed on data and computational complexity for
performing these operations, regardless of the implementation in a concrete data
structure.
Selection of an abstract data structure is crucial in the design of efficient
algorithms and in estimating their computational complexity, while selection of
concrete data structures is important for efficient implementation of algorithms.
Abstract data types (ADT) typically implemented in programming languages (or
their libraries) include :
Complex Number
List
Priority Queue
Queue
Stack
String
Tree
Q.2

What is Recursion? Explain with example?

Ans.: Recursion, in mathematics and computer science, is a method of defining


functions in which the function being defined is applied within its own
definition. The term is also used more generally to describe a process of

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

17

repeating objects in a self-similar way. For instance, when the surfaces of two
mirrors are almost parallel with each other the nested images that occur are a
form of recursion.
It is a way of thinking about and solving problems. It is, in fact, one of the central
ideas of computer science. [1] Solving a problem using recursion means the
solution depends on solutions to smaller instances of the same problem. [2]
Factorial : A classic example of a recursive procedure is the function used to
calculate the factorial of an integer.
Function Definition : A recurrence relation is an equation that relates later terms
in the sequence to earlier terms[6].
Recurrence relation for factorial:
bn = n * bn-1
b0 = 1
Computing the recurrence relation for n = 4:
b4

= 4 * b3
= 4 * 3 * b2
= 4 * 3 * 2 * b1
= 4 * 3 * 2 * 1 * b0
=4*3*2*1*1
=4*3*2*1
=4*3*2
=4*6
=4*6
= 24

18

Biyani's Think Tank

CHAPTER-4
C

Searching & Sorting Techniques


Q.1

Explain the concept of Bubble Sort along with Algorithm.

Ans.: Bubble sort is a simple sorting algorithm. It works by repeatedly stepping


through the list to be sorted, comparing two items at a time and swapping them
if they are in the wrong order. The pass through the list is repeated until no
swaps are needed, which indicates that the list is sorted. The algorithm gets its
name from the way smaller elements "bubble" to the top of the list. Because it
only uses comparisons to operate on elements, it is a comparison sort.
Step-by-Step Example : Let us take the array of numbers "5 1 4 2 8", and sort the
array from lowest number to greatest number using bubble sort algorithm. In
each step, elements written in bold are being compared.
First Pass :
( 5 1 4 2 8 ) ( 1 5 4 2 8 ) Here, algorithm compares the first two elements,
and swaps them.
(15428)(14528)
(14528)(14258)
( 1 4 2 5 8 ) ( 1 4 2 5 8 ) Now, since these elements are already in order,
algorithm does not swap them.
Second Pass :
(14258)(14258)
(14258)(12458)
(12458)(12458)
(12458)(12458)
Now, the array is already sorted, but our algorithm does not know if it is
completed.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

19

Algorithm needs one whole pass without any swap to know it is sorted.
Third Pass :
(12458)(12458)
(12458)(12458)
(12458)(12458)
(12458)(12458)
Finally, the array is sorted, and the algorithm can terminate.
procedure bubbleSort( A : list of sortable items ) defined as:
for each i in 1 to length(A) do:
for each j in length(A) downto i + 1 do:
if A[ j -1 ] > A[ j ] then
swap( A[ j - 1], A[ j ] )
end if
end for
end for
end procedure
Q.2

Explain the concept of Selection Sort along with Algorithm.

Ans.: The algorithm works as follows :


(1)

Find the minimum value in the list.

(2)

Swap it with the value in the first position.

(3)

Repeat the steps above for remainder of the list (starting at the second
position).

Effectively, we divide the list into two parts: the sublist of items already sorted,
which we build up from left to right and is found at the beginning, and the
sublist of items remaining to be sorted, occupying the remainder of the array.
Here is an example of this sort algorithm sorting five elements :
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64

20

Biyani's Think Tank


11 12 22 25 64
Selection sort can also be used on list structures that make add and remove
efficient, such as a linked list. In this case it's more common to remove the
minimum element from the remainder of the list, and then insert it at the end of
the values sorted so far. For example :
64 25 12 22 11
11 64 25 12 22
11 12 64 25 22
11 12 22 64 25
11 12 22 25 64
Pseudo-code :
A is the set of elements to sort, n is the number of elements in A (the array starts
at index 0)
for i 0 to n-2 do
min i
for j (i + 1) to n-1 do
if A[j] < A[min]
min j
swap A[i] and A[min]

Q.3

Explain the Algorithm of Insertion Sort?

Ans.: Insertion sort is a simple sorting algorithm, a comparison sort in which the
sorted array (or list) is built one entry at a time. It is much less efficient on large
lists than more advanced algorithms such as quick sort, heap sort, or merge sort,
but it has various advantages :
(1)

Simple to implement.

(2)

Efficient on (quite) small data sets.

(3)

Efficient on data sets which are already substantially sorted: it runs in O(n
+ d) time, where d is the number of inversions.

(4)

stable(does not change the relative order of elements with equal keys)

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

21

(5)

In- place (only requires a constant amount O(1) of extra memory space)

(6)

It is an online algorithm , in that it can sort a list as it receives it.

A simple procedure for Insertion Sort is :


insertionSort(array A)
for i = 1 to length[A]-1 do
begin
value = A[i]
j = i-1
while j >= 0 and A[j] > value do
begin
A[j + 1] = A[j]
j = j-1
end
A[j+1] = value
end
Q.4

Explain the Merge Sort?

Ans.: Conceptually, a Merge Sort works as follows :


If the list is of length 0 or 1, then it is sorted. Otherwise;
Divide the unsorted list into two sublists of about half the size;
Sort each sublist recursively by re-applying merge sort;
Merge the two sublists back into one sorted list.
In a simple pseudocode form, the algorithm could look something like this:
function mergesort(m)
var list left, right, result
if length(m) 1
return m
var middle = length(m) / 2
for each x in m up to middle
add x to left

22

Biyani's Think Tank


for each x in m after middle
add x to right
left = mergesort(left)
right = mergesort(right)
result = merge(left, right)
return result

Q.5

Explain the Radix Sort?

Ans.: In computer science, radix sort is a sorting algorithm that sorts integers by
processing individual digits. Because integers can represent strings of characters
(e.g., names or dates) and specially formatted floating point numbers, radix sort
is not limited to integers.
Most digital computers internally represent all of their data as electronic
representations of binary numbers, so processing the digits of integer
representations by groups of binary digit representations is most convenient.
Two classifications of radix sorts are least significant digit (LSD) radix sorts and
most significant digit (MSD) radix sorts. LSD radix sorts process the integer
representations starting from the least significant digit and move towards the
most significant digit. MSD radix sorts work the other way around.
The integer representations that are processed by sorting algorithms are often
called "keys," which can exist all by themselves or be associated with other data.
LSD radix sorts typically use the following sorting order: short keys come before
longer keys, and keys of the same length are sorted lexicographically. This
coincides with the normal order of integer representations, such as the sequence
1, 2, 3, 4, 5, 6, 7, 8, 9, 10. MSD radix sorts use lexicographic order, which is
suitable for sorting strings, such as words, or fixed-length integer
representations. A sequence such as "b, c, d, e, f, g, h, i, j, ba" would be
lexicographically sorted as "b, ba, c, d, e, f, g, h, i, j". If lexicographic ordering is
used to sort variable-length integer representations, then the representations of
the numbers from 1 to 10 would be output as 1, 10, 2, 3, 4, 5, 6, 7, 8, 9, as if the
shorter keys were left-justified and padded on the right with blank characters to
make the shorter keys as long as the longest key for the purpose of determining
sorted order.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

Q.6

23

Explain the Quick Sorting?

Ans.: Quicksort sorts by employing a divide and conquer strategy to divide a list into
two sub-lists.
The steps are :
Pick an element, called a pivot, from the list.
Reorder the list so that all elements which are less than the pivot come
before the pivot and so that all elements greater than the pivot come after
it (equal values can go either way). After this partitioning, the pivot is in
its final position. This is called the partition operation.
Recursively sort the sub-list of lesser elements and the sub-list of greater
elements.
The base case of the recursion are lists of size zero or one, which are always
sorted.
In simple pseudocode, the algorithm might be expressed as:
function quicksort(array)
var list less, greater
if length(array) 1
return array
select a pivot value pivot from array
for each x in array
if x < pivot then append x to less
if x > pivot then append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))
Q.7

Explain the concept of Binary Search?

Ans.: A binary search algorithm (or binary chop) is a technique for finding a
particular value in a sorted list. It makes progressively better guesses, and closes
in on the sought value by selecting the median element in a list, comparing its
value to the target value, and determining if the selected value is greater than,
less than, or equal to the target value. A guess that turns out to be too high
becomes the new top of the list, and a guess that is too low becomes the new
bottom of the list. Pursuing this strategy iteratively, it narrows the search by a
factor of two each time, and finds the target value.

24

Biyani's Think Tank


The algorithm : The most common application of binary search is to find a
specific value in a sorted list. To cast this in the frame of the guessing game (see
Example below), realize that we are now guessing the index, or numbered place,
of the value in the list. This is useful because, given the index, other data
structures will contain associated information. Suppose a data structure
containing the classic collection of name, address, telephone number and so forth
has been accumulated, and an array is prepared containing the names, numbered
from one to N. A query might be: what is the telephone number for a given name
X. To answer this the array would be searched and the index (if any)
corresponding to that name determined, whereupon it would be used to report
the associated telephone number and so forth. Appropriate provision must be
made for the name not being in the list (typically by returning an index value of
zero), indeed the question of interest might be only whether X is in the list or not.
low = 0
high = N
while (low < high) {
mid = (low + high)/2;
if (A[mid] < value)
low = mid + 1;
else
//can't be high = mid-1: here A[mid] >= value,
//so high can't be < mid if A[mid] == value
high = mid;
}
if (low < N) and (A[low] == value)
return low
else
return not_found
This algorithm has two other advantages. At the end of the loop, low points to the
first entry greater than or equal to value, so a new entry can be inserted if no
match is found. Moreover, it only requires one comparison; which could be
significant for complex keys in languages which do not allow the result of a
comparison to be saved.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

Q.8

25

What is Internal & External Sorting techniques?

Ans.: An internal sort is any data sorting process that takes place entirely within the
main memory of a computer. This is possible whenever the data to be sorted is
small enough to all be held in the main memory. For sorting larger datasets, it
may be necessary to hold only a chunk of data in memory at a time, since it wont
all fit. The rest of the data is normally held on some larger, but slower medium,
like a hard-disk. Any reading or writing of data to and from this slower media
can slow the sortation process considerably. This issue has implications for
different sort algorithms.
Consider a Bubblesort, where adjacent records are swapped in order to get them
into the right order, so that records appear to 'bubble' up and down through the
dataspace. If this has to be done in chunks, then when we have sorted all the
records in chunk 1, we move on to chunk 2, but we find that some of the records
in chunk 1 need to 'bubble through' chunk 2, and vice versa (i.e., there are
records in chunk 2 that belong in chunk 1, and records in chunk 1 that belong in
chunk 2 or later chunks). This will cause the chunks to be read and written back
to disk many times as records cross over the boundaries between them, resulting
in a considerable degradation of performance. If the data can all be held in
memory as one large chunk, then this performance hit is avoided.
On the other hand, some algorithms handle external sorting rather better. A
Merge sort breaks the data up into chunks, sorts the chunks by some other
algorithm (maybe bubblesort or Quick sort) and then recombines the chunks two
by two so that each recombined chunk is in order. This approach minimises the
number or reads and writes of data-chunks from disk, and is a popular external
sort method.

26

Biyani's Think Tank

CHAPTER-5
C

Arrays
Q.1

What are the different functions used for Allocation of Memory?

Ans.: Sizeof & Malloc : The sizeof operator returns the size in bytes of its operand.
Whether the result of sizeof is unsigned int or unsigned long is implementation
definedwhich is why the declaration of malloc above ducked the issue by
omitting any parameter information; normally you would use the stdlib.h header
file to declare malloc correctly. Here is the last example done portably :
#include <stdlib.h>

/* declares malloc() */

float *fp;
fp = (float *)malloc(sizeof(float));
The operand of sizeof only has to be parenthesized if it's a type name, as it was in
the example. If you are using the name of a data object instead, then the
parentheses can be omitted, but they rarely are.
#include <stdlib.h>
int *ip, ar[100];
ip = (int *)malloc(sizeof ar);
In the last example, the array ar is an array of 100 ints; after the call to malloc
(assuming that it was successful), ip will point to a region of store that can also
be treated as an array of 100 ints.
The fundamental unit of storage in C is the char, and by definition
sizeof(char)
is equal to 1, so you could allocate space for an array of ten chars with
malloc(10)
while to allocate room for an array of ten ints, you would have to use
malloc(sizeof(int[10]))

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

27

If malloc can't find enough free space to satisfy a request it returns a null pointer
to indicate failure. For historical reasons, the stdio.h header file contains a
defined constant called NULL which is traditionally used to check the return
value from malloc and some other library functions. An explicit 0 or (void *)0
could equally well be used.
Calloc and Realloc : There are two additional memory allocation functions,
Calloc() and Realloc(). Their prototypes are given below:
void *calloc(size_t num_elements, size_t element_size};
void *realloc( void *ptr, size_t new_size);
Malloc does not initialise memory (to zero) in any way. If you wish to initialise
memory then use calloc. Calloc there is slightly more computationally expensive
but, occasionally, more convenient than malloc. Also note the different syntax
between calloc and malloc in that calloc takes the number of desired elements,
num_elements, and element_size, element_size, as two individual arguments.
Thus to assign 100 integer elements that are all initially zero you would do:
int *ip;
ip = (int *) calloc(100, sizeof(int));
Realloc is a function which attempts to change the size of a previous allocated
block of memory. The new size can be larger or smaller. If the block is made
larger then the old contents remain unchanged and memory is added to the end
of the block. If the size is made smaller then the remaining contents are
unchanged.
If the original block size cannot be resized then realloc will attempt to assign a
new block of memory and will copy the old block contents. Note a new pointer
(of different value) will consequently be returned. You must use this new value.
If new memory cannot be reallocated then realloc returns NULL.
Thus to change the size of memory allocated to the *ip pointer above to an array
block of 50 integers instead of 100, simply do:
ip = (int *) calloc( ip, 50);
Q.2

What is Hashing? How is it used for searching?

Ans.: Hashing has a worst-case behavior that is linear for finding a target, but with
some care, hashing can be dramatically fast in the average-case. Hashing also

28

Biyani's Think Tank


makes it easy to add and delete elements from the collection that is being
searched.
Suppose we want to store information about each student in a database, so that
we can later retrieve information about any student simply using his/her student
ID. To be specific, suppose the information about each student is an object of the
following form, with the student ID stored in the key field:
struct Student
{
int key;
long phone;

// the student ID
// phone number

string address; // student address


};
We call each of these objects a record. Of course, there might be other
information in each student record.
If student IDs are all in the range 0..99, we could store the records in an array of
the following type, placing student ID k in location data[k]:
Student data[100]; // array of 100 records
The record for student ID k can be retrieved immediately since we know it is in
data[k].
What, however, if the student IDs do not form a neat range like 0..99. Suppose
that we only know that there will be a hundred or fewer and that they will be
distributed in the range 0..9999. We could then use an array with 10,000
components, but that seems wasteful since only a small fraction of the array will
be used. It appears that we have to store the records in an array with 100
elements and to use a serial search through this array whenever we wish to find
a particular student ID. If we are clever, we can store the records in a relatively
small array and still retrieve students by ID much faster than we could by serial
search.
To illustrate this, suppose that we know that the student IDs will be:
0, 100, 200, ... , 9800, 9900
In this case, we can store the records in an array called data with only 100
components. We'll store the record with student ID k at location:
data[k/100]

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

29

If we want to retrieve information for student ID 700, we compute 700/100 and


obtain the index 7. The record for student ID 700 is stored in array component
data[7].
This general technique is called hashing. Each record requires a unique value
called its key. In our example the student ID is the key, but other, more complex
keys are sometimes used. A function called the hash function, maps keys to array
indices.
Suppose we name our hash function hash. If a record has a key of k, then we will
try to store that record at location data[hash(k)]. Using the hash function to
compute the correct array index is called hashing the key to an array index. The
hash function must be chosen so that its return value is always a valid index for
the array. In our example:
hash(k) = k / 100
Given this hash function and keys that are multiples of 100, every key produces a
different index when it was hashed. Thus, hash is a perfect hash function.
Unfortunately, a perfect hash function cannot always be found.

30

Biyani's Think Tank

CHAPTER-6
C

String Manipulations
Q.1

What are the different String Manipulations?

Ans.: The different string manipulations are :


#include <string.h>
char *stpcpy (char *dest, char *src) - Copy one string into another.
int strcmp(char *string1, char *string2) - Compare string1 and string2 to
determine alphabetic order.
char *strcpy(char *string1, char *string2) - Copy string2 to stringl.
char *strerror(int errnum) - Get error message corresponding to specified error
number.
int strlen(char *string) - Determine the length of a string.
char *strncat(char *string1, char *string2, size_t n) - Append n characters from
string2 to stringl.
int strncmp(char *string1, char *string2, size_t n) - Compare first n characters of
two strings.
char *strncpy(char *string1, char *string2, size_t n) - Copy first n characters of
string2 to stringl .
char *strnset(char *string, int c, size _t n) - Set first n characters of string to c.
char *strrchr(char *string, int c) - Find last occurrence of character c in string
Examples :
1)

main()
{
char arr[]=Colleges;

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

31

int len1,len2;
len1=strlen(arr);
len2=strlen(Girls collge);
printf(String = %s length = %d,arr,len1);
printf(String = %s length = %d,Girls college,len2);
}
2)

main()
{
char source[]=Biyani College;
char target[20];
strcpy(target,source);
printf(String is : %s,target);
}

32

Biyani's Think Tank

CHAPTER-7
C

Data Structures & File Handling


Q.1

What is text file & binary file?

Ans.: A text file (sometimes spelled "textfile") is a kind of computer file that is
structured as a sequence of lines. A text file exists within a computer file system.
The end of a text file is often denoted by placing one or more special characters,
known as an end-of-file marker, after the last line in a text file.
"Text file" refers to a type of container, while plain text refers to a type of content.
Text files can contain plain text, but they are not limited to such.
Because of their simplicity text files are commonly used for storage of
information. They avoid some of the problems encountered with other file
formats, such as endianness, padding bytes, or differences in the number of bytes
in a machine word. Further, when data corruption occurs in a text file, it is often
easier to recover and continue processing the remaining contents. A
disadvantage of text files is that they usually have a low entropy, meaning that
the information occupies more storage than is strictly necessary.
A binary file is a computer file which may contain any type of data, encoded in
binary form for computer storage and processing purposes; for example,
computer document files containing formatted text. Many binary file formats
contain parts that can be interpreted as text; binary files that contain only textual
data - without, for example, any formatting information - are called plain text
files. In many cases, plain text files are considered to be different from binary
files because binary files are made up of more than just plain text. When
downloading, a completely functional program without any installer is also often
called program binary, or binaries (as opposed to the source code).
Binary files are usually thought of as being a sequence of bytes, which means the
binary digits (bits) are grouped in eights. Binary files typically contain bytes that
are intended to be interpreted as something other than text characters. Compiled

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

33

computer programs are typical examples; indeed, compiled applications (object


files) are sometimes referred to, particularly by programmers, as binaries. But
binary files can also contain images, sounds, compressed versions of other files,
etc. in short, any type of file content whatsoever.
Some binary files contain headers, blocks of metadata used by a computer
program to interpret the data in the file. For example, a GIF file can contain
multiple images, and headers are used to identify and describe each block of
image data. If a binary file does not contain any headers, it may be called a flat
binary file.
Q.2 What are the various functions used in C to open & close file?
Ans.: Opening a File : Before we can write to a file, we must open it. What this really
means is that we must tell the system that we want to write to a file and what the
filename is. We do this with the fopen function illustrated in the example
#include "stdio.h"
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
The file pointer, fp in our case, points to the file and two arguments are required
in the parentheses, the filename first, followed by the file type.
The filename is any valid DOS filename, and can be expressed in upper or lower
case letters, or even mixed if you so desire. It is enclosed in double quotes. For
this example we have chosen the name TENLINES.TXT. This file should not exist
on your disk at this time. If you have a file with this name, you should change its
name or move it because when we execute this program, its contents will be

34

Biyani's Think Tank


erased. If you dont have a file by this name, that is good because we will create
one and put some data into it. You are permitted to include a directory with the
filename.The directory must, of course, be a valid directory otherwise an error
will occur. Also, because of the way C handles literal strings, the directory
separation character \ must be written twice. For example, if the file is to be
stored in the \PROJECTS subdirectory then the filename should be entered as
"\\PROJECTS\\TENLINES.TXT"
Closing a File : To close a file you simply use the function fclose with the file
pointer in the parentheses. Actually, in this simple program, it is not necessary to
close the file because the system will close all open files before returning to DOS,
but it is good programming practice for you to close all files in spite of the fact
that they will be closed automatically, because that would act as a reminder to
you of what files are open at the end of each program.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

35

CHAPTER-8
C

Advanced Programming Concepts


Q.1

What is a System Call? What are the various System Calls?

Ans.: A system call is a request made by any arbitrary program to the operating
system for performing tasks -- picked from a predefined set -- which the said
program does not have required permissions to execute in its own flow of
execution. Most operations interacting with the system require permissions not
available to a user level process, i.e. any I/O performed with any arbitrary device
present on the system or any form of communication with other processes
requires the use of system calls.
The fact that improper use of the system can easily cause a system crash
necessitates some level of control. The design of the microprocessor architecture
on practically all modern systems (except some embedded systems) offers a
series of privilege levels -- the (low) privilege level in which normal applications
execute limits the address space of the program so that it cannot access or modify
other running applications nor the operating system itself. It also prevents the
application from using any system devices (e.g. the frame buffer or network
devices). But obviously any normal application needs these abilities; thus it can
call the operating system. The OS executes at the highest level of privilege and
allows the applications to request services via system calls, which are often
implemented through interrupts. If allowed, the system enters a higher privilege
level, executes a specific set of instructions which the interrupting program has
no direct control over, then returns control to the former flow of execution. This
concept also serves as a way to implement security.
With the development of separate operating modes with varying levels of
privilege, a mechanism was needed for transferring control safely from lesser
privileged modes to higher privileged modes. Less privileged code could not
simply transfer control to more privileged code at any arbitrary point and with
any arbitrary processor state. To allow it to do so would allow it to break

36

Biyani's Think Tank


security. For instance, the less privileged code could cause the higher privileged
code to execute in the wrong order, or provide it with a bad stack.
The various System Calls are :
1)

Open : A file is opened or created by calling the open function :


int open (const char *pathname, int oflag, .../*,mode_t mode */);
The value returned is the new file descriptor . This integer is usually an
index on a table of open files for the process. The operating system keeps
independent tables for different processes. The file descriptor contains,
among other things, a position pointer that indicates which place of the
file will be acted upon by further file operations.
Alternatively, open can return a negative number indicating that the open
operation failed.
The pathname argument is the name of the file to open. It is a file path
indicating in which place of the file system the file should be found (or
created if that is requested)
There are a multiple options for this function, which are specified by the
oflag argument.
This argument formed by OR'ing together one or more of the following
constants (from <fcntl.h>)
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing.
Optionally, you can also use the following parameters (the following list is
not exhaustive, it intends to show what kind of options can be used with
open) :
O_APPEND
When using this flag, all data written will be appended to the end
of the file. The file operations will ignore the position pointer inside the
file descriptor and always append at the end of the file, even when other
processes are also accessing the file.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

37

O_CREAT
This flag will make open to create the file if it does not exist, or
overwrite an existing one.
O_EXCL
When this flag is used with O_CREAT, it avoids the overwriting
behaviour.
O_NONBLOCK
Operations on the file descriptor will return control to the process
immediately instead of waiting to finish.
the mode_t argument is optional, and is relevant only when creating a new
file. It indicates the file permissions for the newly created file.
2)

Wait : In modern computer operating system, a process(or task) may wait


on another process to complete its execution. In most systems, a parent
process can create an independently executing child process. The parent
process may then issue a wait system call , which suspends the execution of
the parent process while the child executes. When the child process
terminates, it returns an exit status to the operating system, which is then
returned to the waiting parent process. The parent process then resumes
execution.

3)

Exec : The exec functions of Unix-like operating systems are a collection of


functions that causes the running process to be completely replaced by the
program passed as argument to the function. As a new process is not
created, the process ID (PID) does not change across and execute, but the
data, heap and stack of the calling process are replaced by those of the
new process.
In the execl, execlp, execv, and execvp calls, the child process inherits the
parent's environment.
Files open when an exec call is made remain open in the new process. All
open files must be flushed before an exec call. The exec calls do not
preserve the translation modes of open files. If the child process uses files
inherited from the parent, setmode function can be called to set the
translation mode to the desired mode.

4)

Fork : In computing, when a process forks, it creates a copy of itself,


which is called a "child process." The original process is then called the
"parent process". More generally, a fork in a multithreading environment

38

Biyani's Think Tank


means that a thread of execution is duplicated, creating a child thread
from the parent thread.
Under Unix and Unix-like operating systems, the parent and the child
operations are selected by examining the return value of the fork() system
call. In the child process, the return value of fork() is 0, whereas the return
value in the parent process is the PID of the newly-created child process.

Q.2

5)

Exit : A computer process terminates its execution by making an exit


system call. More generally, an exit in a multithreading environment
means that a thread of execution has stopped running. The operating
system reclaims resources (memory, files, etc.) that were used by the
process. The process is said to be a dead process after it terminates.

6)

Kill : Kill is a command used to send simple messages to processes


running on the system. By default, the message sent is the "termination"
signal, which requests that the process exit. But kill is something of a
misnomer; the signal sent may have nothing to do with process killing.
The kill command is a wrapper around the kill() system call, which sends
signals to processes or process groups on the system, referenced by their
numeric process IDs (PIDs) or process group IDs (PGIDs). kill is always
provided as a standalone utility, but most shells have built-in kill
commands that may slightly differ from it.

What is Inter-Process Communication?

Ans.: Inter-Process Communication (IPC) is a set of techniques for the exchange of


data among two or more threads in one or more processes . Processes may be
running on one or more computers connected by a network. IPC techniques are
divided into methods for message passing , synchronization , shared memory
and remote procedure calls (RPC). The method of IPC used may vary based on
the bandwidth and latency of communication between the threads and the type
of data being communicated.
IPC may also be referred to as inter-thread communication and inter-application
communication.
Typically, applications can use IPC categorized as clients or servers. A client is an
application or a process that requests a service from some other application or
process. A server is an application or a process that responds to a client request.
Many applications act as both a client and a server, depending on the situation.
For example, a word processing application might act as a client in requesting a
summary table of manufacturing costs from a spreadsheet application acting as a

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

39

server. The spreadsheet application, in turn, might act as a client in requesting


the latest inventory levels from an automated inventory control application.
After you decide that your application would benefit from IPC, you must decide
which of the available IPC methods to use. It is likely that an application will use
several IPC mechanisms. The answers to these questions determine whether an
application can benefit by using one or more IPC mechanisms.
Should the application be able to communicate with other applications
running on other computers on a network, or is it sufficient for the
application to communicate only with applications on the local computer?
Should the application be able to communicate with applications running
on other computers that may be running under different operating
systems (such as 16-bit Windows or UNIX)?
Should the user of the application have to choose the other applications
with which the application communicates, or can the application
implicitly find its cooperating partners?
Should the application communicate with many different applications in a
general way, such as allowing cut-and-paste operations with any other
application, or should its communications requirements be limited to a
restricted set of interactions with specific other applications?
Is performance a critical aspect of the application? All IPC mechanisms
include some amount of overhead.
Should the application be a GUI application or a console application?
Some IPC mechanisms require a GUI application.
The following IPC mechanisms are supported by Windows :
Clipboard
COM
Data Copy
DDE
File Mapping
Mailslots
Pipes
RPC
Windows Sockets

40

Biyani's Think Tank


Using the Clipboard for IPC : The clipboard acts as a central depository for data
sharing among applications. When a user performs a cut or copy operation in an
application, the application puts the selected data on the clipboard in one or
more standard or application-defined formats. Any other application can then
retrieve the data from the clipboard, choosing from the available formats that it
understands. The clipboard is a very loosely coupled exchange medium, where
applications need only agree on the data format. The applications can reside on
the same computer or on different computers on a network.
Using COM for IPC : Applications that use OLE manage compound documents
that is, documents made up of data from a variety of different applications. OLE
provides services that make it easy for applications to call on other applications
for data editing. For example, a word processor that uses OLE could embed a
graph from a spreadsheet. The user could start the spreadsheet automatically
from within the word processor by choosing the embedded chart for editing.
OLE takes care of starting the spreadsheet and presenting the graph for editing.
When the user quit the spreadsheet, the graph would be updated in the original
word processor document. The spreadsheet appears to be an extension of the
word processor.
Using Data Copy for IPC : Data copy enables an application to send information
to another application using the WM_COPYDATA message. This method
requires cooperation between the sending application and the receiving
application. The receiving application must know the format of the information
and be able to identify the sender. The sending application cannot modify the
memory referenced by any pointers.
Using DDE for IPC : DDE is a protocol that enables applications to exchange
data in a variety of formats. Applications can use DDE for one-time data
exchanges or for ongoing exchanges in which the applications update one
another as new data becomes available.
The data formats used by DDE are the same as those used by the clipboard. DDE
can be thought of as an extension of the clipboard mechanism. The clipboard is
almost always used for a one-time response to a user command, such as choosing
the Paste command from a menu. DDE is also usually initiated by a user
command, but it often continues to function without further user interaction.
You can also define custom DDE data formats for special-purpose IPC between
applications with more tightly coupled communications requirements.
DDE exchanges can occur between applications running on the same computer
or on different computers on a network.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

41

Using a File Mapping for IPC : File mapping enables a process to treat the
contents of a file as if they were a block of memory in the process's address
space. The process can use simple pointer operations to examine and modify the
contents of the file. When two or more processes access the same file mapping,
each process receives a pointer to memory in its own address space that it can
use to read or modify the contents of the file. The processes must use a
synchronization object, such as a semaphore, to prevent data corruption in a
multitasking environment.
You can use a special case of file mapping to provide named shared memory
between processes. If you specify the system swapping file when creating a filemapping object, the file-mapping object is treated as a shared memory block.
Other processes can access the same block of memory by opening the same filemapping object.
File mapping is quite efficient and also provides operating-systemsupported
security attributes that can help prevent unauthorized data corruption. File
mapping can be used only between processes on a local computer; it cannot be
used over a network.
Using a Mailslot for IPC : Mailslots provide one-way communication. Any
process that creates a mailslot is a mailslot server. Other processes, called mailslot
clients, send messages to the mailslot server by writing a message to its mailslot.
Incoming messages are always appended to the mailslot. The mailslot saves the
messages until the mailslot server has read them. A process can be both a
mailslot server and a mailslot client, so two-way communication is possible
using multiple mailslots.
A mailslot client can send a message to a mailslot on its local computer, to a
mailslot on another computer, or to all mailslots with the same name on all
computers in a specified network domain. Messages broadcast to all mailslots on
a domain can be no longer than 400 bytes, whereas messages sent to a single
mailslot are limited only by the maximum message size specified by the mailslot
server when it created the mailslot.
Using Pipes for IPC : There are two types of pipes for two-way communication:
anonymous pipes and named pipes. Anonymous pipes enable related processes to
transfer information to each other. Typically, an anonymous pipe is used for
redirecting the standard input or output of a child process so that it can exchange
data with its parent process. To exchange data in both directions (duplex
operation), you must create two anonymous pipes. The parent process writes
data to one pipe using its write handle, while the child process reads the data
from that pipe using its read handle. Similarly, the child process writes data to

42

Biyani's Think Tank


the other pipe and the parent process reads from it. Anonymous pipes cannot be
used over a network, nor can they be used between unrelated processes.
Named pipes are used to transfer data between processes that are not related
processes and between processes on different computers. Typically, a namedpipe server process creates a named pipe with a well-known name or a name
that is to be communicated to its clients. A named-pipe client process that knows
the name of the pipe can open its other end, subject to access restrictions
specified by named-pipe server process. After both the server and client have
connected to the pipe, they can exchange data by performing read and write
operations on the pipe.
Using RPC for IPC : RPC enables applications to call functions remotely.
Therefore, RPC makes IPC as easy as calling a function. RPC operates between
processes on a single computer or on different computers on a network.
The RPC provided by Windows is compliant with the Open Software
Foundation (OSF) Distributed Computing Environment (DCE). This means that
applications that use RPC are able to communicate with applications running
with other operating systems that support DCE. RPC automatically supports
data conversion to account for different hardware architectures and for byteordering between dissimilar environments.
RPC clients and servers are tightly coupled but still maintain high performance.
The system makes extensive use of RPC to facilitate a client/server relationship
between different parts of the operating system.
Using Windows Sockets for IPC : Windows Sockets is an protocol-independent
interface. It takes advantage of the communication capabilities of the underlying
protocols. In Windows Sockets 2, a socket handle can optionally be used as a file
handle with the standard file I/O functions.
Windows Sockets are based on the sockets first popularized by Berkeley
Software Distribution (BSD). An application that uses Windows Sockets can
communicate with other socket implementation on other types of systems.
However, not all transport service providers support all available options.

Q.3

What is Indexing? What are the different type of Indexes used in File
Organization?

Ans.: Indexing :

Index File (same idea as textbook index) : auxiliary structure designed to


speed up access to desired data.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

43

Indexing Field : field on which the index file is defined.

Index file stores each value of the index field along with pointer: pointer(s)
to block(s) that contain record(s) with that field value or pointer to the
record with that field value :
<Indexing Field, Pointer>

In oracle, the pointer is called RowID which tells the DBMS where the row
(record) is located (by file, block within that file, and row within the
block).

To find a record in the data file based on a certain selection criterion on an


indexing field, we initially access the index file, which will allow the
access of the record on the data file.

Index file much smaller than the data file => searching will be fast.

Indexing important for file systems and DBMSs :

Databases eventually map data to file structures on disk :

Records of each relation may be stored in a separate file.

Records of several different relations can be stored in the


same file (i.e. physically clustered file organization : to
minimize I/O).

In DBMSs, the query processor accesses the index structures for


processing a query (e.g., indexed join called also single-loop join).

Types of Indexes :

Indexes on ordered vs. unordered files.

Dense vs. non-dense (i.e. sparse) indexes.


-

Dense : An entry in the index file for each record of the data file.

Sparse : only some of the data records are represented in the index,
often one index entry per block of the data file.

Primary indexes vs. secondary indexes.

Ordered Indexes Hash indexes :

Ordered Indexes: indexing fields stored in sorted order.

Hash indexes: indexing fields stored using a hash function.

Single-level vs. multi-level :

44

Biyani's Think Tank

Single-level index is an ordered file and is searched using binary


search.

Multi-level ones are tree-structured that improve the search and


require a more elaborate search algorithm.

Index on a single indexing field Index on multiple indexing fields (i.e.


Composite Index).

If a certain combination of fields is used frequently, set an index on multiple


fields.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

45

CHAPTER-9
C

First Order Predicate Calculus


Q.1
Wh

What is the use of Propositional Logic? What is syntax and semantics of


Propositional Logic?
OR
Why use Propositional Logic?

Ans.:
Specifying logical formulae is often more natural than filling in tables (i.e.,
arbitrary constraints).
It is easier to check and debug formulae than tables.
We can exploit the Boolean nature for efficient reasoning.
We need a language for asking queries that may be more complicated
than asking for the value of one variable.
It is easy to incrementally add formulae.
It can be extended to infinitely many variables (using logical
quantification).
This is a starting point for more complex logics (e.g., first-order logic) that
go beyond CSPs.
Syntax of Predicate Logic : Propositional logic is fairly powerful but we must
add variables and quantification to be able to reason about objects in atoms and
express properties of a set of objects without listing the atom corresponding to
each object.
We shall adopt the Prolog convention that variables have an initial capital letter.
(This is contrary to many Mathematical Logic books where variables are lower
case and constants have an initial capital.)

46

Biyani's Think Tank


When we include variables we must specify their scope or quantification. The
first quantifier we want is the universal quantifier (for all).
X.loves(misspiggy, X)
This allows X to range over all the objects and asserts that Miss Piggy loves each
of them. We have introduced one variable but any number is allowed
XY.loves(X, Y)
Each of the objects love all of the objects, even itself! Therefore XY. is the same
as X. Y. Quantifiers, like connectives, act on sentences. So if Miss Piggy loves
all cute things (not just Kermit!) we would write
C.[cute(C) -> loves(misspiggy, C)]
rather than
loves(misspiggy,

C.cute(C))

because the second argument to loves must be an object, not a sentence.


When the world contains a finite set of objects then a universally quantified
sentence can be converted into a sentence without the quantifier; e.g.
X.loves(misspiggy, X) becomes
loves(misspiggy, misspiggy)
loves(misspiggy, animal)

loves(misspiggy, kermit)

...

Contrast this with the infinite set of positive integers and the sentence
N.[odd(N)

even(N)]

The other quantifier is the existential quantifier

(there exists).

X.loves(misspiggy, X)
This allows X to range over all the objects and asserts that Miss Piggy loves (at
least) one of them. Similarly
XY.loves(X, Y)
asserts that there is at least one loving couple (or self-loving object).
Note: We shall be using First Order Predicate Logic where quantified variables
range over object constants only. We are defining Second Order Predicate Logic
if we allow quantified variables to range over functions or predicates as well; e.g.
X.loves(misspiggy,
voiceof(kermit))

X(kermit))

includes

loves(misspiggy,

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

47

X.X(misspiggy, kermit) (there exists some relationship linking Miss


Piggy and Kermit!)
Semantics of First Order Predicate Logic
Now we must deal with quantification.
:
holds in a model iff

holds for all objects

in our domain.

:
holds in a model iff there is some object

in our domain so that

holds.
Example: Available Objects affects Quantification
If misspiggy is the only object in our domain then
ugly(misspiggy)
X.ugly(X)

beautiful(misspiggy) is equivalent to
beautiful(X)

If there were other objects then there would be more atoms and so the set of
models would be larger; e.g. with objects misspiggy and kermit the possible
models are all combinations of the atoms ugly(misspiggy), beautiful(misspiggy)
ugly(kermit), beautiful(kermit). Now the 2 sentences are no longer equivalent.
1.

Although, every model in which


X.ugly(X)
beautiful(X) holds,
ugly(misspiggy)
beautiful(misspiggy) also holds

2.

there are models in which ugly(misspiggy)


beautiful(misspiggy)
holds,
but X.ugly(X)
beautiful(X) does not hold; e.g.
M = {ugly(kermit), beautiful(kermit)}.
What about M = {ugly(misspiggy)}, beautiful(misspiggy)?

Q.2

Explain the Conditional Propositional in brief?

Ans.: Conditional Propositions : A proposition of the form if p then q or p implies


q, represented p ! q is called a conditional proposition. For instance: if John is

48

Biyani's Think Tank


from Chicago then John is from Illinois. The proposition p is called hypothesis or
antecedent, and the proposition q is the conclusion or consequent. Note that p ! q is
true always except when p is true and q is false. So, the following sentences are
true: if 2 < 4 then Paris is in France (true ! true), if London is in Denmark then
2 < 4 (false ! true), if 4 = 7 then London is in Denmark (false ! false). However
the following one is false: if 2 < 4 then London is in Denmark (true ! false). In
might seem strange that p ! q is considered true when p is false, regardless of
the truth value of q. This will become clearer when we study predicates such as if
x is a multiple of 4 then x is a multiple of 2. That implication is obviously true,
although for the particular case x = 3 it becomes if 3 is a multiple of 4 then 3 is a
multiple of 2. The proposition p $ q, read p if and only if q, is called
biconditional.
It is true precisely when p and q have the same truth value, i.e., they are both true
or both false.
The Biconditional: p if and only if q May be written as p q.
The bi-conditional is defined by the following truth table:
P

p q

Defn: A compound proposition P is called logically equivalent to another


compound
proposition Q if P and Q have the same truth value. We write P Q.
DeMorgans Laws :

Q.3

(1)

( pq ) p q

(2)

( pq ) p q

Explain Formal Logic in Artificial Intelligence ?

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

49

Ans.: Formal Logic : Formal logic is a set of rules for making deductions that seem self
evident. Syllogisms like the following occur in every day conversation.
All humans are mortal.
Socrates is a human.
Therefore Socrates is mortal.
Mathematical logic formalizes such deductions with rules precise enough to
program a computer to decide if an argument is valid.
This is facilitated by representing objects and relationships symbolically. For
example we might use for the set of humans,
for the set of mortal creatures
and
object

for Socrates. We use the symbolic expression `


is a member of set

' to indicate that

. Thus we represent `Socrates is a human' with

. We use the `quantifier'


to indicate that all objects satisfy some
condition. For example all men are mortal can be written as
. This reads that every that has the property of being
human must also have the property of being mortal. Then we restate the
syllogism as follows.
Logic assumes something cannot be both true and not true. It looks only at the
truth value of a proposition. It involves simple relationships between these truth
values. These can be represented by truth tables as shown in Table 3.1. The only
logical operations required are the three in this figure.
Others such as implication represented by `
three.
and

is the same as
are true or is false.

' can be constructed from these


implies

requires that either both

Determining the truth of a logical expression that contains no quantifiers (like )


is a straightforward application of simple rules. One can use a truth table to
evaluate each subexpression starting with those at the root of the expression tree
as shown in Table 3.2. If a logical expression contains quantifiers than we need to
evaluate a logical relationship over a range of values to determine the truth of the
expression. If the range is infinite then there is no general way to evaluate the

50

Biyani's Think Tank


expression. We can use induction3.2to prove that some statements hold for all
integers but for that we need to go beyond logic to mathematics.
Table 3.1: Truth tables for AND, OR and NOT
AND
AAB

false
false
false
false
true
false
true
false
false
true
true
true
OR
AAB

false
false
false
false
true
true
true
false
true
true
true
true
NOT A
false
true
true
false
Table 3.2: Evaluating a logical expression
symbolA B CDE F
truth value
true
true
false
true
true
false

expression evaluation

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

false

51

true

false

false

false

true

true

The order in which the logical operations are done is important. The rules for this
are called precedence. First do NOT then AND finally OR. If the NOT sign
extends over a subexpression, the subexpression is evaluated and the NOT
operation is applied to that result. In this example at the first level we can
evaluate
and
. At subsequent levels the part of the expression
evaluated at higher levels in in smaller type.
Q.4

What are the different proofs that are already existed in Artificial Intelligence?

Ans.: "Existence Proofs" of Artificial Intelligence :


(i)

Low-Level Appearances and Attributions : The doings of many machines


some much simpler than computers inspire us to describe them in
mental terms commonly reserved for animals. Some missiles, for instance,
seek heat, or so we say. We call them heat seeking missiles and nobody
takes it amiss. Room thermostats monitor room temperatures and try to
keep them within set ranges by turning the furnace on and off; and if you
hold dry ice next to its sensor, it will take the room temperature to be
colder than it is, and mistakenly turn on the furnace (see McCarthy 1979).
Seeking, monitoring, trying, and taking things to be the case seem to be
mental processes or conditions, marked by their intentionality. Just as
humans have low-level mental qualities such as seeking and detecting
things in common with the lower animals, so too do computers seem to
share such low-level qualities with simpler devices. Our working
characterizations of computers are rife with low-level mental attributions:
we say they detect key presses, try to initialize their printers, search for
available devices, and so forth. Even those who would deny the
proposition machines think when it is explicitly put to them, are moved
unavoidably in their practical dealings to characterize the doings of
computers in mental terms, and they would be hard put to do otherwise.

52

Biyani's Think Tank


In this sense, Turings prediction that at the end of the century the use of
words and general educated opinion will have altered so much that one
will be able to speak of machines thinking without expecting to be
contradicted (Turing 1950) has been as mightily fulfilled as his prediction
of a modicum of machine success at playing the Imitation Game has been
confuted. The Turing test and AI as classically conceived, however, are
more concerned with high-level appearances such as the following.
(ii)

Theorem Proving and Mathematical Discovery : Theorem proving and


mathematical exploration being their home turf, computers have
displayed not only human-level but, in certain respects, superhuman
abilities here. For speed and accuracy of mathematical calculation, no
human can match the speed and accuracy of a computer. As for high level
mathematical performances, such as theorem proving and mathematical
discovery, a beginning was made by A. Newell, J.C. Shaw, and H. Simons
(1957) Logic Theorist program which proved 38 of the first 51 theorems
of B. Russell and A.N. Whiteheads Principia Mathematica. Newell and
Simons General Problem Solver (GPS) extended similar automated
theorem proving techniques outside the narrow confines of pure logic and
mathematics. Today such techniques enjoy widespread application in
expert systems like MYCIN, in logic tutorial software, and in computer
languages such as PROLOG. There are even original mathematical
discoveries owing to computers. Notably, K. Appel, W. Haken, and J.
Koch (1977a, 1977b), and computer, proved that every planar map is four
colorable an important mathematical conjecture that had resisted
unassisted human proof for over a hundred years. Certain computer
generated parts of this proof are too complex to be directly verified
(without computer assistance) by human mathematicians.
Whereas attempts to apply general reasoning to unlimited domains are
hampered by explosive inferential complexity and computers' lack of
common sense, expert systems deal with these problems by restricting
their domains of application (in effect, to microworlds), and crafting
domain-specific inference rules for these limited domains. MYCIN for
instance, applies rules culled from interviews with expert human
diagnosticians to descriptions of patients' presenting symptoms to
diagnose blood-borne bacterial infections. MYCIN displays diagnostic
skills approaching the expert human level, albeit strictly limited to this
specific domain. Fuzzy logic is a formalism for representing imprecise
notions such as most and bald and enabling inferences based on such facts
as that a bald person mostly lacks hair.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

53

(iii)

Game Playing : Game playing engaged the interest of AI researchers


almost from the start. Samuels (1959) checkers (or draughts) program
was notable for incorporating mechanisms enabling it to learn from
experience well enough to eventually to outplay Samuel himself.
Additionally, in setting one version of the program to play against a
slightly altered version, carrying over the settings of the stronger player to
the next generation, and repeating the process enabling stronger and
stronger versions to evolve Samuel pioneered the use of what have come
to be called genetic algorithms and evolutionary computing. Chess
has also inspired notable efforts culminating, in 1997, in the famous
victory of Deep Blue over defending world champion Gary Kasparov in a
widely publicized series of matches (recounted in Hsu 2002). Though
some in AI disparaged Deep Blues reliance on brute force application
of computer power rather than improved search guiding heuristics, we
may still add chess to checkers (where the reigning human-machine
machine champion since 1994 has been CHINOOK, the machine), and
backgammon, as games that computers now play at or above the highest
human levels. Computers also play fair to middling poker, bridge, and Go
though not at the highest human level. Additionally, intelligent agents
or "softbots" are elements or participants in a variety of electronic games.

(iv)

Planning : Planning, in large measure, is what puts the intellect in


intellectual games like chess and checkers. To automate this broader
intellectual ability was the intent of Newell and Simons General Problem
Solver (GPS) program. GPS was able to solve puzzles like the cannibals
missionaries problem (how to transport three missionaries and three
cannibals across a river in a canoe for two without the missionaries
becoming outnumbered on either shore) by setting up subgoals whose
attainment leads to the attainment of the [final] goal (Newell & Simon
1963: 284). By these methods GPS would generate a tree of subgoals
(Newell & Simon 1963: 286) and seek a path from initial state (for
example, all on the near bank) to final goal (all on the far bank) by
heuristically guided search along a branching tree of available actions
(for example, two cannibals cross, two missionaries cross, one of each
cross, one of either cross, in either direction) until it finds such a path (for
example, two cannibals cross, one returns, two cannibals cross, one
returns, two missionaries cross, ... ), or else finds that there is none. Since
the number of branches increases exponentially as a function of the
number of options available at each step, where paths have many steps
with many options available at each choice point, as in the real world,
combinatorial explosion ensues and an exhaustive brute force search

54

Biyani's Think Tank


becomes computationally intractable; hence, heuristics (fallible rules of
thumb) for identifying and pruning the most unpromising branches in
order to devote increased attention to promising ones are needed. The
widely deployed STRIPS formalism first developed at Stanford for Shakey
the robot in the late sixties (see Nilsson 1984) represents actions as
operations on states, each operation having preconditions (represented by
state descriptions) and effects (represented by state descriptions): for
example, the go(there) operation might have the preconditions at(here) &
path(here,there) and the effect at(there). AI planning techniques are
finding increasing application and even becoming indispensable in a
multitude of complex planning and scheduling tasks including airport
arrivals, departures, and gate assignments; store inventory management;
automated satellite operations; military logistics; and many others.
(v)

Robots : Robots based on sense-model-plan-act (SMPA) approach


pioneered by Shakey, however, have been slow to appear. Despite
operating in a simplified, custom-made experimental environment or
microworld and reliance on the most powerful available offboard
computers, Shakey operated excruciatingly slowly (Brooks 1991b), as
have other SMPA based robots. An ironic revelation of robotics research is
that abilities such as object recognition and obstacle avoidance that
humans share with "lower" animals often prove more difficult to
implement than distinctively human "high level" mathematical and
inferential abilities that come more naturally (so to speak) to computers.
Rodney Brooks alternative behavior-based approach has had success
imparting low-level behavioral aptitudes outside of custom designed
microworlds, but it is hard to see how such an approach could ever scale
up to enable high-level intelligent action (see Behaviorism: Objections &
Discussion: Methodological Complaints). Perhaps hybrid systems can
overcome the limitations of both approaches. On the practical front,
progress is being made: NASA's Mars exploration rovers Spirit and
Opportunity, for instance, featured autonomous navigation abilities. If
space is the "final frontier" the final frontiersmen are apt to be robots.
Meanwhile, Earth robots seem bound to become smarter and more
pervasive.

(vi)

Knowledge Representation (KR) : Knowledge representation embodies


concepts and information in computationally accessible and inferentially
tractable forms. Besides the STRIPS formalism mentioned above, other
important knowledge representation formalisms include AI programming
languages such as PROLOG, and LISP; data structures such as frames,
scripts, and ontologies; and neural networks (see below). The frame

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

55

problem is the problem of reliably updating dynamic systems


parameters in response to changes in other parameters so as to capture
commonsense generalizations: that the colors of things remain unchanged
by their being moved, that their positions remain unchanged by their
being painted, and so forth. More adequate representation of
commonsense knowledge is widely thought to be a major hurdle to
development of the sort of interconnected planning and thought processes
typical of high-level human or "general" intelligence. The CYC project
(Lenat et al. 1986) at Cycorp and MIT's Open Mind project are ongoing
attempts to develop ontologies representing commonsense knowledge
in computer usable forms.
(vii)

Machine Learning (ML) : Learning performance improvement, concept


formation, or information acquisition due to experience underwrites
human common sense, and one may doubt whether any preformed
ontology could ever impart common sense in full human measure.
Besides, whatever the other intellectual abilities a thing might manifest (or
seem to), at however high a level, without learning capacity, it would still
seem to be sadly lacking something crucial to human-level intelligence
and perhaps intelligence of any sort. The possibility of machine learning is
implicit in computer programs' abilities to self-modify and various means
of realizing that ability continue to be developed. Types of machine
learning techniques include decision tree learning, ensemble learning,
current-best-hypothesis learning, explanation-based learning, Inductive
Logic Programming (ILP), Bayesian statistical learning, instance-based
learning, reinforcement learning, and neural networks. Such techniques
have found a number of applications from game programs whose play
improves with experience to data mining (discovering patterns and
regularities in bodies of information).

(viii) Neural Networks and Connectionism : Neural or connectionist networks


composed of simple processors or nodes acting in parallel are designed
to more closely approximate the architecture of the brain than traditional
serial symbol-processing systems. Presumed brain-computations would
seem to be performed in parallel by the activities of myriad brain cells or
neurons. Much as their parallel processing is spread over various, perhaps
widely distributed, nodes, the representation of data in such connectionist
systems is similarly distributed and sub-symbolic (not being couched in
formalisms such as traditional systems' machine codes and ASCII). Adept
at pattern recognition, such networks seem notably capable of forming
concepts on their own based on feedback from experience and exhibit

56

Biyani's Think Tank


several other humanoid cognitive characteristics besides. Whether neural
networks are capable of implementing high-level symbol processing such
as that involved in the generation and comprehension of natural language
has been hotly disputed. Critics (for example, Fodor and Pylyshyn 1988)
argue that neural networks are incapable, in principle, of implementing
syntactic structures adequate for compositional semantics wherein the
meaning of larger expressions (for example, sentences) are built up from
the meanings of constituents (for example, words) such as those natural
language comprehension features. On the other hand, Fodor (1975) has
argued that symbol-processing systems are incapable of concept
acquisition: here the pattern recognition capabilities of networks seem to
be just the ticket. Here, as with robots, perhaps hybrid systems can
overcome the limitations of both the parallel distributed and symbolprocessing approaches.
(ix)

Natural Language Processing (NLP) : Natural language processing has


proven more difficult than might have been anticipated. Languages are
symbol systems and (serial architecture) computers are symbol crunching
machines, each with its own proprietary instruction set (machine code)
into which it translates or compiles instructions couched in high level
programming languages like LISP and C. One of the principle challenges
posed by natural languages is the proper assignment of meaning. Highlevel computer languages express imperatives which the machine
understands" procedurally by translation into its native (and similarly
imperative) machine code: their constructions are basically instructions.
Natural languages, on the other hand, have perhaps principally
declarative functions: their constructions include descriptions whose
understanding seems fundamentally to require rightly relating them to
their referents in the world. Furthermore, high level computer language
instructions have unique machine code compilations (for a given
machine), whereas, the same natural language constructions may bear
different meanings in different linguistic and extralinguistic contexts.
Contrast the child is in the pen and the ink is in the pen where the
first "pen" should be understood to mean a kind of enclosure and the
second "pen" a kind of writing implement. Commonsense, in a word, is
how we know this; but how would a machine know, unless we could
somehow endow machines with commonsense? In more than a word it
would require sophisticated and integrated syntactic, morphological,

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

57

semantic, pragmatic, and discourse processing. While the holy grail of full
natural language understanding remains a distant dream, here as
elsewhere in AI, piecemeal progress is being made and finding
application in grammar checkers; information retrieval and information
extraction systems; natural language interfaces for games, search engines,
and question-answering systems; and even limited machine translation
(MT).
Q.5

What are the various Rules of Inference & Resolution Proofs in the field of
Artificial Intelligence?

Ans.: Rules of Inference :


o

Logic has a traditional notation.

Quantifiers determine when expressions are true.

Logic has a rich vocabulary.

Interpretations tie logic symbols to worlds.

Proofs tie axioms to consequences.

Resolution ss a sound rule of inference.

Resolution Proofs :
o

Resolution proves theorems by refutation.

Using resolution requires axioms to be in clause form.

Proof is exponential.

Resolution requires unification.

Traditional logic is monotonic.

Theorem proving is suitable for certain problems, but not for all problems.

MCQs:

58

Biyani's Think Tank

Set-I

1.

Two main measures for the efficiency of an Algorithm are:


(a)
Processor and Memory
(b)
Complexity and Capacity
(c)
Time and Space
(d)
Data and Space

( )

2.

The time factor when determining the efficiency of an algorithm is measured by:
(a)
Counting microseconds
(b)
Counting the number of key operations
(c)
Counting the number of statement
(d)
Counting the Kilobytes of algorithm
( )

3.

A data structure is a way of:


(a)
arrangement of different data elements
(b)
organizing data with consideration of items stored into it along with their
relationship with each other
(c)
ordering of collected data
(d)
None of the above
( )

4.

The space factor when determining the efficiency of algorithm is measured by:
(a)
Counting the maximum memory needed by the algorithm
(b)
Counting the minimum memory needed by the algorithm
(c)
Counting the average memory needed by the algorithm
(d)
Counting the maximum disk space needed by the algorithm

( )

The de-que process removes data:


(a)
From the front of the queue
(b)
From the bottom of the queue
(c)
Can not be removed
(d)
None of the above

( )

A queue is a :
(a)
Sequential Organization of data
(b)
Listing of data
(c)
Indexing of data
(d)
None of the above

( )

5.

6.

7.

.is a way of grouping things together by placing one thing on top of


another and then removing things one at a time from the top.
(a)
Array
(b)
Stack
(c)
Pointer

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(d)
8.

9.

All of the above

59

( )

The complexity of Binary Search algorithm is:


(a)
O (n)
(b)
(c)
O (n2)
(d)

O (log n)
O (n log n)

( )

The complexity of Bubble Sort algorithm is:


(a)
O (n)
(b)
2
(c)
O (n )
(d)

O (log n)
O (n log n)

( )

10.

Each array declaration need not give, implicitly or explicitly, the information about: (a)
the name of array
(b)
the data type of array
(c)
the first data from the set to be stored
(d)
the index set of the array
( )

11.

Which of the following is not linear data structure?


(a)
Arrays
(b)
Linked lists
(c)
Both of the above
(d)
None of the above

( )

Finding the location of the element with a given value is:


(a)
Traversal
(b)
Search
(c)
Sort
(d)
None of the above

( )

The operation of processing each element in the list is known as:


(a)
Sorting
(b)
Merging
(c)
Inserting
(d)
Traversal

( )

12.

13.

14.

Arrays are best data structures :


(a)
for relatively permanent collections of data
(b)
for the size of the structure and the data in the structure are constantly changing
(c)
for both of above situation
(d)
for none of the above situation
( )

15.

Linked lists are best suited:


(a)
For relatively permanent collections of data
(b)
for the size of the structure and the data in the structure are constantly changing
(c)
for both of above situation
(d)
for none of the above situation
( )

60

16.

Biyani's Think Tank


In tree construction which is the suitable efficient data structure :
(a)
array
(b)
linked lists
(c)
stack
(d)
queue

( )

17.

By a schematics character variable we mean:


(a)
A variable whose length is defined before the program is executed and cannot
change through the program
(b)
A variable whose length may vary during the execution of the program as long as
the length does not exceed a maximum value determined by the program before
the program is executed
(c)
(a) and (b) both
(d)
None of the above
( )

18.

In this STACKS, "PUSH" is the term used to:


(a)
insert an element into a stack
(b)
delete an element from a stack
(c)
modify the existing element of a stack
(d)
None of the above

( )

Maximum number of queues needed to implement the priority queue:


(a)
Three
(b)
Two
(c)
Five
(d)
One

( )

Polish notation refers to the notations in which:


(a)
the operator symbol is placed after its two operands
(b)
the operator symbol is placed before its two operands
(c)
the operator symbol is placed in the middle
(d)
None of the above

( )

A node has .elements.


(a)
None
(c)
Two

( )

19.

20.

21.

(b)
(d)

One
Three

22.

Which of the following abstract data types are not used by Integer Abstract Data Type
group?
(a)
Short
(b)
Int
(c)
Float
(d)
Long
( )

23.

There are..standard ways of maintaining a graph G in the


memory of a computer.
(a)
four
(b)
three
(c)
two
(d)
None of the above
( )

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

24.

25.

26.

27.

61

In the sequential representation of Graph G in computer, it may be difficult to:


(a)
insert nodes in G
(b)
delete nodes in G
(c)
(a) and (b) Both
(d)
None of the above

( )

The three standard ways of traversing a binary tree is:


(a)
Process the Root R
(b)
Traverse the left subtree of R in procedure
(c)
Traverse the right subtree of R in preorder
In order is:
(a)
(2) (1) (3)
( b)
(3) (2) (1)
(c)
(1) (2) (3)
(d)
None of the above

( )

Recursion may be implemented by means of:


(a)
Stacks
(b)
Binary Tree
(c)
Queue
(d)
None of the above

( )

An array PTR is called a pointer array if each element of a PTR is a:


(a)
Integer
(b)
Null element
(c)
Pointer
(d)
None of the above

( )

28.

Two condition of Binary Search algorithm are:


(a)
the list must be sorted and one must have direct access to the middle element in
any sub list
(b)
the list must be sorted and one must have direct access to the last element in any
sub list
(c)
only list is sorted
(d)
None of the above
( )

29.

Variables that can be accessed by all program modules are called:


(a)
Private variables
(b)
Global variables
(c)
Static variables
(d)
None of the above

30.

Liner array is a :
(a)
List of finite number n of heterogeneous data elements
(b)
List of finite number, n of homogenous data elements

( )

62

Biyani's Think Tank


(c)
(d)

31.

32.

33.

34.

35.

(a) and (b) both


None of the above

( )

How many null branches are there in a binary tree with 20 nodes:
(a)
Zero
(b)
Thirty
(c)
Twenty one
(d)
None of the above

( )

Equivalent Prefix notations for the expression:


((A+B)*C (DE)^(F+G)) is :
(a)
^_*+ABCDE+FG
(b)
*_^+ABCDE+FG
(c)
^+*_ABCDE+FG
(d)
None of the above

( )

Queue are also called:


(a)
LIFO lists
(b)
FIFO lists
(c)
Linked lists
(d)
None of the above

( )

Quick sort is an algorithm of the :


(a)
Modern type
(b)
Divide and conquer type
(c)
Slower efficiency
(d)
None of the above

( )

Deletion of elements in a queue can take place at:


(a)
both end
(b)
one end
(c)
in the middle
(d)
None of the above

( )

36.

An input restricted deque is the one that allows:


(a)
insertion at only one end of the list but allows deletions at both of the list
(b)
insertions at both ends of the list but allows deletion at only one end of the list
(c)
uncertain insertion and deletion of elements at both ends
(d)
None of the above
( )

37.

A binary tree T is said to be a 2-tree or an extended binary tree if each node N:


(a)
has either O or 2 children
(b)
has maximum number of children
(c)
has odd number of children

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(d)
38.

39.

40.

None of the above

63

( )

Data items that are divided into sub items are called:
(a)
Elementary item
(b)
Group item
(c)
(a) and (b) Both
(d)
None of the above

( )

DELETE (ABCDEFG', 4,2) results into:


(a)
ABCDG
(b)
ABCD
(c)
ACDEFG
(d)
None of the above

( )

Complexity of searching algorithm measured in terms of :


(a)
the umber f (n) of comparisons required to find item in DATA where DATA
contain n elements
(b)
O (log2n) comparisons
(c)
O (n2) comparisons
(d)
None of the above
( )

Answer Key
1. (c)
2. (a)

3. (b)

4. (a)

5. (a)

6. (a)

7. (b)

8. (b)

9. (c)

10. (c)

11. (d)

12. (b)

13. (d)

14. (a)

15. (b)

16. (b)

17. (b)

18. (a)

19. (b)

20. (b)

21. (d)

22. (c)

23. (c)

24. (c)

25. (a)

26. (a)

27. (c)

28. (a)

29. (b)

30. (b)

31. (c)

32. (a)

33. (b)

34. (b)

35. (b)

36. (a)

37. (a)

38. (a)

39. (a)

40. (a)

__________

64

Biyani's Think Tank

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

65

Set-II

1.

2.

3.

4.

5.

6.

7.

8.

9.

The process of arranging data in increasing order is called:


(a)
Sorting
(b)
Data Arrangement
(c)
Merging
(d)
Indexing

( )

What is the complexity of linear Search?


(a)
O (log2 n)
(c)
O (n log2 n)

( )

(b)
(d)

O (n)
O (n2)

Complexity measures are:


(a)
time
(b)
speed
(c)
both (a) & (b)
(d)
None of the above

( )

Which of the following is LIFO structure?


(a)
Stack
(c)
Tree

(b)
(d)

Queue
Graph

( )

What is the lower bound of an array in C?


(a)
1
(c)
Garbage

(b)
(d)

0
1

( )

The elements of an array are accessed by:


(a)
Accessing function in built in data structure
(b)
Mathematical function
(c)
Index
(d)
None of the above

( )

Array is:
(a)
Linear Data Structure
(b)
Non Linear Data Structure
(c)
Complex Data Structure
(d)
None of the above

( )

A dynamically allocated memory can be returned to the system by using :


(a)
malloc ()
(b)
Calloc ()
(c)
realloc ()
(d)
free ()

( )

If char * name = Dishita",; statement is executed successfully, then what will be the value
of * name?

66

Biyani's Think Tank


(a)
(b)
(c)
(d)

10.

11.

12.

13.

14.

15.

D
Dishita
Garbage
None of the above

( )

String Concatenate means:


(a)
Copying one string to another
(b)
Adding one string at end of the other
(c)
Adding one string at beginning of the other
(d)
None of the above

( )

What is the minimum number of field with each node of doubly linked list?
(a)
1
(b)
2
(c)
3
(d)
4

( )

The address field of a linked list:


(a)
Contain address of the next node
(b)
Contain address of the next pointer
(c)
May contain NULL address
(d)
Both (a) and (c)

( )

It is appropriate to represent a queue is:


(a)
A circular list
(c)
Linear linked list

(b)
(d)

Doubly linked list


Array

( )

NULL pointer is used to tell:


(a)
End of linked list
(b)
Empty pointer field of a structure
(c)
the linked list is empty
(d)
All of the above

( )

The operations push () and pop () are associated with:


(a)
Stack
(b)
Queue
(c)
Tree
(d)
All of the above

( )

16.

The infix expression A + (B C) * D is correctly represented in prefix notation is:


(a)
A +B C *D
(b)
+A * BCD
(c)
ABCD*+
(d)
A+BC D*
( )

17.

A linear list of elements in which deletion can be done from one end and insertion can
take place only at the other end is known is:
(a)
Queue
(b)
Stacks

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(c)

Tree

(d)

Branch

67

( )

18.

A binary search tree is generated by inserting in order the following integers:


50,15,62,5,20,58,91,3,8,37,60,24,
The number of nodes in the left subtree and right subtree of the root respectively is:
(a)
4,7
(b)
7,4
(c)
8,3
(d)
3,8
( )

19.

In the balanced binary search tree:


(a)
Balance factor each node is either - 1,0 or 1
(b)
Balance factor of each node is 0
(c)
Balance factor of each node is either 2, 1, 0, 1, 2
(d)
A binary search tree is always balanced

( )

In which traversal algorithm, the items are printed in Ascending order?


(a)
Preorder
(b)
Post order
(c)
In order
(d)
All of the above

( )

The heap (represented by an array) constructed from the list of number :


30,10,80,60,15,55,17, is :
(a)
60,80,,55,30,10,17,15
(b)
80,55,60,15,10,30,17
(c)
80,60,30,17,55,15,10,
(d)
None of the above

( )

Breadth first search :


(a)
Scans all incident edges before moving to other vertex
(b)
Scans all adjacent unvested vertex as soon as possible
(c)
Is same as backtracking
(d)
None of the above

( )

20.

21.

22.

23.

Which method of traversal does not use stack to hold nodes that are waiting to be
processed >
(a)
Breadth First
(b)
Depth first
(c)
D-search
(d)
None of the above
( )

24.

A binary tree with nodes has.number of Null links.


(a)
n +1
(b)
2n
(c)
n +2
(d)
n1

( )

68

25.

Biyani's Think Tank


How many cycles should be contained in a tree?
(a)
0
b)
At least 1
(c)
Any number
(d)
None of the above

( )

26.

A balanced binary tree is a binary tree in which the height of the two subtree of every
node never differs by more than:
(a)
2
(b)
1
(c)
3
(d)
None of the above
( )

27.

In which of the following tree must balance of each node be either 1, 1 or 0?


(a)
Threaded tree
(b)
Lexical ordered binary tree
(c)
AV tree
(d)
None of the above

( )

28.

Which of the following abstract data types can be used to represent a many to many
relation?
(a)
Tree, only
(b)
Plex, only
(c)
Graph, only
(d)
Both B and A
( )

29.

Graphic can be implemented using:


(i)
Arrays
(ii)
Linked list
(iii) Stack
(iv)
Queue
(a)
(i), (ii) and (iv)
(c)
(ii) and (iii)

30.

31.

(b)
(d)

(i), (ii) and (iii)


(i) and (ii)

( )

Adjacency matrix of a graph is:


(a)
Identity matrix
(b)
Symmetric matrix
(c)
Asymmetric matrix
(d)
None of the above

( )

A technique which collects all detected space in free storage list is called:
(a)
Static memory allocation
(b)
Garbage collection
(c)
Dynamic memory
(d)
None of the above

( )

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

32.

33.

34.

35.

36.

37.

38.

39.

40.

69

If function DELETE (AAA BBB', 2,2) runs, result will be:


(a)
AABB
(b)
ABBB
(c)
AAAB
(d)
None of the above

( )

Header of linked list is a special node at the :


(a)
Middle of the list
(b)
(c)
End of the linked list
(d)

( )

Beginning of the list


Both (b) and (c)

Divide and Conquer algorithm may be viewed as a:


(a)
Recursive procedure
(b)
Iterative procedure
(c)
Both of the above
(d)
None of the above
A full binary tree with a non-leaf nodes contains:
(a)
2n + 1 nodes
(b)
(c)
2n + 5 nodes
(d)

( )

n +1 nodes
log2 n nodes

( )

A connected graph G is a Eular graph if an only if all vertices is known as:


(a)
Same degree
(b)
Different degree
(c)
Odd degree
(d)
Even degree

( )

A vertex of degree one is called as:


(a)
Isolated vertex
(c)
Colored vertex

( )

(b)
(d)

Pendant vertex
Null vertex

Using arrays most efficient implementation of Queue is as:


(a)
Linear queue
(b)
Circular queue
(c)
Priority queue
(d)
None of the above

( )

Traversing means:
(a)
Accessing and Processing each record exactly once
(b)
Arranging and data in some given order
(c)
Finding the location of the record with a given key
(d)
None of the above

( )

Stack is:
(a)
Static data structure
(b)
In built data structure
(c)
Dynamic data structure

70

Biyani's Think Tank


(d)

None of the above

( )

Answer Key
1. (a)
2. (b)

3. (c)

4. (a)

5. (b)

6. (c)

7. (a)

8. (a)

9. (a)

10. (b)

11. (c)

12. (a)

13. (c)

14. (a)

15. (a)

16. (b)

17. (a)

18. (b)

19. (a)

20. (c)

21. (c)

22. (b)

23. (a)

24. (a)

25. (a)

26. (b)

27. (c)

28. (c)

29. (d)

30. (b)

31. (b)

32. (b)

33. (b)

34. (c)

35. (d)

36. (d)

37. (b)

38. (a)

39. (a)

40. (b)

________

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

71

Set- III

1.

2.

3.

Efficiently of an algorithm is measured by:


(a)
time used
(b)
(c)
A and B
(d)

space used
None

( )

The pointer of the last node in a linked list contains:


(a)
Data item
(b)
Null value
(c)
Address
(d)
None

( )

A node contains :
(a)
Information and link field
(b)
Information and data item
(c)
Address and link field
(d)
All of the above

( )

4.

Operating system periodically collect all the deleted space into the free storage list is
called:
(a)
Fragmentation
(b)
Garbage collection
(c)
Overflow
(d)
Underflow
( )

5.

Overflow means:
(a)
NO empty space available
(b)
No item is available
(c)
Error
(d)
none

( )

The pointer available in two way list node:


(a)
INFO, FORW, BACK
(b)
INFO, FORM, REVE
(c)
INFO, FRONT, REAR
(d)
None

( )

6.

7.

Stack is also called:


(a)
First in first out
(c)
First in last out

(b)
(d)

Last in first out


Last in last out

( )

72

Biyani's Think Tank

8.

Data structure that take insertion and deletion only at beginning or the end, not in the
middle:
(a)
Linked list and linear array
(b)
Stack and queues
(c)
Stack and linked list
(d)
Linked list and queues
( )

9.

The element insert in stack through:


(a)
POP
(c)
FIFO

10.

11.

12.

13.

(b)
(d)

PUSH
LIFO

Which one shows that STACK is empty :


(a)
TOP = 0 or TOP = N
(b)
TOP = 0 or TOP = NULL
(c)
TOP = N or TOP = NULL
(d)
None
Which one is not in infix notation:
(a)
A+B
(c)
G/H

( )

( )

(b)
(d)

CD
+AB

( )

is based on 'Divide and Conquer' paradigm:


(a)
Merge sort
(b)
Quick sort
(c)
Heap sort
(d)
All of the above

( )

Complexity of quick sort :


(a)
n log2 n
(c)
log n . n

( )

(b)
(d)

log n
n1

14.

A ..is a linear list of elements in which deletion can take place only at one
end and insertion at other end?
(a)
Stack
(b)
Linked list
(c)
Queue
(d)
Tree
( )

15.

Dequeue stands for :


(a)
Double single queue
(b)
Double ended queue
(c)
Double circular queue
(d)
None

16.

Which one is non linear data structure :


(a)
Linked

( )

(b)

Stack

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(c)
17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

Queue

(d)

Tree

73

( )

Any node N in binary tree has either.successor:


(a)
0,1,2
(b)
1,2 N
(c)
0,3,5
(d)
All

( )

A tree becomes tree :


(a)
If each node N has either 0 or 2 children
(b)
Each node N has N children
(c)
Each node has no children
(d)
None

( )

The depth of the complete tree Tn with n nodes is given by:


(a)
Dn = [log2 n+1]
(b)
Dn = [log n +1]
(c)
Dn = [logn 2 +1]
(d)
None

( )

Threads are related to:


(a)
Linked list
(c)
Queues

(b)
(d)

Stack
Tree

( )

Heap is related to:


(a)
Linked list
(c)
Tree

(b)
(d)

Stack
Queue

( )

Graphs can be represented by:


(a)
G (V,E)
(c)
G = (A,B)

(b)
(d)

G = (B,C)
G = (A,C)

( )

Complexity of buddle sort is:


(a)
O (n2)
(c)
log n

(b)
(d)

O (n log2 n)
O (n)

( )

Complexity of Heapsort is:


(a)
O (n log2 n)
(c)
log n

(b)
(d)

O (n)
None

( )

An edge e is called ..if it has identical endpoints.


(a)
Loop
(b)
Multigraph
(c)
Forest
(d)
Extended tree

( )

What will be the length of string 'string':


(a)
6
(c)
8

( )

(b)
(d)

7
None

74

27.

28.

Biyani's Think Tank


A class is a :
(a)
Abstract data type
(b)
User defined data type
(c)
Binding of data and member function
(d)
All of the above

( )

The following is an example of:


A

(a)
(c)
29.

30.

31.

32.

33.

Graph
Tree

(b)
(d)

Multigraph
Weighted graph

( )

BCE
BAED

( )

(b)
(d)

CDEA
None

( )

(b)
(d)

3
1

( )

(b)
(d)

BAC
CDE

( )

(b)
(d)

ABDECF
None

( )

Which one is the path of length 2 (refer Fig- A)


(a)
BAD
(b)
(c)
BCDE
(d)
A 4 cycles in the graph (refer Fig A) :
(a)
ABCEA
(c)
BADC
Degree of C i..e. deg (c) is (refer fig A ):
(a)
2
(c)
4
Which one is not a path (refer Fig A) :
(a)
BAD
(c)
ABC
Consider the binary tree (T) :
A
C

(a)
(c)
34.

DBEACF
DEBFCA

The in order traversal of tree (refer Fig B) :

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(a)
(c)
35.

36.

37.

38.

39.

40.

DBEACF
DEBFCA

75

(b)
(d)

DBEACF
None

( )

The post order traversal of tree (tree Fig B)


(a)
DEBFCA
(b)
(c)
ABDECF
(d)

DBEACF
NONE

( )

Which of the following is a graph traversal method:


(a)
BFS
(b)
DFS
(c)
Both
(d)
None

( )

A program is made up of:


(a)
constants
(b)
variables
(c)
instructions
(d)
all of the above

( )

Which of the following is a flowchart symbol:


(a)
Decision
(b)
(c)
Both A & B
(d)

Flow lines
None

( )

Recursion means:
(a)
function calling itself
(c)
Null function

(b)
(d)

Subroutine
None

( )

A binary tree node that has no children is called:


(a)
Leaf node
(b)
(c)
Non leaf node
(d)

Root node
None

( )

Answer Key
1. c)
2. (b)

3. (a)

4. (b)

5. (a)

6. (a)

7. (b)

8. (b)

9. (b)

10. (b)

11. (d)

12. (b)

13. (a)

14. (c)

15. (b)

16. (d)

17. (a)

18. (a)

19. (a)

20. (d)

21. (c)

22. (a)

23. (a)

24. (a)

25. (a)

26. (a)

27. (d)

28. (a)

29. (b)

30. (a)

31. (c)

32. (a)

33. (b)

34. (a)

35. (a)

36. (c)

37. (d)

38. (c)

39. (a)

40. (a)

76

Biyani's Think Tank


________

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

77

Set -IV
1.

2.

Stack is also known as:


(a)
LIFO system
(b)
FIFO system
(c)
FIFO LIFO system
(d)
None of the system

( )

A binary tree node that has no children is called:


(a)
Leaf node
(b)
Root Node
(c)
Non leaf node
(d)
None of the above

( )

3.

Which
(a)
(b)
(c)
(d)

of the following sorting algorithm is based on the 'Divide and Conquer' paradigm?
Quick sort
Merge Sort
Heap Sort
All of the above
( )

4.

The collection of same type of data is called:


(a)
A union
(b)
A structure
(c)
A graph
(d)
None of the above

( )

5.

The process of accession data stored in a tape is similar to manipulating data on a:


(a)
Stack
(b)
Queue
(c)
List
(d)
Heap
( )

6.

The initial configuration of a queue is P,Q, R,S (P is the front end). To the configuration
S,R,Q one needs a minimum of:
(a)
2 addition and 3 deletion
(b)
3 addition and 3 deletion
(c)
3 addition and 4 deletion
(d)
3 addition and 2 deletion
( )

7.

The depth n of the complete binary tree in with a nodes is gives by:
(a)
log2 (n +1) 1
(b)
log2 n+1
(c)
log2 (n1) + 1
(d)
log2 n

( )

78

8.

Biyani's Think Tank


What will be the expression for the following binary tree?
(a)
E = (ab)/((c*d)+e)
(b)
E = ab/c* d + e
(c)
E = a (b/c *d) +e
(d)
E =(ab/c) * (d+e)

( )

9.

One of the more popular balanced trees was introduced in 1962 by adelson-velski and
Landis is known as:
(a)
AVL Tree
(b)
B Tree
(c)
M-way search tree
(d)
None of the above
( )

10.

The following is an example of:


r

(a)
(c)
11.

Skewed binary search tree


AVL search tree

Binary tree
Binary search tree

( )

The following figure represents:


A
D
e1

e2

12.

(b)
(d)

e3

e4

(a)
(b)
(c)
(d)

e5
Directed graph
Multigraph
AVL tree
None of the above

( )

The operation of finding the location of a given item in a collection of items is called: (a)
Sorting
(b) Searching
(c)
Listing
(d)
None of the above
( )

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

13.

14.

15.

79

Worst case complexity of quick sort algorithm is:


(a)
O (n2)
(b)
O (n log n)
(c)
O (lon n)
(d)
None of those

( )

Average case complexity of heap sort algorithm is:


(a)
O (n log n)
(b)
O (n2)
(c)
O (n)
(d)
O (n log2 n)

( )

Hashing or has addressing is a technique of:


(a)
Searching
(b)
Sorting
(c)
Both (a) and (b)
(d)
None of the above

( )

16.

The notation in which operation symbol is placed before its two operands, is called: (a)
Infix notation
(b)
Polish notation
(c)
Suffix notation
(d)
None of the above
( )

17.

.is the term used to delete an element from a stack.


(a)
PUSH
(b)
POP
(c)
DEL
(d)
Both B and C

( )

18.

When a called function in turn calls another function a process of chaining occurs. A
special case of this process, where a function calls itself is called.
(a)
Recursion
(b)
Deletion
(c)
Insertion
(d)
Overloading
( )

19.

Sparse matrices have:


(a)
Many zero elements
(b)
Many non zero elements
(c)
Higher dimension
(d)
None of the above

( )

Length of the string "Manisha" is :


(a)
7
(b)
8
(c)
either 7 or 8
(d)
None of the above

( )

20.

80

21.

22.

Biyani's Think Tank

What will be the results of insert (' ABCDEFG',3 XYZ)?


(a)
ABCDEFGXYZ
(b)
ABXYZCDEFG
(c)
ABCXYZDEFG
(d)
None of the above

( )

The string with zero characters is called:


(a)
Empty string
(c)
Full string

( )

(b)
(d)

Null string
Both A and B

23.

The variables which can be accessed only within a particular program of subprogram are
known as:
(a)
Local variables
(b)
Global variable
(c)
Auto variables
(d)
External variables
( )

24.

Which of the following is a data structure?


(a)
Array
(b)
Linked list
(c)
Tree
(d)
All of the above

( )

A collection of related data-items or fields or attributes is called a:


(a)
Record
(b)
File
(c)
Database
(d)
None of the above

( )

Which of the following is a graph traversal method?


(a)
BFS
(b)
DFS
(c)
Both BFS and DFS
(d)
None of the above

( )

Previously allocated memory returned to the system by using the function:


(a)
malloc ( )
(b)
calloc ( )
(c)
free ( )
(d)
realloc( )

( )

25.

26.

27.

28.

The following figure represents :

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

81

1
2

(a)
(c)

Directed graph
Unconnected graph

(b)
(d)

Undirected graph
AVL tree

( )

29.

A special list maintained with the linked list in memory, which consists of unused
memory cells and has its own pointer is called:
(a)
List of available space
(b)
Free storage list
(c)
Free pool
(d)
All of the above
( )

30.

If every edge in the graph is assigned some data, it is called:


(a)
Multi graph
(b)
Directed graph
(c)
Tree
(d)
Weighted graph

( )

31.

What is the minimum number of fields with each elements of a doubly linked list?
(a)
1
(b)
2
(c)
3
(d)
4
( )

32.

Character data types are represented by the word?


(a)
int
(b)
(c)
char
(d)

float
ch

( )

33.

The running time T (n), where 'n' is the input size of recursive algorithm is given as
follows: T (n) = c +T (n 1 ;, if n >1, )
D =1, if n<_1
The order of algorithm is:
(a)
n2
(b)
n
(c)
n3
(d)
nn
( )

34.

If we use a 16-bit word length, the maximum size of the integer value is:
(a)
2161
(b)
2151
(c)
2191
(d)
215

35.

( )

A linear list of elements in which deletions can take place only at one end and insertions
can take place only at other end is called:
(a)
Stack
(b)
Queue
(c)
Deque
(d)
Linked list
( )

82

Biyani's Think Tank

36.

Sometimes new data are to be inserted into a data structure but there is no available space
i.e. the free storage list is empty. This situation is usually called:
(a)
Underflow
(b)
Overflow
(c)
Overflow
(d)
None of the above
( )

37.

Which of the following is not a sorting technique?


(a)
Bubble
(b)
Binary
(c)
Radix
(d)
Insertion

( )

The process of memory allocation at run time is known as:


(a)
Dynamic memory allocation
(b)
Static memory allocation
(c)
Compaction
(d)
Fragmentation

( )

The following series is known as:


0,1,1,2,3,5,8,13,21,34,55..
(a)
Fibonacci series
(c)
Compaction

Natural number series


Even number series

( )

A header list where the last node points back to the header node is called :
(a)
A grounded header list
(b)
A circular header list
(c)
Both (A) and (B)
(d)
None of the above

( )

38.

39.

40.

(b)
(d)

Answer Key
1. (a)
2. (a)

3. (a)

4. (d)

5. (b)

6. (a)

7. (b)

8. (a)

9. (a)

10. (a)

11. (b)

12. (b)

13. (a)

14. (a)

15. (a)

16. (b)

17. (b)

18. (a)

19. (a)

20. (a)

21. (b)

22. (d)

23. (a)

24. (d)

25. (a)

26. (c)

27. (c)

28. (b)

29. (d)

30. (d)

31. (c)

32. (c)

33. (a)

34. (a)

35. (b)

36. (b)

37. (b)

38. (a)

39. (a)

40. (b)

________

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

83

SET-V
1.

What is the term used for describing the judgmental or commonsense part of problem
solving?
A.
Heuristic
B.
Critical
C.
Value based
D.
Analytical
E.
None of the above
Answer: Option A

2.

What stage of the manufacturing process has been described as "the mapping of function
onto form"?
A.
Design
B.
Distribution
C.
project management
D.
field service
E.
None of the above
Answer: Option A

84

Biyani's Think Tank

3.

Which kind of planning consists of successive representations of different levels of a


plan?
A.
hierarchical planning
B.
non-hierarchical planning
C.
All of the above
D.
project planning
E.
None of the above
Answer: Option A

4.

What was originally called the "imitation game" by its creator?


A.
The Turing Test
B.
LISP
C.
The Logic Theorist
D.
Cybernetics
E.
None of the above
Answer: Option A

5.

Decision support programs are designed to help managers make:


A.
budget projections
B.
visual presentations
C.
business decisions
D.
vacation schedules
E.
None of the above
Answer: Option C

6.

PROLOG is an AI programming language which solves problems with a form of


symbolic logic known as predicate calculus. It was developed in 1972 at the University of
Marseilles by a team of specialists. Can you name the person who headed this team?
A.
Alain Colmerauer
B.
Nicklaus Wirth
C.
Seymour Papert
D.
John McCarthy
E.
None of the above
Answer: Option A

7.

Programming a robot by physically moving it through the trajectory you


follow is called:
A.
contact sensing control
B.
continuous-path control
C.
robot vision control

want it to

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

D.
E.

85

pick-and-place control
None of the above

Answer: Option B

8.

To invoke the LISP system, you must enter


A.
AI
B.
LISP
C.
CL (Common Lisp)
D.
both b and c
E.
None of the above
Answer: Option D

9.

DEC advertises that it helped to create "the world's first expert system routinely used in
an industrial environment," called XCON or:
A.
PDP-11
B.
Rl
C.
VAX
D.
MAGNOM
E.
None of the above
Answer: Option B

10.

Prior to the invention of time sharing, the prevalent method of computer


A.
batch processing
B.
telecommunication
C.
remote access
D.
All of the above
E.
None of the above
Answer: Option A

11.

Seymour Papert of the MIT AI lab created a programming environment for children
called:
A.
BASIC
B.
LOGO
C.
MYCIN
D.
FORTRAN
E.
None of the above
Answer: Option B

access was:

86

Biyani's Think Tank

12.

The Strategic Computing Program is a project of the:


A.
Defense Advanced Research Projects Agency
B.
National Science Foundation
C.
Jet Propulsion Laboratory
D.
All of the above
E.
None of the above
Answer: Option A

13.

The original LISP machines produced by both LMI and Symbolics were based on
research performed at:
A.
CMU
B.
MIT
C.
Stanford University
D.
RAMD
E.
None of the above
Answer: Option B

14.

In LISP, the addition 3 + 2 is entered as


A.
3+2
B.
3 add 2
C.
3+2=
D.
(+ 3 2)
E.
None of the above
Answer: Option D

15.

Weak AI is
A.
the embodiment of human intellectual capabilities within a computer.
B.
a set of computer programs that produce output that would be considered to
reflect intelligence if it were generated by humans.
C.
the study of mental faculties through the use of mental models implemented on a
computer.
D.
All of the above
E.
None of the above
Answer: Option C

16.

In LISP, the function assigns the symbol x to y is


A.
(setq y x)
B.
(set y = 'x')
C.
(setq y = 'x')

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

87

D.
(setq y 'x')
E.
None of the above
Answer: Option D
_
17.

18.

In LISP, the function returns t if <object> is a CONS cell and nil otherwise:
A.
(cons <object>)
B.
(consp <object>)
C.
(eq <object>)
D.
(cous = <object>)
E.
None of the above
Answer: Option B

In a rule-based system, procedural domain knowledge is in the form of:


A.
production rules
B.
rule interpreters
C.
meta-rules
D.
control rules
E.
None of the above
Answer: Option A

19.

If a robot can alter its own trajectory in response to external conditions, it is considered to
be:
A.
intelligent
B.
mobile
C.
open loop
D.
non-servo
E.
None of the above
Answer: Option A

20.

One of the leading American robotics centers is the Robotics Institute located at:
A.
CMU
B.
MIT
C.
RAND
D.
SRI
E.
None of the above
Answer: Option A

21.

In LISP, the function returns the first element of a list Is


A.
set

88

Biyani's Think Tank


B.
car
C.
first
D.
second
E.
None of the above
Answer: Option B

22.

Nils Nilsson headed a team at SRI that created a mobile robot named:
A.
Robitics
B.
Dedalus
C.
Shakey
D.
Vax
E.
None of the above
Answer: Option C

23.

An AI technique that allows computers to understand associations and relationships


between objects and events is called:
A.
heuristic processing
B.
cognitive science
C.
relative symbolism
D.
pattern matching
E.
None of the above
Answer: Option D

24.

The new organization established to implement the Fifth Generation Project is called:
A.
ICOT (Institute for New Generation Computer Technology)
B.
MITI (Ministry of International Trade and Industry)
C.
MCC (Microelectronics and Computer Technology Corporation)
D.
SCP (Stategic Computing Program)
E.
None of the above
Answer: Option A

25.

The field that investigates the mechanics of human intelligence is:


A.
history
B.
cognitive science
C.
psychology
D.
sociology
E.
None of the above
Answer: Option B
Set -VI I

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

1.

2.

89

FRONT and REAR words are related with:


(a)
Stack
(b)
Queue
(c)
Linked list
(d)
None of the above

( )

Queue is also known as:


(a)
LIFO system
(b)
FIFO system
(c)
LIFO FIFO
(d)
None of the above

( )

3.

For a sequential search, the average number of comparisons for a file with records is:
(a)
(n+1)/2
(b)
log2 n
(c)
n2
(d)
n/2
( )

4.

A data structure, in which an element is added and removed only from one end is known
is:
(a)
Queue
(b)
Stack
(c)
Array
(d)
None of the above
( )

5.

Header of a linked list a special node at the:


(a)
End of the linked list
(b)
Middle of the list
(c)
Beginning of the list
(d)
None of the above

( )

Adjacency matrix for a graph is:


(a)
Unimarix
(b)
Symmetric
(c)
Asymmetric
(d)
None of the above

( )

6.

7.

What is the minimum number of fields with each element of a doubly linked list?
(a)
1
(b)
2
(c)
3
(d)
4
( )

8.

The collection of same type of data is called:

90

Biyani's Think Tank


(a)
(b)
(c)
(d)

9.

An array
A union
A structure
None of the above

( )

In a linear linked list, a node contains at least:


(a)
Node address field and next pointer filed
(b)
Node number and data field
(c)
An information field and next pointer field
(d)
None of the above

( )

10.

Which of the following sorting algorithm is based on the idea of "Divide" and conquer?
(a)
Merge sort
(b)
Heap sort
(c)
Both B and A
(d)
None of the above
( )

11.

Which of the following is a method of searching?


(a)
Linear search
(b)
(c)
Insertion search
(d)

12.

13.

Bubble search
Selection search

( )

The element at the root of heap is:


(a)
Largest
(b)
Smallest
(c)
Depends on type of heap
(d)
None of the above

( )

Average case time complexity of quick sort algorithm is:


(a)
O (n log n)
(b)
O (log2 n)
(c)
O (n2)
(d)
None of the above

( )

14.

The five items A B C D AND E are pushed in a stack, one after the another starting from
A. The stack is popped four times and each elements is inserted in a queue. The two
element are deleted from the queue and pushed back on the stack. Now one item is
popped from the stack. The popped items is:
(a)
A
(b)
B
(c)
C
(d)
D
( )

15.

Malloc function returns a NULL when:


(a)
Memory is successfully allocated
(b)
All memory is cleared

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

(c)
(d)
16.

17.

Space is insufficient to satisfy the request


None of the above

91

( )

The process memory allocation at run time is known as:


(a)
Dynamic memory allocation
(b)
Static memory allocation
(c)
Compaction
(d)
fragmentation

( )

Which of the following is not a type of tree?


(a)
Binary
(b)
(c)
AVL
(d)

( )

Binary Search
Insertion

18.

In which tree for every node the height of its left and right sub tree differ at last by one?
(a)
Binary search tree
(b)
AVL tree
(c)
Complete Tree
(d)
None of the above
( )

19.

Which of the following is data structure operation?


(a)
Searching
(b)
Sorting
(c)
Traversing
(d)
All of the above

( )

20.

When of the following in turn calls another function a process of 'chaining' occurs. A
special case of this process, where a function calls itself is called:
(a)
Recursion
(b) Delection
(c)
Insertion
(d)
Overloading
( )

21.

Which of the following abstract data types can be used to represent a many to many
relation:
(a)
Tree
(b)
Graph
(c)
Both A and B
(d)
None of the above
( )

22.

In the balanced binary tree given below, how many nodes become unbalanced when a
node inserted as a child of the node "g"
a
e
b
d

(a)

(b)

92

Biyani's Think Tank


(c)

23.

(d)

Which of the following is a non linear data structure?


(a)
Tree only
(b)
Graph only
(c)
Array
(d)
Both tree and graph

( )

( )

24.

If we use a 16- bit word length, the size of the integer value is limited to the range:
(a)
26 to 261
(b)
210 to 2101
(c)
215
(d)
215
( )

25.

Floating point data types are represented by the word:


(a)
int
(b)
floating
(c)
float
(d)
char

26.

If there are n vertices in the graph then how many edges are needed to construct a
minimum spanning tree?
(a)
(c)

27.

28.

( )

n
n1

(b)
(d)

n+1
n2

Which of the following is an advantage o using pointers:


(a)
Pointers reduce the length and complexity of a program
(b)
They increase the execution speed
(c)
Pointers are more efficient in handling the data tables
(d)
All of the above

( )

( )

What will be the expression for the following tree?


-

(a)
(b)
(c)
(d)

(A + (B * C)) (D * E)
(A+B)* C DE
ABC +*(D*E)
None of the above

( )

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

29.

30.

31.

93

A connection between two vertices is called:


(a)
edge
(b)
vertex
(c)
tree
(d)
none of the above

( )

A node that has no children is called:


(a)
lead node
(b)
root node
(c)
parent node
(d)
none of the above

( )

Following figure represents:


a
e
b
c

(a)
(c)
32.

Directed Graph
Unconnected graph

(b)
(d)

Undirected graph
AVL tree

The fundamental operations used on a stack are:


(a)
PUSH
(b)
POP
(c)
Both A and B
(d)
None of the above

( )

( )

33.

A linear list in which elements can be added or removed at either end but not in the
middle is called:
(a)
Queue
(b)
Dequeue
(c)
Stack
(d)
Linked list
( )

34.

FRONT : = REAR : = NULL, refers to empty


(a)
Stack
(b)
(c)
Array
(d)

Queue
Linked

( )

Worst case complexity of heap sort is:


(a)
O (n2)
(c)
o (n)

O (n log2 n)
O (log2n)

( )

35.

36.

(b)
(d)

Which of the following algorithm have worst case complexity as O (n2)?


(a)
Insertion sort

94

Biyani's Think Tank


(b)
(c)
(d)

37.

38.

Bubble sort
Quick sort
All of the above

( )

Which of the following is a hashing technique?


(a)
Division method
(b)
Med square method
(c)
Folding method
(d)
All of the above

( )

POP is the term used to delete an elements from a :


(a)
Stack
(b)
Queue
(c)
Linked list
(d)
Tree

( )

39.

When new data are to be inserted into a data structure but there is no available space, this
situation is called :
(a)
Overflow
(b)
Underflow
(c)
Compaction
(d)
Fragmentation
( )

40.

The variables which can be accessed by all modules in a program, are known as:
(a)
Local variables
(b)
Internal variables
(c)
Global variables
(d)
Auto variables
( )

Answer Key
1. (b)
2. (b)

3. (d)

4. (b)

5. (c)

6. (b)

7. (c)

8. (a)

9. (c)

10. (d)

11. (a)

12. (c)

13. (a)

14. (d)

15. (c)

16. (a)

17. (d)

18. (b)

19. (d)

20. (a)

21. (b)

22. (b)

23. (d)

24. (a)

25. (c)

26. (c)

27. (d)

28. (a)

29. (a)

30. (d)

31. (a)

32. (c)

33. (b)

34. (b)

35. (b)

36. (d)

37. (d)

38. (a)

39. (a)

40. (c)

_________

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

95

A Case Study
Small world Notion.
The mathematical model that we use for studying the nature of pairwise connections among
entities is known as the graph. Some graphs exhibit a specific property known as the small-world
phenomenon. You may be familiar with this property, which is sometimes known as six degrees
of separation. It is the basic idea that, even though each of us has relatively few acquaintances,
there is a relatively short chain of acquaintances (the six degrees of separation) separating us
from one another.

Graphs.
A graph is comprised of a set of vertices and a set of edges. Each edge represents a connection
between two vertices. The list below suggests the diverse range of systems where graphs are
appropriate starting points for understanding structure.
GRAPH

VERTICES

EDGES

Communication

telephones, computers

fiber optic cable

Circuits

gates, registers, processors

wires

Mechanical

joints

rods, beams, springs

Hydraulic

reservoirs, pumping stations

pipelines

Financial

stocks, currency

transactions

Transportation

street intersections, airports

highways, air routes

Scheduling

tasks

precedence constraints

Software systems

functions

function calls

Internet

web pages

hyperlinks

Games

board positions

legal moves

Social networks

people, actors, terrorists

friendships,movie casts, associations

Protein interaction networks

proteins

protein-protein interactions

96

Biyani's Think Tank

Genetic regulatory networks

genes

regulatory interactions

Neural networks

neurons

synapses

Infectious disease

people

infections

Electrical power grid

transmission stations

cable

Chemical compounds

molecules

chemical bonds

Graph data type.


The following API supports graph processing:

Graph implementation.
Program Graph.java implements this API. Its internal representation is a symbol table of sets: the
keys are vertices and the values are the sets of neighbors (the vertices adjacent to the key) This

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

97

representation uses the two data types ST.java and SET.java that we introduced in Section 4.4.
Our implementation has three important properties:
Clients can efficiently iterate through the graph vertices.
Clients can efficiently iterate through a vertex's neighbors.
Space usage is proportional to the number of edges.

Performer-movie graphs.
The performer-movie graph includes a vertex for each performer and movie and an edge between
a performer and a movie if the performer appeared in the movie.

98

Biyani's Think Tank

We provide a number of sample data files. Each line in a file consists of a movie, followed by a
list of peformers that appeared in the movie, separated by the / delimiter.

FILE

DESCRIPTION

MOVIES ACTORS EDGES

cast.06.txt

movies release in 2006

8780

84236

103815

cast.00-06.txt movies release since 2000

52195

348497

606531

cast.G.txt

movies rated G by MPAA

1288

21177

28485

cast.PG.txt

movies rated PG by MPAA

3687

74724

116715

cast.PG13.txt movies rated PG-13 by MPAA

2538

70325

103265

cast.mpaa.txt movies rated by MPAA

21861

280624

627061

cast.action.txt action movies

14938

139861

266485

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING

99

cast.rated.txt

popular movies

4527

122406

217603

cast.all.txt

over 250,000 movies

285462

933864

3317266

Program IndexGraph.java takes a query which is the name of a movie (in which case it prints the
list of performers that appear in that movie) or the name of a performer (in which case it prints
the lst of movies in which that performer has appeared).

Shortest paths in graphs.


Given two vertices in a graph, a path is a sequence of edges connecting them. A shortest path is
one with minimal length over all such paths (there typically are multiple shortest paths).

We use the following API.

100

Biyani's Think Tank

PathFinder.java implements the API using a classic algorithm known as breadth-first search.

Degrees of separation.
One of the classic applications of shortest-paths algorithms is to find the degrees of separation of
individuals in social networks. To fix ideas, we discuss this application in terms of a recently
popularized pastime known as the Kevin Bacon game, which uses the movie-performer graph
that we just considered. Kevin Bacon is a prolific actor who appeared in many movies. We
assign every performer who has appeared in a movie a Bacon number: Bacon himself is 0, any
performer who has been in the same cast as Bacon has a Kevin Bacon number of 1, any other
performer (except Bacon) who has been in the same cast as a performer whose number is 1 has a
Kevin Bacon number of 2, and so forth. For example, Meryl Streep has a Kevin Bacon number
of 1 because she appeared in The River Wild with Kevin Bacon. Nicole Kidman's number is 2:
although she did not appear in any movie with Kevin Bacon, she was in Cold Mountain with
Donald Sutherland, and Sutherland appeared in Animal House with Kevin Bacon.
Given the name of a performer, the simplest version of the game is to find some alternating
sequence of movies and performers that lead back to Kevin Bacon. Remarkably, PathFinder.java
is precisely the program that you need to find a shortest path that establishes the Bacon number
of any performer in movies.txt.

% java PathFinder movies.txt "/" "Bacon, Kevin"


Kidman, Nicole
Bacon, Kevin
Animal House (1978)
Sutherland, Donald (I)
Cold Mountain (2003)
Kidman, Nicole
Delpy, Julia

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 101


Bacon, Kevin
The Air I Breathe (2007)
Delpy, Julia

The six degrees of separation rule suggests that most actors will have a Kevin Bacon number of
6 or less. In fact, most have a Kevin Bacon number of 3 or less!

Source:

http://introcs.cs.princeton.edu/java/45graph/

102

Biyani's Think Tank

References
A Practical Introduction to Data Structures and Algorithm Analysis Third Edition (C++
Version)
This book provides a thorough and comprehensive treatment of fundamental data structures and
the principles of algorithm analysis. Focuses on the principles required to select or design the
data structure that will best solve the problem.
Algorithmic Problem Solving
An introduction to problem-solving and algorithm formulation using an example-driven
approach. It demonstrates the importance of mathematical calculation, but the chosen examples
are typically not mathematical.
Algorithms
Contains carefully selected and clustered algorithm topics. No attempt was made to be
encyclopedic, so that this book can include topics traditionally de-emphasized or omitted from
most Algorithms books.
Algorithms for Programmers
Selected algorithms for programmers who are interested in the treated algorithms and actually
want to create a working and reasonably optimized code.
Algorithms in the Real World: Lecture Notes
This document looks both at algorithms and at case studies in which the problems are used in
real-world applications.
Art Gallery Theorems and Algorithms
Art gallery theorems and algorithms are so called because they relate to problems involving the
visibility of geometrical shapes and their internal surfaces. This book explores generalizations
and specializations in these areas.
Art of Programming Contest
A textbook for an algorithm course focusing on programming as well as a programming course
focusing on algorithms. The book is designed to train students to participate in competitions,
especially the ACM International Collegiate Programming Contest.
Average Case Analysis of Algorithms on Sequences
Describes methods employed in average case analysis of algorithms, combining both analytical
and probabilistic tools.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 103

Computational Modeling and Complexity Science


This book is about data structures and algorithms, intermediate programming in Python,
complexity science and the philosophy of science.
Data Structures and Algorithms with Object-Oriented Design Patterns in C#
Promotes object-oriented design using C# and to illustrate the use of the emerging objectoriented design patterns.
Data Structures and Algorithms with Object-Oriented Design Patterns in C++
Promotes object-oriented design using C++ and illustrates the use of the emerging objectoriented design patterns.
Data Structures and Algorithms With Object-Oriented Design Patterns in Java
Covers the fundamentals of data structures and algorithms -- the basic elements from which large
and complex software artifacts are built -- using Java programming language.
Design and Analysis of Algorithms: Course Notes
These notes teach the techniques for the design and analysis of algorithms and data structures. It
also study efficient algorithms from areas such as graph theory, networks, scheduling etc.
Design and Analysis of Computer Algorithms
Focuses on how to design good algorithms, and how to analyze their efficiency.
Efficient Algorithms for Sorting and Synchronization
Presents efficient algorithms for internal and external parallel sorting and remote data update.
Foundations of Computer Science
Introduces the principles of data structures and algorithms. Emphasises the algorithmic side of
programming, focusing on problem-solving rather than on hardware-level bits and bytes.
GNU libavl Online Book
Provides an introduction to binary tree techniques using GNU libavl, a library in ANSI C for
manipulation of various types of binary trees.
Introduction to Algorithms
Covers the behaviour, implementation, correctness and complexity of some well known array
algorithms, especially for sorting and searching.
Jeff Erickson's Algorithms Course Materials
Helps students develop algorithmic intuition, i.e. understanding how various algorithms really
work, how to attack a problem for the first time, how to tell which techniques will work at all
and which ones will work best.

104

Biyani's Think Tank

Notes for the Course of Advanced Algorithms


Describe a couple of the classical algorithms which are not taught in a first algorithms course.
Also give a general understanding of efficient algorithms and a better understanding for how to
design and analyze efficient algorithms.
Notes for the Course of Algorithms
Deal with how to design good algorithms, which is about the mathematical theory behind the
design of good programs.
Notes for the Course of Data Structures
Focus on the representation and algorithms, the concrete issues of implementation of data
structures. Provide the students with the tools needed to design and implement their own data
structures.
Object-oriented Programming with Ansi-C
Uses ANSI-C to discover how object-oriented programming is done, what its techniques are,
why they help us solve bigger problems, and how we harness generality and program to catch
mistakes earlier.
Optimization Algorithms on Matrix Manifolds
This book offers techniques with broad applications in linear algebra, signal processing, data
mining, computer vision, and statistical analysis. It can serve as a graduate-level textbook.
Practical Optimization: A Gentle Introduction
An introduction to the most important topics in applied optimization.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 105

Glossary
Acyclic, of a graph, 'having no cycles';
Adjacent, as in vertices of a graph, w is adjacent to v if there is an edge <v,w>;
Assertion, a true statement about, or a condition of, the state of a program's variables at a certain
point in the program.
Arc of a graph, direct connection between two vertices
Atom, indivisible value especially when the element of a list.
AVL tree, height balanced binary tree.
B-tree of order k (not a binary tree!) each internal node can hold k-1 keys and (pointers to) k
subtrees; ordered left to right; is height-balanced.
Binary recursion, where an activation of a subprogram may call the subprogram twice.
Binary search, to search by successive division into two equal parts.
Binary search tree, elements in left subtree < root < elements in right subtree & all subtrees also
satisfy this condition.
Binary tree, a tree where each node has 0, 1 or 2 child nodes (subtrees); also see strict binary
tree.
Breadth first traversal of a tree, visit parent then children then grand children etc.
Complete binary tree, a full binary tree where all leaf nodes are at level 'n' or 'n-1', and all
gaps, if any, are in level n at the right
Complete undirected graph, one having an edge between each pair of vertices (so it is a
clique).

Cycle, a path (see path) in a graph where the 1st and last vertices in the path are the same.
DAG, directed acyclic graph, i.e., no cycles.

106

Biyani's Think Tank

Dense graph, one where |E|~|V|2.


Dense type, where a large fraction of the set of potential values is in use.
Digraph, abbreviation for directed graph.
Directed graph, graph where each edge, <v1,v2>, has a direction, from v1 to v2.
Disjoint union, S+T, of sets S and T is the set of 'tagged union' elements from S or T.
Disjunction, as in p or q or ... or r.
Dynamic programming, a certain problem solving strategy.
Edge of a graph, direct connection between two vertices, specified by giving the two
vertices <v1,v2>; see arc.

Graph, <V,E>, a set of vertices V, and a set of edges E.

Hash, to map a sparse index type onto a range of (usually) integers.


Infix traversal of a tree, infix(left); node; infix(right).
Intersection of two sets, sometimes written S*T, or ST, or even S.T, set of elements that are in
both S and T.
Interval of an array, A[i..j] consists of A[i], A[i+1], ..., A[j] if i<=j, and is empty otherwise.
Key, unique identifier, number or other identifying attribute of an entity or thing.
Leaf, a node of a tree having no subtrees (or only empty ones).
Lexicographical, as in lexicographical order, generalizes alphabetical order, e.g.,
"abbey"<"able", "a"<"aardvark", "123"<"45", and "001.642 KNU 1:2"<"005.1 K74A"
Linear recursion, where an activation of a subprogram may call the subprogram once.
Perfect binary tree, a complete binary tree where all leaf nodes are at level 'n'.
Postfix traversal of a tree, postfix(left); postfix(right); node.
Search tree, (usually) binary tree with elements ordered left to right.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 107

Space complexity, amount of space an algorithm uses, and in particular how this varies with the
size, or some other property, of the data.
Spanning tree of a graph G, a subgraph which is a tree, contains all vertices of G; edges form a
subset of the edges of G.
Traverse, to visit each element, cell or node of a list, tree, graph or other data structure.
Tree (binary, rooted), either empty or contains two subtrees and usually also an element.
Tree (unrooted), a connected undirected graph where for any two vertices u and v, there is a
unique path from u to v.
Undirected graph, one where the edges, e.g., (v1,v2), have no sense of direction, (v1,v2) is
equivalent to (v2,v1).
Vertex, a point in a tree or graph.
Weighted graph, one where each edge has a cost or weight, i.e., edge-weighted; less
commonly, can also have a vertex-weighted graph.

108

Biyani's Think Tank


M.Sc.(INFORMATION TECHNOLOGY)
(FIRST SEMESTER)EXAMINATION, 2012
(Held in February 2013)
(New Scheme)
ALGORITHMIC AND APPLICATION PROGRAMMING
PAPER: T-101
TIME ALLOWED: THREE HOURS
Maximum Marks80
(1) No supplementary answer-book will be given to any candidate. Hence the
candidates should write the answers precisely in the Main answer-book only.
(2) All the parts of question should be answered at one place in the answer-book.
One complete question should not be answered at different places in the answer
book.
Attempt FIVE questions in out of nine
All question carry equal marks

1.

2.

3.

4.

5.

(a)

What is algorithm complexity? What is need of measuring the


complexity of an algorithm?
(b) How is a Syntax error different form a Logical error? What is
Pseudo code?

(a)

What is the difference between entry controlled loop and exit


controlled loop? Explain with example.
(b) Write an algorithm to find the sum of numbers from 1 to N.
(a) What is recursion? How does recursion compare with iteration?
(b) Why is a linked list called a dynamic data structure? What are the
advantages of using linked list over array?
(a) Difference between internal and external sorting.
(b) What is the principal difference between the function malloc and
calloc?
(c)
Difference between the getc and getchar function.
(d) Difference between printf and fprintf function.
(a) Write a program to count the number of words in a file.
(b) What is pattern matching? Describe various operations that can
perform on strings.

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 109

6.
7.

(a) Write an algorithm of binary search.


(b) Write a short note on hashing with example.
Write short notes on any Two:(a) Quicksort with example
(b) Indexing
(c)
Abstract data type
(d) File Organization.
-------------------------------------

110

Biyani's Think Tank

M.Sc.(Information Technology)
(FIRST SEMESTER)EXAMINATION, 2011
(New Scheme)
ALGORITHMIC AND APPLICATION
PAPER: T-101
TIME ALLOWED: THREE HOURS
Maximum Marks80
Note:(1) No supplementary answer-book will be given to any candidate. Hence the
candidates should write the answers precisely in the Main answer-book only.
(2) All the parts of question should be answered at one place in the answer-book.
One complete question should not be answered at different places in the answer
book.

Attempt FIVE questions in out of nine


All question carry equal marks

1.(a)

(b)
2. (a)
(b)
3. (a)
(b)
4. (a)
(b)
5. (a)

Define algorithm and its characteristics. What do you understand by


time and space complexities?
Define Pseudo codes. Explain the looping and branching in
pseudocodes.
What do you mean by data types? Explain the primitive data types.
What are strings? How is it represented in memory.
Write an algorithm to find the sum of two matrices.
What do you mean by structure with example? What is an array of
structures?
What do you understand by recursion? Explain the role of recursion
with a suitable example.
Give a comparison of quick sort and heap sort techniques and explain
them with examples.
What do you understand by Bubble sorting? Give step by step
representation of bubble sort for the following :
10,12,22,6,7,19,25,29,2,7,34,9

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 111

6. (a)
(b)
7. (a)

Write a program to copy the contents of one string to another string.


What is dynamic memory allocation? Explain with a suitable example?
Write short notes on the following :
(a) First order predicate calculus
(b) Hashed allocation
(c) Indexing
(d) Merge sort.

..

112

Biyani's Think Tank

References
http://www.algosort.com/
http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=...
@ http://www.topcoder.com/

http://algolist.manual.ru/
http://www.eternallyconfuzzled.com/jsw_home.aspx
@ http://www.eternallyconfuzzled.com/

http://www.topcoder.com/tc?d1=tutorials&d2=alg_index&modu...
@ http://www.topcoder.com/

http://www.risc.jku.at/people/ckoutsch/stuff/e_algorithms.html
@ http://www.risc.jku.at/

http://en.wikipedia.org/wiki/List_of_algorithms
@ http://en.wikipedia.org/

http://www.filepie.us/?title=List_of_algorithms
@ http://www.filepie.us/

http://www.scriptol.com/programming/list-algorithms.php
@ http://www.scriptol.com/

http://www.sorting-algorithms.com/

M.Sc.-IT (1st Semester) : ALGORITHMS AND APPLICATION PROGRAMMING 113

Bibliography
Data Structures and Algorithms: A First Course published by Springer Verlag, 1996. ISBN:
3540760474.
Data Structures and Algorithms published by Addison Wesley, 1983. ISBN: 0201000237. Pascal

The Design and Analysis of Computer Algorithms published by Addison Wesley, 1974. ISBN:
0201000296.
Algorithms and Data Structures published by Wordware Publishing, 2001. ISBN: 1556227361.
Delphi
Introduction to Algorithms 2nd edition, published by M.I.T. Press/Triliteral, 2001. ISBN:
0262032937. General

Data Structures and Algorithms in C++ 2nd edition, published by Brooks/Cole Pub Co, 2000.
ISBN:
Practical Data Structures in C++ published by John Wiley & Sons, 1993. ISBN: 047155863X.
C++

Data Structures with C++ Using STL 2nd edition, published by Prentice Hall, 2001. ISBN:
0130858501. C++

Data Structures: A Pseudocode Approach with C++ published by Brooks/Cole Pub Co, 2000.
ISBN: 053495216X. C++

Data Structures and Algorithms in Java 2nd edition, published by John Wiley & Sons, 2000.
ISBN: 0471383678. Java

Object-Oriented C++ Data Structures for Real Programmers published by Morgan Kaufmann
Data Abstraction & Structures Using C++ published by Jones & Bartlett Pub, 1996. ISBN:
0763702951. C++

114

Biyani's Think Tank

You might also like