0% found this document useful (0 votes)
57 views86 pages

Notes Part1

Uploaded by

sunnykar.9485
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
57 views86 pages

Notes Part1

Uploaded by

sunnykar.9485
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 86

TOPIC 1: ESSENTIALS OF DATA STRUCTURE

What is a Data Structure?


A data structure is a way of organizing the data so that the data can be used efficiently.

 Linear: A data structure is said to be linear if its elements form a sequence or a linear list.
Examples: Array. Linked List, Stacks and Queues
 Non-Linear: A data structure is said to be non-linear if the traversal of nodes is nonlinear in
nature. Example: Graph and Trees.

What is an Algorithm?
An algorithm is a process or a set of rules required to perform calculations or some other problem- solving
operations especially by a computer. The formal definition of an algorithm is that it contains the finite set of
instructions which are being carried in a specific order to perform the specific task. It is not the complete
program or code; it is just a solution (logic) of a problem

GAURAV BHATIA
1
Characteristics of an Algorithm

The following are the characteristics of an algorithm:

o Input: An algorithm has some input values. We can pass 0 or some input value to an
algorithm.
o Output: We will get 1 or more output at the end of an algorithm.
o Unambiguity: An algorithm should be unambiguous which means that the instructions in an
algorithm should be clear and simple.
o Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm
should contain a limited number of instructions, i.e., the instructions should be countable.
o Effectiveness: An algorithm should be effective as each instruction in an algorithm affects
the overall process.
o Language independent: An algorithm must be language-independent so that the instructions
in an algorithm can be implemented in any of the languages with the same output.

1.1 Introduction to pointer


A pointer is a variable that refers to the address of a value. It makes the code optimized and makes the
performance fast. Whenever a variable is declared inside a program, then the system allocates some memory
to a variable. The memory contains some address numbers. The variables that hold this address number is
known as the pointer variable.

int *p; // declaration of pointer variable

GAURAV BHATIA
2
Simple program to understand how pointer works
#include <stdio.h>
int main( )
{
int a = 5;
int *b;
b = &a;
printf ("value of a = %d\n", a); printf
("value of a = %d\n", *(&a));printf
("value of a = %d\n", *b); printf
("address of a = %d\n", b); printf
("address of b = %u\n", &b);
printf ("value of b = address of a = %u", b);return 0;
}
Output
value of a = 5
value of a = 5
address of a = 3010494292
address of b = 3010494296
value of b = address of a = 3010494292

%p used as format specifier in printf() function.

It's purpose is to print a pointer value in an implementation defined format. The corresponding argument
must be a void * value.

And %p is used to printing the address of a pointer the addresses are depending by our system bit.

1.2 Pointer and Array


There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. It declares ptr as an array of MAX integer pointers. Thus, each element in ptr,
holds a pointer to an int value

int *ptr[MAX]; // declaration of an array of pointers

#include <stdio.h>
GAURAV BHATIA
3
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

Output: Value of var[0] = 10


Value of var[1] = 100
Value of var[2] = 200

Example:

int arr[5] = { 1, 2, 3, 4, 5 };

int *ptr = arr;

Here, ptr that points to the 0th element of the array

Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes.

#include <stdio.h>

int main()
{
int arri[] = {1, 2 ,3};
int *ptri = arri;

char arrc[] = {1, 2 ,3};


char *ptrc = arrc;

printf("sizeof arri[] = %d ", sizeof(arri));


printf("sizeof ptri = %d ", sizeof(ptri));

printf("sizeof arrc[] = %d ", sizeof(arrc));


printf("sizeof ptrc = %d ", sizeof(ptrc));

return 0;
}
OutPut:
sizeof arri[] = 12 sizeof ptri = 4 sizeof arrc[] = 3 sizeof ptrc = 4
Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.

GAURAV BHATIA
4
For Example:

If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and
the new address it will points to 1002. While if a float type pointer is incremented then it will increment by
4(size of a float) and the new address will be 1004.

Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually
decrements by the number equal to the size of the data type for which it is a pointer.

For Example:

If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an int) and
the new address it will points to 998. While if a float type pointer is decremented then it will decrement by
4(size of a float) and the new address will be 996.

Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h>

int main()
{
float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
float *ptr1 = &arr[0];
float *ptr2 = ptr1 + 3;

printf("%f ", *ptr2);


printf("%d", ptr2 - ptr1);

return 0;
}

Output: 90.500000 3

1.3 Pointer and String


A String is a sequence of characters stored in an array. A string always ends with null ('\0') character.
Simply a group of characters forms a string and a group of strings form a sentence.

char *ptr = str;

GAURAV BHATIA
5
The pointer variable ptr is allocated memory address 8000 and it holds the address of the stringvariable
str i.e., 1000.

#include <stdio.h> // pointer to stringint


main()
{
char *cities[] = {"Iran", "Iraq"};int
i;
for(i = 0; i < 2; i++)
printf("%s\n", cities[i]);
return 0;
}

Output:
Iran

Iraq

// pointer to string
#include <stdio.h>
#include <string.h>
void function(char**);
int main()
{
char *str = "Pointer-to-string";int
i, j = strlen(str);

for(i = 0; i < j; i++)

GAURAV BHATIA
6
printf("%c",
*str++);return 0;
}
Output: Pointer-to-string

GAURAV BHATIA
7
To print the cities:

int r, c;

// print cities

for (r = 0; r < 4; r++) {c

= 0;

while(*(cityPtr[r] + c) != '\0') {

printf("%c", *(cityPtr[r] + c));

c++;

printf("\n");

1.4 Pointer and Structure.


Structure (name) is a collection of member variables member1, member2.struct

name {

member1;

member2;

};

void main()

struct name *ptr;

Here, ptr is a pointer to structure.

GAURAV BHATIA
8
Access Members of a structure using pointers
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person = person1; //person1 is an instance of structure person
struct person *personPtr;
// personPtr is the structure pointers , stores address of person structpersonPtr
= &person1;
printf("Enter age: "); scanf("%d",
&personPtr->age);printf("Enter
weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
}

In this example, the address of person1 is stored in the personPtr pointer using personPtr =
&person1;.

Now, you can access the members of person1 using the personPtr pointer. By the

way,

personPtr->age is equivalent to (*personPtr).age personPtr-

>weight is equivalent to (*personPtr).weight

Output:

Enter age: 12

Enter weight: 34

Displaying:

Age: 12

weight: 34.000000

1.5 Algorithm Complexity


Algorithmic complexity (running time) is a rough sense of how much computing resources will be required
for an algorithm to handle input data of various sizes or values, particularly in terms of time and space
GAURAV BHATIA
9
(memory or storage.)

Algorithm complexity can be further divided into two types: time complexity and space complexity
 The time complexity, as the name suggests, refers to the time taken by the algorithm to
complete its execution.
 The space complexity refers to the memory occupied by the algorithm.

Time Complexity?
Time Complexity of an algorithm/program is not the measure of actual time taken for the program to be
executed, rather it is the number of times each statement of the logic gets executed to produce the required
output.

Why do you need to Calculate Time Complexity?


A lot of times, there is more than one way to solve a particular problem and in such cases, you shouldbe able
to identify the most efficient solution out of all. This is where time-complexity comes into the picture. Time-
complexity helps you compare the performance of different solutions, thus helping you determine the
most efficient solution. Time-Complexity is nothing but a function of the input size.

How do you Calculate the Time Complexity of an Algorithm?


Time-complexity can be expressed using the below three terms called as Asymptotic Notations.

 Big - Oh or Big O Notation (BIG O)


 Omega Ω
 Theta Θ

Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic
behavior.

Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 suchthat 0


<= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}

Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds afunction
only from above.

O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) <= c*g(n) forall n >=
n0}

Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ωnotation
provides an asymptotic lower bound.

Ω (g(n)) = {f(n): there exist positive constants c and n0 such that 0 <= c*g(n) <= f(n) for
all n >= n0}.
But most times, we will use the Big O notation because it will give us an upper limit of the
execution time i.e. the execution time in the worst-case inputs. Also, an algorithm's running time
may vary among different inputs of the same size, and hence we consider worst-case complexity,
which is the maximum amount of time required for inputs of a given size.

GAURAV BHATIA
10
Asymptotic analysis
Asymptotic analysis of an algorithm, refers to defining the mathematical boundation/framing of its run-time
performance. Using asymptotic analysis, we can very well conclude the best case, average case and worst
case scenario of an algorithm.

Asymptotic analysis can provide three levels of mathematical binding of execution time of an algorithm −

 Best case is represented by Ω(n) notation.


 Worst case is represented by Ο(n) notation.
 Average case is represented by Θ(n) notation.

GAURAV BHATIA
11
Example: #include <stdio.h>int
main()
{
int a = 4;
int b = 6;
int c;
c = a + b;
printf(%d, c);
}

Complexity is O(1). No loop only simple statements, these are executed only once.

int count(int arr[], int n)


{
int sum = 0, i;
for(i = 0; i < n; i++) //Control statement
{
sum = sum + arr[i];
}
return sum;
}

Time complexity is O(n).

GAURAV BHATIA
12
GAURAV BHATIA
13
1.7 Recursion

The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite
easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree
Traversals, DFS of Graph, etc.

Example: add N natural numbers:

approach(2) – Recursive adding


f(n) = 1 n=1
f(n) = n + f(n-1) n>1

What is base condition in recursion?


In the recursive program, the solution to the base case is provided and the solution of the biggerproblem is
expressed in terms of smaller problems.

int fact(int n) // recursive program for factorial


{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1); //recursive case
}

Short Type Questions:


1 What are valid operations on pointers?
Answer:
 Assignment of pointers to the same type of pointers.
 Adding or subtracting a pointer and an integer.
 subtracting or comparing two-pointer.
 incrementing or decrementing the pointers pointing to the elements of an array. When a pointer
to an integer is incremented by one, the address is incremented by two. It is done automatically
by the compiler.
 Assigning the value 0 to the pointer variable and comparing 0 with the pointer. The pointer
having address 0 points to nowhere at all.

2 What is the usage of the pointer in C?


Answer:
 Accessing array elements: Pointers are used in traversing through an array of integers and
strings. The string is an array of characters which is terminated by a null character ‘\0’.
 Dynamic memory allocation: Pointers are used in allocation and deallocation of memory

GAURAV BHATIA
14
during the execution of a program.
 Call by Reference: The pointers are used to pass a reference of a variable to other function.
 Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct different
data structures like tree, graph, linked list, etc.

3 What is a NULL pointer in C?


Answer: A pointer that doesn’t refer to any address of value but NULL is known as a NULL pointer. When
we assign a ‘0’ value to a pointer of any type, then it becomes a Null pointer.

4 What is dangling pointer in C?


Answer: A Pointer in C Programming is used to point the memory location of an existing variable. In case
if that particular variable is deleted and the Pointer is still pointing to the same memory location, then that
particular pointer variable is called as a Dangling Pointer Variable.

5 What is pointer to pointer in C?


Answer: In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The
pointer to pointer is a chain of pointers. Generally, the pointer contains the address of a variable. The pointer
to pointer contains the address of a first pointer.

6 To make pointer generic for which data type needs to be declared?


Answer: void

7 Can Math Operations Be Performed On A Void Pointer?


Answer: No. Pointer addition and subtraction are based on advancing the pointer by a number of elements.
By definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of
what it’s pointing to. If you want pointer arithmetic to work on raw addresses,use character pointers.

8 What Is Indirection?
Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a
variable or any other object in memory, you have an indirect reference to its value.

9 How Are Pointer Variables Initialized?


Answer: Pointer variable are initialized by one of the following two ways:Static
memory allocation
Dynamic memory allocation
10 How is the null pointer different from a void pointer?
Answer: A pointer is initialized as NULL when its value isn’t known at the time of declaration. Generally,
NULL pointers do not point to a valid location. Unlike NULL pointers, void pointers are general-purpose

GAURAV BHATIA
15
pointers that do not have any data type associated with them. Void pointers can contain the address of any
type of variable. So, the data type that a void pointer points to can be anything.

11 In what data structures are pointers applied?


Answer: Pointers that are used in the linked list have various applications in the data structure. Data
structures that make use of this concept include the Stack, Queue, Linked List and Binary Tree

12 What does it mean when a pointer is used in an if statement?


Answer: It is good habits to check the pointer in if condition before using it. It prevents code crashing. A
pointer can be used in an if, while, for, or do/while statement, or in any conditional expression.

if ( p )
{
/*Run when valid address */
}
else
{
/*When NULL pointer*/
}
13 Differentiate Between Arrays And Pointers?
Answer: Pointers are used to manipulate data using the address. Pointers use * operator to access
the data pointed to by them Arrays use subscripted variables to access and manipulate data. Array
variables can be equivalently written using pointer expression.

14 What is an array of pointers?


Answer: If the elements of an array are addresses, such an array is called an array of pointers.

15 Represent a two-dimensional array using pointer?


Address of a[I][j] Value of a[I][j]
&a[I][j]
or
a[I] + j
or
*(a+I) + j
*&a[I][j] or a[I][j]
or
*(a[I] + j )
or
*( * ( a+I) +j )

GAURAV BHATIA
16
16 Difference between an array of pointers and a pointer to an array
Answer:
Array of pointers
Declaration is: data_type *array_name[size];Size
represents the row size.
The space for columns may be dynamically

Pointers to an array
Declaration is data_type ( *array_name)[size];Size
represents the column size.

17 Are the expressions *ptr ++ and ++ *ptr same?


Answer: No, *ptr ++ increments pointer and not the value pointed by it. Whereas ++ *ptr
increments the value being pointed to by ptr.

#include <stdio.h>
int main(void)
{
int aiData[5] = {100,200,300,400,500};
int *piData = &aiData;
++*piData;
printf("%d %d %d \n ”, aiData[0], aiData[1], *piData);
printf("%d”, *(piData+2));

return 0;
}
Output: 101 200 101
300

18 What are the advantages of using array of pointers to string instead of an array of strings?
Answer:

i) Efficient use of memory.


ii) Easier to exchange the strings by moving their pointers while sorting.
19 State the equivalent pointer expression which refer the given array element
a[i][j][k][l]?
Answer: Above pointer expression can be written as *(*(*(*(a+i)+j)+k)+l).

20 What is difference between tailed and non-tailed recursion?


Answer: A recursive function is tail recursive when recursive call is the last thing executed by
the function.

GAURAV BHATIA
17
21 How memory is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on the stack. A recursive
function calls itself, the memory for a called function is allocated on top of memory allocated to
calling function and different copy of local variables is created for each function call. When the
base case is reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
22 What are the disadvantages of recursive programming over iterative programming?
Answer: The recursive program has greater space requirements than iterative program as all functions
will remain in the stack until the base case is reached. It also has greater time requirements because of
function calls and returns overhead.

23 What are the advantages of recursive programming over iterative programming?


Answer: Recursion provides a clean and simple way to write code.

GAURAV BHATIA
18
Essential Quiz 1- ESSENTIALS OF DATA STRUCTURE

1. Predict output of following program.


#include <stdio.h>

int fun(int n)
{
if (n == 4)
return n;
else return 2*fun(n+1);
}

int main()
{
printf("%d ", fun(2));
return 0;
}

(A) 4
(B) 8
(C) 16
(D) Runtime error

Answer: C

2. What is the output of the following program?


#include<stdio.h>

main()

int x = 65, *p = &x;

void *q=p;

char *r=q;

printf("%c",*r);

A - Garbage character.

B-A

C - 65

D - Compile error

Answer: B

19
3. What is the output of the following program?
#include<stdio.h>

main()

int a[] = {1,2}, *p = a;

printf("%d", p[1]);

A-1
B-2
C - Compile error
D - Runtime error
Answer: B

4. Consider the following recursive function fun(x, y). What is the value of fun(4, 3)

int fun(int x, int y)


{
if (x == 0)
return y;
return fun(x - 1, x + y);
}
(A) 13
(B) 12
(C) 9
(D) 10
Answer: A

5. What does the following function print for n = 25?


void fun(int n)
{
if (n == 0)
return;
printf("%d", n%2);
fun(n/2);
}

(A) 11001
(B) 10011
(C) 11111
(D) 00000

Answer: B

20
6. What does the following function do?
int fun(int x, int y)
{
if (y == 0) return 0;
return (x + fun(x, y-1));
}

A. x+y
B. x+x*y
C. x*y
D. xy
Answer: C

7. Output of following program?


#include<stdio.h>
void print(int n)
{
if (n > 4000)
return;
printf("%d ", n);
print(2*n);
printf("%d ", n);
}
int main()
{
print(1000);
getchar();
return 0;
}
A. 1000 2000 4000 4000 2000 1000
B. 1000 2000 4000 2000 1000
C. 1000 2000 4000 2000
D. None of the above
Answer: A

8. The reason for using pointers in a C program is


A. Pointers allow different functions to share and modify their local variables.
B. To pass large structures so that complete copy of the structure can be avoided.
C. Pointers enable complex “linked" data structures like linked lists and binary trees.

D. All of the above

Answer: D

9. Predict the output of following program


#include <stdio.h>
int f(int n)
{
if(n <= 1)
return 1;
if(n%2 == 0)
GAURAV BHATIA
return f(n/2);
return f(n/2) + f(n/2+1);
}
int main()
{
printf("%d", f(11));
return 0;
}

(A) Stack Overflow,


(B) 3
(C) 4
(D) 5
Answer: D

10. Which of the following C code snippet is not valid?


(A) char* p = “string1”; printf(“%c”, *++p);
(B) char q[] = “string1”; printf(“%c”, *++q);
(C) char* r = “string1”; printf(“%c”, r[1]);
(D) None of the above
Answer: B

11. What does the following fragment of C-program print?


char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;
(A) GATE2011
(B) E2011
(C) 2011
(D) 011
Answer: C
12. What is the output of following code:
main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}

GAURAV BHATIA
A. Address Of p
B. Hello
C. H
D. None
Answer: C
13.
int y[4] = {6, 7, 8, 9};
int *ptr = y + 2;
printf("%d\n", ptr[ 1 ] );

What is printed when the sample code above is executed?

A. 6
B. 7
C. 8
D. 9
Answer: D

14. What are the two main measures for the efficiency of an algorithm?
A. Time and memory
B. Time and space
C. Complexity and space
D. Data and memory
Answer: A

15. Let w(n) and A(n) denote respectively, the worst case and average case running time of an
algorithm executed on an input of size n. which of the following is ALWAYS TRUE?

Answer: C

16. The following statement is valid. log(n!) = (n log n).


A. True
B. False
Answer: A

17. What does it mean when we say that an algorithm X is asymptotically more efficient than Y?
A. X will be a better choice for all inputs
B. X will be a better choice for all inputs except possibly small inputs
C. X will be a better choice for all inputs except possibly large inputs

GAURAV BHATIA
D. Y will be a better choice for small inputs.
Answer: B.

18. What is the time, space complexity of the following code:

int a = 0, b = 0;

for (i = 0; i < N; i++) {a

= a + rand();

for (j = 0; j < M; j++) {b

= b + rand();

A. O(N * M) time, O(1) space


B. O(N + M) time, O(N + M) space
C. O(N + M) time, O(1) space
D. O(N * M) time, O(N + M) space
Answer: C.
19. void fun(int *ptr)
{
*ptr = 30;
}

int main()
{
int y = 20;
fun(&y);
printf("%d", y);

return 0;
}

(A) 20
(B) 30
(C) Compiler error
(D) Runtime error
Answer: B

20. What will be output of following program?

#include<stdio.h>
int main() {
int a = 10;
void *p = &a;
int *ptr = p;
GAURAV BHATIA
printf(“%u”,*ptr);
return 0;
}

A. 11
B. 10
C. Garbage value
D. None of the above

Answer: B
Essential Quiz 2: ESSENTIALS OF DATA STRUCTURE

1. What is the time complexity of the following code?

int a = 0, i = N;
while (i > 0) {
a += i;i
/= 2;
}
A. O(N)
B. O(Sqrt(N))
C. O(N / 2)
D. O(log N)
Answer: D.

2. How is time complexity measured?


A. By counting the number of algorithms in an algorithm.
B. By counting the number of primitive operations performed by the algorithm on given input
size.
C. By counting the size of data input to the algorithm.
D. None of the above
Answer: B.
3. What is the complexity of the following code:

for(var i=0;i<n;i++)
i*=k

A. O(n)
B. O(k)
C. O(logkn)
D. O(lognk)
Answer: C
4. What will be the time complexity of the following code?
var value = 0; for(var

i=0;i<n;i++)

for(var j=0;j<i;j++)
value += 1;

GAURAV BHATIA
A. n
B. (n+1)
C. n(n-1)/2
D. n(n+1)/2
Answer: C

5. To print an address string, which specifier should be used? *


A. %p
B. %d
C. %s
D. Address cannot be printed
Answer: A

6. NULL is a special pointer constant defined under which header file? *


A. conio.h
B. stdio.h
C. math.h
D. None of these
Answer:B.

7. Which of the following is/are FALSE?


A. A pointer holds the address of the very first byte of memory location where it is pointing to
B. Pointers can be multiplied
C. An integer may be added to or subtracted from a pointer
D. All are false
Answer: B.

8. Consider the code fragment: int num[] = {24,34,12}; int i = 0; Then, to print the first number
of the array, which of the following statements cannot be used?

A. printf(“%d”, *(num+i));
B. printf(“%d”,*(i+num));
C. printf(“%d”,i[num]);
D. All can be used
Answer: D.

9. What will be the output of this code fragment :

int student[3][2]= { {1234,56}, {1212,33}, {1434,80}};

int i=0, j=1;

printf(“%d”, *(*(student+i)+j));

A. 56
B. 33
C. 1234
D. 80

GAURAV BHATIA
Answer: A

10. Which of the following operations is not allowed?

int *p1, *p2, *p3;

11.int x = 2, y = 3;

p1 = &x; p2 = &y;

A.p3 =p1+p2;
B.p1++
C.p2--
D.p1+=2
Answer: A

11. int x[3][5] = { {1,2,3,4,5} , {6,7,8,9,10}, {11,12,13,14,15} };

Pick the incorrect statement:

A. printf(“%d”, *(*(x+2)+1)) prints 12


B. printf(“%d”,*(*(x+1))) prints 6
C. printf(“%d”,*(*(x)+2)+1) prints 5
D. printf("%d",*(*(x+1)+3) prints 9
Answer: C

12. How many times is ‘a’ printed when the following C code is executed?

#include<stdio.h>
main()
{
int a;
a=f1(10);
printf("%d",a);
}
f1(int b)
{
if(b==0)
return 0;
else
{
printf("a");
f1(b--);
}
}
a) 9 times
b) 10 times
c) 0 times
d) Infinite number of times

GAURAV BHATIA
Answer: D

13. void fun(int *ptr)


{
*ptr = 50;
}
int main()
{
int y = 200;
fun(&y);
printf("%d", y);

return 0;
}

A. 200
B. 50
C. Compiler error
D. Runtime error
Answer: B

14. What does the following function print for n = 100?


void fun(int n)
{
if (n == 0)
return;
printf("%d", n%2);
fun(n/2);
}
A. 0010011
B. 0010010
C. 0010101
D. ] 0000011
Answer: A

15. In the absence of a exit condition in a recursive function, the following error is given

A) Compile time error


B) Run time error
C) Logical error
D) No error
Answer: B
What is the output of the code?#include<stdio.h>
main()
{
int n,i;
n=f(6);
printf("%d",n);
}
f(int x)
{
if(x==2)
return 2;
else
GAURAV BHATIA
{
printf("+");
f(x-1);
}
}
A) ++++2
B) +++++2
C) +++++
D) 2

Anwer: A

16. Can we call main() function recursively.?


A. Yes
B. No
C. Compiler Error
D. Run Time Error
Answer: A

17. Iteration requires more system memory than recursion.


A. True
B. False
Answer: B

18. Which of the following problems can’t be solved using recursion?


a) Factorial of a number
b) Nth fibonacci number
c) Length of a string
d) Problems without base case
Answer: D

19. In recursion, the condition for which the function will stop calling itself is
a) Best case
b) Worst case

GAURAV BHATIA
c) Base case
d) There is no such condition
Answer: C
Essential Quiz 3: ESSENTIALS OF DATA STRUCTURE

1.
void fun(int *ptr)
{
printf("%d ", *ptr);
*ptr = 150;
}

int main()
{
int y = 2020;
fun(&y);
printf("%d", y);

return 0;
}

A. 2020 150
B. 150 2020
C. Compiler error
D. 2020 2020
Answer: A

2. What will be output of following program?

#include<stdio.h>
void main() {
char a = 'A';
char *p = &a;
printf("%d \t",*p);
printf("%c",*p);
}
A. 65 A
B. A A
C. Garbage value
D. None of the above
Answer: A

3. What is the output of the program?


#include<stdio.h>
main()
{
int n;
n = f1(4);
printf("%d",n);
}
GAURAV BHATIA
f1(int x)
{
int b;
if(x==1)
return 1;
else
b=x*f1(x-1);
return b;

A. 24
B. 4
C. 12
D. 10
Answer: A

4. The data structure used to implement recursive function calls


A) Array
B) Linked list
C) Binary tree
D) Stack
Answer: D

5. What will be the output of the following C code?


#include<stdio.h>
main()
{
int n=10;
int f(int n);
printf("%d",f(n));
}
int f(int n)
{
if(n>0)
return(n+f(n-2));
}
a) 10
b) 80
c) 30
d) Error

Answer: C

6. What will be the output of the following C code?


#include<stdio.h>
GAURAV BHATIA
int main()
{
printf("Hello");
main();
return 0;
}
A) Hello is printed once
B) Hello infinite number of times
C) Hello is not printed at all
D) compiler error
Answer: B

7. Recursion is a method in which the solution of a problem depends on


A) Larger instances of different problems
B) Larger instances of the same problem
C) Smaller instances of the same problem
D) Smaller instances of different problems
Answer: C

8. What is the output of C Program with Strings.?


int main()

char ary[]="Discovery Channel";

printf("%s",ary);

return 0;

A) D
B) Discovery Channel
C) Discovery
D) Compiler error
Answer: B

GAURAV BHATIA
9. What is the output of the code?
int main()
{
char country[]="INDIA";
char *ptr;
ptr = country;
while(*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
return 0;
}
A) I
B) INDIA
C) Compiler error
D) NDIA
Answer: B

10. What is the output


int main()

char *p1 = "GOAT";


char *p2;
p2 = p1;
p2="ANT";
printf("%s", p1);
}

A) ANT
B) GOAT
C) G
D) A
Answer: B

11. What is the output of the code?


int main()

char *p1 = "GOAT";


char *p2;
p2 = p1;
p2="ANT";
printf("%s", p2+1);
}

A) NT
B) OAT

GAURAV BHATIA
C) ANT
D) Compiler error
Answer: A

12. What is the output of the code?


int main()

char p[] = "QuizProgram";int

i=2;

while(p[i] != '\0')

printf("%c",*(p+i));

i++;

A. izProgram
B. QuizProgram
C. Compiler error
D. zProgram
Answer: A

13. Output of the code?


Assume that an int variable takes 2 bytes and a char variable takes 1 byte
#include<stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr1 = arr;
int *ptr2 = arr + 4;
printf("Number of elements between two pointer are: %d.",(ptr2
- ptr1));
printf("\n Number of bytes between two pointers are: %d",
(char*)ptr2 - (char*) ptr1);
return 0;
}
A. Number of elements between two pointer are:4
Number of bytes between two pointers are: 8

B. Number of elements between two pointer are:5

GAURAV BHATIA
Number of bytes between two pointers are: 10
C. Number of elements between two pointer are:0
Number of bytes between two pointers are: 12

D. None of the above


Answer: A

14. Pick the correct statement:

int x[3][4] = { {1,2,3,4 } , {6,7,8,9}, {11,12,13,14} };

A. printf(“%d”, *(*(x+2)+2)) prints 12


B. printf(“%d”,*(*(x+4))) prints 6
C. printf(“%d”,*(*(x)+2)+4) prints 7
D. printf("%d",*(*(x+1)+2) prints 9
Answer: C

15. .
void fun(int *ptr)*ptr = 150 + 10;
{
}

int main()
{
int y = 2020;
fun(&y);
printf("%d", y);

return 0;
}

A. 160
B. Compiler error
C. Address of y incremented by 10
D. None of the above
Answer: A

16. What does the following fragment of C-program print?


char c[] = "IMS2011-2021";

char *p =c;

printf("%s", p + p[3] - p[3]) ;(A)

IMS2011-2021
(B) T2011-2021
(C) 2011-2021
(D) 2021

GAURAV BHATIA
Answer: A

17. main( )
{
static int a[ ] = { 0, 1, 2, 3, 4 } ;
static int *p[ ] = { a, a + 1, a + 2, a + 3, a+ 4 } ;int
**ptr = p ;
ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;

*ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;

**ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;

++*ptr ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr )
}

A. 123 222 333 444


B. 111 222 333 444
C. 111 222 333 444
D. 111 234 333 444

Answer: B

18. main( )
{
static int a[ ] = { 2, 4, 6, 8, 10 } ;
int i ;
for ( i = 0 ; i <= 4 ; i++ )
{
*( a + i ) = a[i] + i[a] ;
printf ( “%d”, *(i + a ) ) ;
}
}

A. 2 4 6 8 10
B. 4 8 12 16 20
C. 2 8 12 16 20
D. 4 8 6 16 20

Answer: B
Answer: C

19. main( )
{
static int b[ ] = { 10, 20, 30, 40, 50 } ;
int i, *k ;
k = &b[4] – 4 ;
for ( i = 0 ; i <= 4 ; i++ )
GAURAV BHATIA
{
printf ( “%d”, *k ) ;
k++ ;
}
}

A. 10 20 30 40 50
B. 50 40 30 20 10
C. 10 30 50 20 40
D. 10 10 10 10 10
Answer: A

20. #include<string.h>
main ( )
{
char str1[15]= “Good” ;
char str2[ ] = “Evening” ;
strcpy (str1, str2) ;
printf ( “%s\n”, str1 ) ;
}

A. Evening
B. GoodEvening
C. Good
D. GoodE

Answer: A

TOPIC 2: Linked List


2.1 Single Linked List
What is a linked list?

GAURAV BHATIA
Linked List is the collection of randomly stored data objects called nodes. In Linked List, each nodeis linked
to its adjacent node through a pointer. A node contains two fields, i.e. Data Field and Link Field. Each node
element has two parts:

 a data field
 a reference (or pointer) to the next node.
The first node in a linked list is called the head and the last node in the list has the pointer to NULL. Null in
the reference field indicates that the node is the last node. When the list is empty, the head isa null reference.

What is a Linked List and What are its types?


A linked list is a linear data structure (like arrays) where each element is a separate object. Eachelement
(that is node) of a list is comprising of two items – the data and a reference to the next node.Types of
Linked List :
1. Singly Linked List : In this type of linked list, every node stores address or reference of next
node in list and the last node has next address or reference as NULL. For example 1 ->2->3-
>4->NULL
2. Doubly Linked List : Here, here are two references associated with each node, One of the
reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3-
>NULL
3. Circular Linked List : Circular linked list is a linked list where all nodes are connected to
form a circle. There is no NULL at the end. A circular linked list can be a singly circular
linked list or doubly circular linked list. Eg. 1->2->3->1 [The next pointer of last node is
pointing to the first]

GAURAV BHATIA
2.2 Doubly Linked List
What is a doubly-linked list (DLL)? What are its applications.

Answer:

The doubly linked list is a complex type of linked list in which a node contains a pointer to the previous
as well as the next node in the sequence. In a doubly linked list, a node consists of threeparts:

o node data
o pointer to the next node in sequence (next pointer)
o pointer to the previous node (previous pointer).

Applications of DLL are:

A music playlist with next song and previous song navigation options.The

browser cache with BACK-FORWARD visited pages

The undo and redo functionality on platforms such as word, paint etc, where you can reverse thenode to
get to the previous page.

What is the use of a doubly-linked list when compared to that of a singly linked list?

GAURAV BHATIA
In a singly linked list, we have only forward links. Hence, we cannot traverse the linked list in a backward
manner. In order to overcome this, we go for a doubly linked list. In a doubly linked list, each node has three
fields such as previous, data and next field and has two links such as a forward and backward link. The
previous field of the first node and the address field of the last node is NULL. The previous field of the second
node has the address of the first node and so on.
Also, accessing of elements can be done more efficiently in case of a doubly linked list.

2.3 Circular Linked List


Circular Linked List is a variation of Linked list in which the first element points to the last element and the
last element points to the first element.

Advantages of Circular Linked Lists:

1) Any node can be a starting point. We can traverse the whole list by starting from any point. We
just need to stop when the first visited node is visited again.

2) Useful for implementation of queue. Unlike this implementation, we don’t need to maintain two
pointers for front and rear if we use circular linked list. We can maintain a pointer to the last inserted
node and front can always be obtained as next of last.

3) Circular lists are useful in applications to repeatedly go around the list. For example, when multiple
applications are running on a PC, it is common for the operating system to put the running
applications on a list and then to cycle through them, giving each of them a slice of time to execute,
and then making them wait while the CPU is given to another application. It is convenient for the
operating system to use a circular list so that when it reaches the end of the list it can cycle around to
the front of the list.

List some applications of circular list.

GAURAV BHATIA
Used in managing the computing resources of a computer.
Implementing stacks and queues.

2.4 Double Circular Linked List

Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two
consecutive elements are linked or connected by previous and next pointer and the last node points to first
node by next pointer and also the first node points to last node by previous pointer.

// Structure of the node

struct node

int data;

struct node *next; // Pointer to next node struct

node *prev; // Pointer to previous node

};

GAURAV BHATIA
How Memory is managed in Circular Doubly linked list

The variable head contains the address of the first element of the list i.e. 1 hence the starting node of the list
contains data A is stored at address 1. Since, each node of the list is supposed to have three parts therefore,
the starting node of the list contains address of the last node i.e. 8 and the next node
i.e. 4. The last node of the list that is stored at address 8 and containing data as 6, contains address ofthe first
node of the list as shown in the image.

Operations on Circular Double Linked List

GAURAV BHATIA
Insertion in empty circular doubly list

Insertion at the beginning of the circular doubly list

To insert a node at the beginning of the list, create a node(Say T) with data = 5, T next pointer points to first
node of the list, T previous pointer points to last node the list, last node’s next pointer points to this T node,
first node’s previous pointer also points this T node and at last don’t forgetto shift ‘Start’ pointer to this T
node.

Advantages of Circular Doubly Linked List

 List can be traversed from both the directions i.e. from head to tail or from tail to head.
 Jumping from head to tail or from tail to head is done in constant time O(1).
 Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.

Disadvantages of Circular Doubly Linked List

 It takes slightly extra memory in each node to accommodate previous pointer.


 Lots of pointers involved while implementing or doing operations on a list. So, pointers
should be handled carefully otherwise data of the list may get lost.

GAURAV BHATIA
Applications of Circular doubly linked list
 Managing songs playlist in media player applications.
 Managing shopping cart in online shopping.

2.5 Applications of Linked List

Few of the main applications of Linked Lists are:

o Linked Lists let us implement queues, stacks, graphs, etc.


o Linked Lists let us insert elements at the beginning and end of the list.

GAURAV BHATIA
Short Type Questions
1 Are linked lists of linear or non-linear type?
Answer:

A linked list is considered both linear and non-linear data structure depending upon the situation.

o On the basis of data storage, it is considered as a non-linear data structure.


o On the basis of the access strategy, it is considered as a linear data-structure.

2 How are linked lists more efficient than arrays?


Answer:

Insertion and Deletion

Insertion and deletion process is expensive in an array as the room has to be created for the newelements
and existing elements must be shifted.

But in a linked list, the same operation is an easier process, as we only update the address present inthe next
pointer of a node.

Dynamic Data Structure

Linked list is a dynamic data structure that means there is no need to give an initial size at the timeof
creation as it can grow and shrink at runtime by allocating and deallocating memory.

Whereas, the size of an array is limited as the number of items is statically stored in the main
memory.

No wastage of memory

As the size of a linked list can grow or shrink based on the needs of the program, there is nomemory
wasted because it is allocated in runtime.

In arrays, if we declare an array of size 10 and store only 3 elements in it, then the space for 3
elements is wasted. Hence, chances of memory wastage is more in arrays.

GAURAV BHATIA
3 How many pointers are necessary to implement a simple Linked List?
Answer: There are generally three types of pointers required to implement a simple linked list:

o A 'head' pointer which is used for pointing to the start of the record in a list.
o A 'tail' pointer which is used for pointing to the last node. The key factor in the last node is
that its subsequent pointer points to nothing (NULL).
o A pointer in every node which is used for pointing to the next node element.

4 Which type of memory allocation is referred for Linked List?


Answer: Dynamic memory allocation is referred for Linked List.

5 What do you know about traversal in linked lists?


Answer:The term 'traversal' refers to the operation of processing each element present in the list.

6 What does the dummy header in the linked list contain?


Answer:In a linked list, the dummy header consists of the first record of the actual data.

7 Mention a few applications of Linked Lists?

Answer:Few of the main applications of Linked Lists are:

o Linked Lists let us implement queues, stacks, graphs, etc.


o Linked Lists let us insert elements at the beginning and end of the list.

How can you insert a node to the beginning of a singly linked list?

To insert the node to the beginning of the list, we need to follow these steps:

o Create a new node


o Insert new node by assigning the head pointer to the new node's next pointer

Update the head pointer to point the new node

Node *head;
voidInsertNodeAtFront(int data)
{
/* 1. create the new node*/
Node *temp = new Node;
temp->datadata = data;
/* 2. insert it at the first position*/

[Type text]
temp->next = head;
/* 3. update head to point to this new node*/
. head = temp;
.}

8 What operations can be performed on a linked list.

Answer: The following are the basic operations supported by linked lists.

 Insertion − Inserts an element at specified positions in the list.


 Deletion − Deletes an element at specified positions in the list.
 Search − Searches an element using the given value.
 Update − Update an element at specified position with the given value

Write the syntax in C to create a node in the singly linked list.

struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node));

9 Differentiate between singly and doubly linked lists?

Answer: Doubly linked list nodes consist of three fields: an integer value and two links pointing to two
other nodes (one to the last node and another to the next node).

On the other hand, a singly linked list consists of a link which points only to the next node.

10 How can we reverse a singly linked list?

Answer: To reverse the singly linked list, we are required to iterate through the list. We need to reverse the
link at each step like after the first iteration, the head will point to null, and the next element will point to the
head. At the end of traversal when we reach the tail of the linked list, the tail will start pointing to the second
last element and will become a new head. It is because we can further traverse through all the elements from
that particular node.

11 The steps given below can be used to reverse a singly linked list:

o First, we need to set a pointer (*current) pointing to the first node (i.e., current=head).
o Move ahead until current! =null (till the end of the list).

GAURAV BHATIA
o Set another pointer (*next) pointing to the next node (i.e. next=current->next>next=result
o Keep reference of *next in a temporary variable (*result) i.e. current->next=result
o Exchange the result value with current, i.e., result=current
o And then swap the current value with next, I.e., current=next.
o Return result and repeat from step 2.

A linked list can also be reversed by using recursion which eliminates the use of a temporary variable.

12 How to calculate the length of a singly linked list?

Answer: We can iterate over the linked list and keep a count of nodes until we reach the end of the linked
list where the next node will be null. The value of the counter is considered as the length of the linked list.

13 How can someone display singly linked list from first to last?

Answer: One must follow these steps to display singly linked list from first to last:

o Create a linked list using create().


o The address stored inside the global variable "start" cannot be changed, so one must declare
one temporary variable "temp" of type node.
o To traverse from start to end, one should assign the address of starting node in the pointer
variable, i.e., temp.

struct node *temp; //Declare temp variable


temp = start; //Assign Starting Address to temp
//If the temp is NULL, then it means that the last node is accessed.
while(temp!=NULL)
{
printf("%d",temp->data);
temptemp=temp->next;
}

14 Mention some drawbacks of the linked list.

Answer: Some of the important drawbacks of the linked list are given below:

o Random access is not allowed. We need to access elements sequentially starting from the first
node. So we cannot perform a binary search with linked lists.
o More memory space for a pointer is required with each element of the list.

GAURAV BHATIA
o Slow O(n) index access, since accessing linked list by index means we have to loop over the
list recursively.
o Poor locality, the memory used for the linked list is scattered around in a mess.

15 Which sorting algorithm is easily adaptable to singly linked lists?

Answer: Simple Insertion sort is easily adabtable to singly linked lists. To insert an element, the linked list
is traversed until the proper position is found, or until the end of the list is reached. It is inserted into the list
by merely adjusting the pointers without shifting any elements, unlike in the array. This reduces the time
required for insertion but not the time required for searching for the proper position.

16 Can we apply Binary search algorithm to a sorted Linked list?

Answer: No, we cannot apply the binary search algorithm to a sorted linked list because finding theindex of
the middle element is difficult.
How to reverse a singly linked list (Iterative approach)
Answer:

 Initialize pointers prev as NULL, curr as head and next as NULL.


 Iterate through the list. In a loop, do the following.

/* Before changing next pointer of current node,


store the next node */
next = curr -> next
/* Change next pointer of current node */
/* Actual reversing */
curr -> next = prev
/* Move prev and curr one step ahead */prev =
curr
curr = next

17 What are the primary disadvantages of doubly linked lists?

Answer:

 Each node requires an extra pointer, requiring more space.


 The insertion or deletion of node takes a bit longer.

Time and Space complexity of List and Array for different operations

GAURAV BHATIA
18 How is an Array different from Linked List?

Answer:
 The size of the arrays is fixed, Linked Lists are Dynamic in size.
 Inserting and deleting a new element in an array of elements is expensive, Whereas both
insertion and deletion can easily be done in Linked Lists.
 Random access is not allowed in Linked Listed.
 Extra memory space for a pointer is required with each element of the Linked list.
 Arrays have better cache locality that can make a pretty big difference in performance

19 Compare Linked List and array in terms of their insertion/deletion time.

Parameter Linked List Array

GAURAV BHATIA
Insertion/deletion at the beginning O(1) O(n)

Deletion at the ending O(n) O(1)

Insertion at ending O(n) O(1)

Insertion in middle O(n) O(n)

Deletion in middle O(n) O(n)

GAURAV BHATIA
Essential Quiz 1 for Topic 2

1. Which of the following statement is true?


i) Using singly linked lists and circular list, it is not possible to traverse the list backwards.
ii) To find the predecessor, it is required to traverse the list from the first node in case of singly
linked list.
A) i-only
B) ii-only
C) Both i and ii
D) None of both

Answer: A

2. The advantage of ...................... is that they solve the problem if sequential storage
representation. But disadvantage in that is they are sequential lists.
A) Lists
B) Linked Lists
C) Trees
D) Queues
Answer: B

3. In a circular linked list

a) Components are all linked together in some sequential manner.


b) There is no beginning and no end.
c) Components are arranged hierarchically.
d) Forward and backward traversal within the list is permitted.

Answer: B

4. A linear collection of data elements where the linear node is given by means of pointer is
called?

a) Linked list
b) Node list
c) Primitive list
d) None

Answer:A

5. Which of the following operations is performed more efficiently by doubly linked list than
by singly linked list?

a) Deleting a node whose location in given


b) Searching of an unsorted list for a given item
c) Inverting a node after the node with given location
d) Traversing a list to process each node

Answer: A
GAURAV BHATIA
Q Consider an implementation of unsorted singly linked list. Suppose it has its representation with a
head and tail pointer. Given the representation, which of the following operation can be
implemented in O(1) time?

i) Insertion at the front of the linked list


ii) Insertion at the end of the linked list
iii) Deletion of the front node of the linked list
iv) Deletion of the last node of the linked list

a) I and II
b) I and III
c) I,II and III
d) I,II and IV

Answer: C

6. Consider an implementation of unsorted singly linked list. Suppose it has its representation
with a head pointer only. Given the representation, which of the following operation can be
implemented in O(1) time?

i) Insertion at the front of the linked list


ii) Insertion at the end of the linked list
iii) Deletion of the front node of the linked list
iv) Deletion of the last node of the linked list

a) I and II
b) I and III
c) I,II and III
d) I,II and IV

Answer: B

7. In linked list each node contain minimum of two fields. One field is data field to store the
data second field is?

a) Pointer to character
b) Pointer to integer
c) Pointer to node
d) Node

Answer:C

8. What would be the asymptotic time complexity to add a node at the end of singly linked
list, if the pointer is initially pointing to the head of the list?

GAURAV BHATIA
a) O(1)
b) O(n)
c) θ (n)
d) θ (1)

Answer:C

9. What would be the asymptotic time complexity to add an element in the linked list?

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

Answer: B

10. What would be the asymptotic time complexity to find an element in the linked list?

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

Answer: B

11. What would be the asymptotic time complexity to insert an element at the second position
in the linked list?

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

Answer: A

12. The concatenation of two list can performed in O(1) time. Which of the following
variation of linked list can be used?

a) Singly linked list


b) Doubly linked list
c) Circular doubly linked list
d) Array implementation of list

Answer: C

GAURAV BHATIA
13. A variant of linked list in which last node of list, points to the first node of the list is?

a) Singly linked list


b) Doubly linked list
c) Circular linked
d) Multiply linked list

Answer: C

14. In doubly linked lists, traversal can be performed?

a) Only in forward direction


b) Only in reverse direction
c) In both directions
d) None

Answer: C

15. What kind of linked list is best to answer question like “What is the item at position n?”

a) Singly linked list


b) Doubly linked list
c) Circular linked list
d) Array implementation of linked list

Answer: D

16. A variation of linked list is circular linked list, in which the last node in the list points to
first node of the list. One problem with this type of list is?

a) It waste memory space since the pointer head already points to the first node and thus the list
node does not need to point to the first node.
b) It is not possible to add a node at the end of the list.
c) It is difficult to traverse the list as the pointer of the last node is now not NULL
d) All of above

Answer: C

17. In circular linked list, insertion of node requires modification of?

a) One pointer
b) Two pointer
c) Three pointer
d) None

Answer: B

GAURAV BHATIA
18. What is the second part of a node in a linked list that contains the address of the next node
called?
A. data
B. pointer
C. element
D. Link
Answer: D

19. Which of the following is NOT a type of linked list?


A) Double ended linked list
B) Double linked list
C) Simple linked list
D) Circular linked list
Answer: A

GAURAV BHATIA
Essential Quiz 2 for Topic 2

1. The time required to delete a node x from a doubly linked list having n nodes is

a. O (n)
b. O (log n)
c. O (1)
d. O (n log n)
Answer:: C

2. 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 above situation
Answer B

3. Linked lists are not suitable to for the implementation of?

a) Insertion sort
b) Radix sort
c) Polynomial manipulation
d) Binary search
Answer : D.

4. Doubly linked list is also called as

a) list

b) two-way linked list

c) skip list

d) none

Answer : B

5. Which linked lists do not have ends?

a) Single linked list

b) doubly linked list

c) circular linked list

d) none Answer : c
GAURAV BHATIA
6. Linked list is generally considered as an example of type of memory allocation.

A. Static

B. Compile time

C. Dynamic

D. None of these

Answer: C

7. Each Node contain minimum two fields one field called data field to store data. Another field is
of type .

A. Pointer to character
B. Pointer to class
C. Pointer to integer
D. Pointer to Node
Answer: D

8. Which of the following statement is not true about the doubly linked list?

a. We can traverse in both the directions.


b. It requires extra space
c. Implementation of doubly linked list is easier than the singly linked list
d. It stores the addresses of the next and the previous node

Answer: c

9. What is the output of following function for start pointing to first node of following linked list?
1->2->3->4->5->6

void fun(struct node* start)


{
if(start == NULL)
return;
printf("%d ", start->data);

if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
A. 1 4 6 6 4 1
B. 1 3 5 1 3 5

GAURAV BHATIA
C. 1 2 3 5
D. 1 3 5 5 3 1
Answer: D

10. Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node
is not given, can we delete the node X from given linked list?

A. Possible if X is not last node


B. Possible if size of linked list is even
C. Possible if size of linked list is odd
D. Possible if X is not first node
Answer: A

11. The situation when in a linked list Head=NULL is

A. underflow
B. Overflow
C. Null linked list
D. saturated
Answer: C

12. Applications of linked list are

A. simulation, event driven systems

B. postfix and prefix manipulations

C. Dictionary systems, polynomial manipulations

D. Fixed block storage allocations, garbage collection

Answer: D

13 Overflow condition in linked list may occur when attempting to

A. Create a node when free space pool is empty


B. Traverse the nodes when free space pool is empty
C. Create a node when linked list is empty
D. None of these
Answer: A

14. Consider a linked list of n elements. What is the time taken to insert an element after element
pointed by same pointer ?

A. O(n)

B. O(log n)
GAURAV BHATIA
C. O(n-1)
D. D.O(1)
E. Answer: D
15. Time require to find any element of the linked list is .

A. O(n)

B. O(1)

C. O(n^2)

D. none of these

Answer: A

16. Consider the below representation and predict what will be printed on the screen by following
statement ?
start->next->data

struct node {

int data;

struct node *next;

}*start = NULL;

A. Access the data field for 3rd node


B. Access the data field for 1st node
C. Access the data field for 2nd node
D. None of these
Answer: C

17. 17.
Consider the following linked list and linked list representation. what will be the value of following
statement ?
start->next->next->next->data

struct node {

int data;

struct node *next;

}*start = NULL;

GAURAV BHATIA
A. 12
B. 30
C. 15
D. 25
Answer: D

18. Consider the following linked list and linked list representation. what will be the value of
following statement ?
start->next->next->datastruct

node {

int data;

struct node *next;

}*start = NULL;

A. 10
B. 5000
C. 5
D. 3000
Answer: C

19. How many nodes will ListSearch visit when searching for 93?

A. 4
B. 3
C. 2

GAURAV BHATIA
D. 1
Answer: B

20. What is value in the head -> next -> next ->next-> data below?

A. 17
B. 93
C. 77
D. 31
Answer: A

GAURAV BHATIA
Topic 3: STACK
STACK

It is an ordered group of homogeneous items of elements. Elements are added to


and removed
from the top of the stack (the most recently added items are at the top of the
stack). The last element to be added is the first to be removed (LIFO: Last In, First
Out).

one end, called TOP of the stack. The elements are removed in reverse order of that in which
they were inserted into the stack.

2.2 STACK
OPERATIONS

These are two basic operations associated with


stack:
• Push() is the term used to insert/add an element into a stack.

. Pop() is the term used to delete/remove an element from a stack.

Other names for stacks are piles and push-down lists.

There are two ways to represent Stack in memory. One is using array and other is using linked
list.

Array representation of stacks:

Usually, the stacks are represented in the computer by a linear array. In the following
algorithms/procedures of pushing and popping an item from the stacks, we have
considered, a linear array STACK, a variable TOP which contain the location of the
top element of the stack; and a variable STACKSIZE which gives the maximum
GAURAV BHATIA
number of elements that can be hold by the stack

Push Operation
Push an item onto the top of the stack (insert an item)

Algorithm for PUSH:

GAURAV BHATIA
Here are the minimal operations we'd need for an abstract stack (and their typical
names):

o Push: Places an element/value on top of the stack.


o Pop: Removes value/element from top of the stack.
o IsEmpty: Reports whether the stack is Empty or not.
o IsFull: Reports whether the stack is Full or not.

APPLICATION OF THE STACK (ARITHMETIC


EXPRESSIONS)

Stacks are used by compilers to help in the process of converting infix to postfix
arithmetic expressions and also evaluating arithmetic expressions. Arithmetic
expressions consisting variables, constants, arithmetic operators and parentheses.
Humans generally write expressions in which the operator is written between the
operands (3 + 4, for example). This is called infix notation. Computers “prefer”
postfix notation in which the operator is written to the right of two operands. The
preceding infix expression would appear in postfix notation as 3 4 +. To evaluate a
complex infix expression, a compiler would first convert the expression to postfix
notation, and then evaluate the postfix version of the expression. We use the
following three levels of precedence for the five binary operations.
112
For example:

(66 + 2) * 5 – 567 / 42
to postfix

66 22 + 5 * 567 42 / –

Transforming Infix Expression into Postfix Expression:

The following algorithm transforms the infix expression Q into its equivalent
postfix expression
P. It uses a stack to temporary hold the operators and left parenthesis. The
postfix expression will be constructed from left to right using operands from
Q and operators popped from STACK.

Convert Q: A+( B * C – ( D / E ^ F ) * G ) * H into postfix form showing


stack status . Now add “)” at the end of expression

A+( B * C – ( D / E ^ F ) * G ) * H )

and also Push a “(“ on Stack.

113
EVALUATION OF POSTFIX EXPRESSION

If P is an arithmetic expression written in postfix notation. This algorithm uses STACK to hold
operands, and evaluate. For example:

Following is an infix arithmetic expression

(5 + 2) * 3 – 9 / 3
And its postfix is:

52+3*93/–

Now add “$” at the end of expression as a sentinel.

114
115
2.6 RECURSION
Recursion is a programming technique that allows the programmer to express operations in

terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive
functions is to imagine them as a process being performed where one of the instructions is to "repeat the
process". This makes it sound very similar to a loop because it repeats the same code, and in some ways, it is
similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the
recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes
be completed without the recursive call. One simpleexample is the idea of building a wall that is ten feet high;
if I want to build a ten-foot-high wall, andthen I will first build a 9-foot-high wall, and then add an extra foot
of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater
than one, first calls itself to build a lower wall, and then adds one a foot of bricks.

A simple example of recursion would be:


void recurse()
{

recurse(); /* Function calls itself */


}

int main()
{

recurse(); /* Sets off the recursion */

return 0;
}
This program will not continue forever, however. The computer keeps function calls on a stack and once too
many are called without ending, the program will crash. Why not write a program to see how many times the
function is called before the program terminates?

Aquick example:
void count_to_ten ( int count )
{

/* we only keep counting if we have a value less than ten if ( count < 10 )
{

116
count_to_ten( count + 1 );

}
}

int main()
{

count_to_ten ( 0 );
}

117
Short Type Question

1. What is a Stack ?
A stack is a non-primitive linear data structure and is an ordered collection of homogeneous data
elements.The other name of stack is Last-in -First-out list.

One of the most useful concepts and frequently used data structure of variable size for problem
solving is the stack.

2. Write down the algorithm for solving Towers of Hanoi problem?


Push parameters and return address on stack.
If the stopping value has been reached then pop the stack to return to previous level else move allexcept
the final disc from starting to intermediate needle.
Move final discs from start to destination needle.
Move remaining discs from intermediate to destination needle.
Return to previous level by popping stack.

3. What are the two operations of Stack?


PUSH
POP

4. What are the postfix and prefix forms of the expression?


A+B*(C-D)/(P-R)
Postfix form: ABCD-*PR-/+
Prefix form: +A/*B-CD-PR

5. Explain the usage of stack in recursive algorithm implementation?


In recursive algorithms, stack data structures are used to store the return address when a recursive
call is encountered and also to store the values of all the parameters essential to the current state of the
procedure.

6. What are applications of stack?


 Conversion of expression
 Evaluation of expression
 Parentheses matching
 Recursion

7. Define recursion?
It is a technique and it can be defined as any function that calls itself is called recursion. There are
some applications which are suitable for only recursion such as, tower of Hanoi, binary tree traversals etc,
can be implementing very easily and efficiently.

118
8. Which data structures are used for BFS and DFS of a graph?
 Queue is used for BFS
 Stack is used for DFS. DFS can also be implemented using recursion (Note that
recursion also uses function call stack).

9. What is the difference between an Array and Stack?


Stack Data Structure:

 Size of the stack keeps on changing as we insert and delete the element
 Stack can store elements of different data type

Array Data Structure:

 Size of the array is fixed at the time of declaration itself


 Array stores elements of similar data type. 

10. Which data structure is ideal to perform recursion operation and why?

Stack is the most ideal for recursion operation. This is mainly because of its LIFO (Last In First Out)
property, it remembers the elements & their positions, so it exactly knows which one to return when a
function is called.

11. What are some of the most important applications of a Stack?


Some of the important applications are given below. Check them out to know the detailed code &
explanation.

 Balanced parenthesis checker


 Redundant braces
 Infix to postfix using a stack
 Infix to prefix using a stack

12. Convert the below given expression to its equivalent Prefix And Postfix notations. ((A +
B) * C - (D - E) ^ (F + G))
Prefix Notation: ^ * +ABC DE + FG Postfix Notation: AB + C * DE FG + ^

13. How many stacks are required to implement a Queue.

2 stacks S1 and S2 ARE REQUIRED.For


Enqueue, perform push on S1.
For Dequeue, if S2 is empty pop all the elements from S1 and push it to S2. The last element youpopped
from S1 is an element to be dequeued. If S2 is not empty, then pop the top element in it.

14. Is it possible to implement 2 stacks in an array?

119
Condition: None of the stack should indicate an overflow until every slot of an array is used.Yes, 2
stacks can be implemented for the given condition
Start 1st stack from left (1st position of an array) and 2nd from right (last position say n). Move 1ststack
towards right(i.e 1,2,3 ...n) and 2nd towards left (i.e n,n-1,n-2...1).

15. Explain why Stack is a recursive data structure


A stack is a recursive data structure, so it's:

 a stack is either empty or


 it consists of a top and the rest which is a stack by itself; 

16. Why and when should I use Stack or Queue data structures instead of Arrays/Lists?
Because they help manage your data in more a particular way than arrays and lists. It means that
when you're debugging a problem, you won't have to wonder if someone randomly inserted an
element into the middle of your list, messing up some invariants.

Arrays and lists are random access. They are very flexible and also easily corruptible. If you want tomanage
your data as FIFO or LIFO it's best to use those, already implemented, collections.

More practically you should:

 Use a queue when you want to get things out in the order that you put them in (FIFO)
 Use a stack when you want to get things out in the reverse order than you put them in (LIFO)
 Use a list when you want to get anything out, regardless of when you put them in (and when
you don't want them to automatically be removed).

17. How to implement Linked List Using Stack?


You can simulate a linked list by using two stacks. One stack is the "list," and the other is used fortemporary
storage.

 To add an item at the head, simply push the item onto the stack.
 To remove from the head, pop from the stack.
 To insert into the middle somewhere, pop items from the "list" stack and push them onto the
temporary stack until you get to your insertion point. Push the new item onto the "list" stack,
then pop from the temporary stack and push back onto the "list" stack. Deletion of an arbitrary
node is similar.

18. Explain the Concept of a Stack. How can you Differentiate it from a Queue?

A stack is a type of linear structure which is used to access components that support the LIFO (LastIn First
Out) method. Push and Pop are key stack functions. Unlike a queue, the arrays and linked lists are used to
enforce a stack.
The element most recently added is removed first in a stack. However, in the event of a queue, theelement
least recently added is removed first.

19. Explain the Steps Involved in the Insertion and Deletion of an Element in the Stack.

120
Algorithms of Stack operations :
Algorithms of PUSH operations-
Step 1: Start
Step 2: Checks if the stack is full if(top==(SIZE-1))
Step 3: If the stack is full, Give a message and exit printf("\nStack Overflow");Step 4:
If the stack is not full, increment top to point next empty space. top=top+1;
Step 5: Add data element to the stack location, where top is pointing.
printf("\nEnter the item to be pushed in stack:"); stack[top]=item; Step 6:
Stop
Algorithms of POP operations :
Step 1: Start
Step 2: Checks if the stack is empty if(top==-1)
Step 3: If the stack is empty, Give a message and exit printf(“\nStack Underflow”);Step 4: If
the stack is not empty, Print the element at which top is pointing. printf("\nPopped element is
: %d\n",stack[top]);
Step 5: Decrement top to point previous location .
top=top-1;
Step 6: Stop

20. Write the stack overflow condition.

Overflow occurs when top = Maxsize -1

21. What is a postfix expression?

An expression in which operators follow the operands is known as postfix expression. The main benefit
of this form is that there is no need to group sub-expressions in parentheses or to consideroperator
precedence.

The expression "a + b" will be represented as "ab+" in postfix notation.

22. What are the drawbacks of array implementation of Stack?

o Memory Wastage: The space of the array, which is used to store stack elements can be
wasted because it is fixed prior to its usage.

121
o Array Size: There might be situations in which, we may need to extend the stack to insert
more elements if we use an array to implement stack, It will almost be impossible to extend
the array size, therefore deciding the correct array size is always a problem in array
implementation of stack.

122
ESSENTIAL QUIZ 1
1) Stack is useful for implementing
(a) Radix sort
(b) Recursion
(c) Breadth first
(d) Depth first

2) The postfix equivalent of the prefix *+ab – cd is


(a) ab + cd- *
(b) abcd +- *
(c) ab + cd* -
(d) ab+- cd*

3) Process of inserting an element in stack is called


a) Create
b) Push
c) Evaluation
d) Pop

4) Process of removing an element from stack is called


a) Create
b) Push

123
c) Evaluation
d) Pop

5) In a stack, if a user tries to remove an element from an empty stack it is called


a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection

6) Pushing an element into stack already having five elements and stack size of 5, then stack
becomes
a) Overflow
b) Crash
c) Underflow
d) User flow

7) Entries in a stack are “ordered”. What is the meaning of this statement?


a) A collection of stacks is sortable
b) Stack entries may be compared with the ‘<‘ operation
c) The entries are stored in a linked list
d) There is a Sequential entry that is one by one

Explanation: In stack data structure, elements are added one by one using push operation. Stackfollows
LIFO Principle i.e. Last In First Out(LIFO).

8) . Which of the following is not the application of stack?


a) A parentheses balancing program
b) Tracking of local variables at run time
c) Compiler Syntax Analyzer
d) Data Transfer between two asynchronous process.

9) Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
The maximum number of parentheses that appear on the stack AT ANY ONE TIME when the
algorithm analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more

Explanation: In the entire parenthesis balancing method when the incoming token is a left parenthesis it is
pushed into stack. A right parenthesis makes pop operation to delete the elements in stack till we get left
parenthesis as top most element. 3 elements are there in stack before right parentheses comes. Therefore,
maximum number of elements in stack at run time is 3.

124
10) What is the value of the postfix expression 6 3 2 4 + – *?
a) 1
b) 40
c) 74
d) -18

11) Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the usual stack
algorithm to convert the expression from infix to postfix notation. The maximum number of
symbols that will appear on the stack AT ONE TIME during the conversion of this expression?
a) 1
b) 2
c) 3
d) 4

12) The postfix form of the expression (A+ B)*(C*D- E)*F / G is?
a) AB+ CD*E – FG /**
b) AB + CD* E – F **G /
c) AB + CD* E – *F *G /
d) AB + CDE * – * F *G /

13) The data structure required to check whether an expression contains a balanced parenthesis is?
a) Stack
b) Queue
c) Array
d) Tree

14) What data structure would you mostly likely see in non recursive implementation of a recursive
algorithm?
a) Linked List
b) Stack
c) Queue
d) Tree

15) The process of accessing data stored in a serial access memory is similar to manipulating data
on a
a) Heap
b) Binary Tree
c) Array
d) Stack

16) The postfix form of A*B+C/D is?


a) *AB/CD+
b) AB*CD/+

125
c) A*BC+/D
d) ABCD+/*

17) Which data structure is needed to convert infix notation to postfix notation?
a) Branch
b) Tree
c) Queue
d) Stack

18) The prefix form of A-B/ (C * D ^ E) is?


a) -/*^ACBDE
b) -ABCD*^DE
c) -A/B*C^DE
d) -A/BC*^DE

19) What is the result of the following operation?


Top (Push (S, X))
a) X
b) X+S
c) S
d) XS

20) The prefix form of an infix expression (p + q) – (r * t) is?


a) + pq – *rt
b) – +pqr * t
c) – +pq * rt
d) – + * pqrt

ESSENTIAL QUIZ 2
1) The result of evaluating the postfix expression 5, 4, 6, +, *, 4, 9, 3, /, +, * is?
a) 600
b) 350
c) 650
d) 588
2) Convert the following infix expressions into its equivalent postfix expressions.
(A + B ⋀D)/(E – F)+G

126
a) (A B D ⋀ + E F – / G +)
b) (A B D +⋀ E F – / G +)
c) (A B D ⋀ + E F/- G +)
d) (A B D E F + ⋀ / – G +)
3) Convert the following Infix expression to Postfix form using a stack.
x + y * z + (p * q + r) * s, Follow usual precedence rule and assume that the expression is
legal.
a) xyz*+pq*r+s*+
b) xyz*+pq*r+s+*
c) xyz+*pq*r+s*+
d) xyzp+**qr+s*+
4) Which of the following statement(s) about stack data structure is/are NOT correct?
a) Linked List are used for implementing Stacks
b) Top of the Stack always contain the new node
c) Stack is the FIFO data structure
d) Null link is present in the last node at the bottom of the stack
5) Consider the following operation performed on a stack of size 5.
Push(1);
Pop();
Push(2);
Push(3);
Pop();
Push(4);
Pop();
Pop();
Push(5);

After the completion of all operation, the number of elements present in stack is?a)1
b)2
c) 3
d) 4

6) Which of the following is not an inherent application of stack?


a) Reversing a string
b) Evaluation of postfix expression
c) Implementation of recursion
d) Job scheduling
7) The type of expression in which operator succeeds its operands is?
a) Infix Expression
b) Prefix Expression
c) Postfix Expression
d) Both Prefix and Postfix Expressions
8) If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, what
is the order of removal?

127
a) ABCD
b) DCBA
c) DCAB
d) ABDC
9) A normal queue, if implemented using an array of size MAX_SIZE, gets full when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
10) Which of the following real-world scenarios would you associate with a stack data structure?
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a counter
c) offer services based on the priority of the customer
d) tatkal Ticket Booking in IRCTC
11) What does ‘stack underflow’ refer to?
a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
12) What is the time complexity of pop() operation when the stack is implemented using an array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
13) Which of the following array position will be occupied by a new element being pushed for a
stack of size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[1]
d) S[0]
14) What happens when you pop from an empty stack while implementing using the Stack ADT in
Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown
15) . Array implementation of Stack is not dynamic, which of the following statements supports
this argument?
a) space allocation for array is fixed and cannot be changed during run-time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation
16) Which of the following array element will return the top-of-the-stack-element for a stack of
size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[N-2]
d) S[N+1]
128
17) What is the best case time complexity of deleting a node in a Singly Linked list?
a) O (n)
b) O (n2)
c) O (nlogn)
d) O (1)
18) Which of the following statements are not correct with respect to Singly Linked List(SLL) and
Doubly Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL and O(1) in DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL
19) Minimum number of queues to implement stack is
a) 3
b) 4
c) 1
d) 2
20) Which one of the following is an application of Stack Data Structure?
a) Managing function Call
b) Stock Span Problem
c) Arithmetic expression evaluation
d) All of the above

ESSENTIAL QUIZ 3

129
1) Minimum number of queues to implement stack is
a) 3
b) 4
c) 1
d) 2
2) What should be done when a left parenthesis '(' is encountered?
a) Ignored
b) Placed in the output
c) Placed onto operator stack
d) Nothing
3) When an operand is read, which of the following is done?
a) Ignored
b) Placed in the output
c) Placed onto operator stack
d) Nothing
4) Which of the following is an infix expression?
a) (a+b)*(c+d)
b) ab+c*
c) +ab*c
d) *ab
5) What is the time complexity of an infix to postfix conversion algorithm?
a) O(nlogn)
b) O(n)
c) O(logn)
d) O(nm)
6) Parentheses are simply ignored in the conversion of infix to postfix expression.
a) True
b) False
c) Depends on question
d) None of these
7) It is easier for a computer to process a postfix expression than an infix expression.
a) False
b) True
8) What is the postfix expression for the infix expression?
a)-ab-c
b) -a-bc
c) -abc-
d)-abc
9) What is the postfix expression for the following infix expression?
a/b^c-d
a) abc^/d-
b) abc/^d-
130
c) ab^c/d-
d) None of these

10) Which of the following statement is incorrect with respect to infix to postfix conversion
algorithm?
a) operand is always placed in the output
b) operator is placed in the stack when the stack operator has lower precedence
c) parenthesis is included in the output
d) higher and equal priority operators follow the same condition

11) In infix to postfix conversion algorithm, the operators are associated from?
a) R to L
b) L to R
c) mid to L
d) mid to R

12) What is the corresponding postfix expression for the given infix expression?
a*(b+c)/d
a) ab*+cd/
b) ab+*cd/
c) abc*+/d
d) abc+*d/

13) What would be the Prefix notation and Postfix notation for the given equation?
a) ++ABC and AB+C+
b) AB+C+ and ++ABC
c) ABC++ and AB+C+
d) ABC+ and ABC+

14) What would be the Prefix notation for the given equation?
a|b&c
a) a|&bc
b) &|abc
c) |a&bc
d) ab&|c

15) Out of the following operators (|, *, +, &, $), the one having lowest priority is

a) +
b) $

131
c) |
d) &

16) Which data structure can be used to test a palindrome?


a) Array
b) Linked List
c) stack
d) heap

17) How many stacks are required for applying evaluation of infix expression
algorithm?
a) 1
b) 2
c) 3
d) 4

18) How many passes does the evaluation of infix expression algorithm makes
through the input?
a) 1
b) 2
c) 3
d) 4

19. Evaluate the following statement using infix evaluation algorithm and choose
the correct answer. 1+2*3-2
a) 3
b) 6
c) 5
d) 4

20. Evaluate the following and choose the correct answer.


a/b+c*d where a=4, b=2, c=2, d=1.
a) 1
b) 4
c) 5
d) 2

132
133

You might also like