VTU Exam Question Paper With Solution of 20MCA11 Data Structure With Algorithms July-2021-Neha Agrawal
VTU Exam Question Paper With Solution of 20MCA11 Data Structure With Algorithms July-2021-Neha Agrawal
int top=-1,stack[MAX];
void push(int);
int pop();
void display();
void main()
{
int ch;
while(1) //infinite loop, will end when choice will be 4
{
printf("\n*** Stack Menu ***");
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n\nEnter your choice(1-4):");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter element to push:");
scanf("%d",&val);
push(val);
break;
case 2: printf(“Deleted ite is %d”, pop());
break;
case 3: display();
break;
case 4: exit(0);
if(top==MAX-1)
{
printf("\nStack is full!!");
}
else
{
top=top+1;
stack[top]=item;
}
}
int pop()
{
if(top==-1)
{
printf("\nStack is empty!!");
return 0;
}
else
{
Int i=stack[top]);
top=top-1;
return i;
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nStack is...\n");
for(i=top;i>=0;i--)
printf("%d\n",stack[i]);
}
}
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
Q2a Ans:
Q2b Ans:
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
Q3a Ans:
Sometimes, the best way to solve a problem is by solving a smaller version of the exact
same problem first. Recursion is a technique that solves a problem by solving a smaller
problem of the same type. When you turn this into a program, you end up with functions
that call themselves (recursive functions)
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
Q3 b Ans:
It is an ordered group of homogeneous items of elements.
Queues have two ends:
Elements are added at one end.
Elements are removed from the other end.
The element added first is also removed first (FIFO: First In, First Out).
Definitions: (provided by the user)
MAX_ITEMS: Max number of items that might be on the queue
ItemType: Data type of the items on the queue
Operations
Boolean IsEmpty
Boolean IsFull
Enqueue (ItemType newItem)
Dequeue (ItemType& item)
Procedure for Insertion
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
4. return.
This procedure deletes an element from a queue and assigns it to the variable ITEM.
2. Set ITEM:=QUEUE[FRONT]
4. return
Q4a Ans:
In Circular Queue, the elements of a given queue can be stored efficiently in an array.
Efficient utilization of memory: In the circular queue, there is no wastage of memory as it
uses the unoccupied space, and memory is used properly in a valuable and effective manner
as compared to a linear queue.
#include<stdio.h>
#define max 3
int CQueue[max];
int rear=-1;
int front=-1;
void CQInsert()
{
if((front==(rear+1)%max))
printf("\n Queue is full");
else
{
printf("\n Enter the element to be inserted:\n");
rear=(rear+1)%max;
scanf("%d",&CQueue[rear]);
if(front==-1)
front=0;
}
}
void CQDelete()
{
if(front==-1)
printf("\n Queue is empty");
else
{
/*item=CQueue[front];*/
printf("Deleted item is %d",CQueue[front]);
/*CQueue[front]=NULL;*/
if(front==rear)
front=rear=-1;
else
front=(front+1)%max;
}
void CQDisplay()
{
int i;
if(front==-1)
printf("\n Queue is empty");
else
{
printf("\n The CQ elements are");
for(i=front;i<=rear;i++)
printf("\n%d",CQueue[i]);
if(front>rear)
{
for(i=front;i<max;i++)
printf("\n%d",CQueue[i]);
for(i=0;i<=rear;i++)
printf("\n%d",CQueue[i]);
}
}
void main()
{
int c;
clrscr();
for(;;)
{
======================SAMPLE OUTPUT======================
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice: 1
Enter the element to be inserted: 23
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice: 1
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice:3
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice: 2
Deleted item is 23
Q4 b. Ans:
Priority Queue is an extension of the Queue data structure where each element has a
particular priority associated with it. It is based on the priority value, the elements from the
queue are deleted. dequeue(): This function removes the element with the highest priority
from the queue.
#include<stdio.h>
#include<conio.h>
int arr[10],front=0,rear=-1;
void disp()
{
int i;
if(rear==-1 || front>rear)
printf("\n Queue is empty");
else
for(i=front;i<=rear;i++)
printf("\n%d",arr[i]);
void main()
{
int c;
clrscr();
do
{
printf("\n 1.Insert");
printf("\n 2.Deletion");
printf("\n 3.Display");
printf("\n 4.Exit");
printf("\n Enter the choice:\n");
scanf("%d",&c);
if(c==1)
addq();
else if(c==2)
delq();
else if(c==3)
disp();
else
exit(1);
}while(1);
}
Q5a Ans:
It uses stack for managing the It uses heap for managing the dynamic
3 static allocation of memory allocation of memory
4 It is less efficient It is more efficient
, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.
1. C malloc() method
2. C calloc() method
3. C free() method
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
int* ptr;
int n, i;
n = 5;
if (ptr == NULL) {
exit(0);
}
else {
ptr[i] = i + 1;
n = 10;
ptr[i] = i + 1;
free(ptr);
}
return 0;
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Q 5b. Ans:
#include<stdio.h>
#include<stdlib.h>
struct Link
{
int info;
struct Link* next;
};
typedef struct Link* NODE;
NODE first=NULL;
NODE getnode()
{
NODE ptr;
ptr= (NODE)malloc(sizeof(struct Link));
if (ptr==NULL)
{
printf("Can Not Allocate");
return 0;
}
ptr->next= NULL;
return ptr;
}
void freenode(NODE ptr)
{
free(ptr);
}
void insert_last()
{
NODE ptr;
ptr=getnode();
printf("Enter the element to insert");
scanf("%d",&ptr->info);
if(first==NULL)
first=ptr;
else
{ NODE temp;
temp=first;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
}
void delete_last()
{
NODE ptr,temp,prev;
if(first==NULL)
printf("List is Empty, can not perform deletion");
else if(first->next==NULL)
{
printf("Deleted value is %d", first->info);
free(first);
}
else
{
prev=NULL;
temp=first;
while(temp->next!=NULL)
{
prev=temp;
temp=temp->next;
}
printf("Deleted value is %d", temp->info);
free(temp);
prev->next=NULL;
}
}
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1..Delete from last\n2.Insert at Last\n 3.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insert_last();
break;
case 2:
delete_last();
break;
case 3:
exit(0)
break;
default:
printf("Please enter valid choice..");
}
}
}
Q 6 a Ans:
Arrays store elements in contiguous memory locations, resulting in easily calculable
addresses for the elements stored and this allows a faster access to an element at a specific
index. Linked lists are less rigid in their storage structure and elements are usually not
stored in contiguous locations, hence they need to be stored with additional tags giving a
reference to the next element.
Major differences are listed below:
• Size: Since data can only be stored in contiguous blocks of memory in an array, its size
cannot be altered at runtime due to risk of overwriting over other data. However in a
linked list, each node points to the next one such that data can exist at scattered (non-
contiguous) addresses; this allows for a dynamic size which can change at runtime.
• Memory allocation: For arrays at compile time and at runtime for linked lists. but,
dynamically allocated array also allocates memory at runtime.
• Memory efficiency: For the same number of elements, linked lists use more memory as
a reference to the next node is also stored along with the data. However, size flexibility
in linked lists may make them use less memory overall; this is useful when there is
uncertainty about size or there are large variations in the size of data elements; memory
equivalent to the upper limit on the size has to be allocated (even if not all of it is being
used) while using arrays, whereas linked lists can increase their sizes step-by-step
proportionately to the amount of data.
• Execution time: Any element in an array can be directly accessed with its index; however
in case of a linked list, all the previous elements must be traversed to reach any element.
Also, better cache locality in arrays (due to contiguous memory allocation) can
significantly improve performance. As a result, some operations (such as modifying a
certain element) are faster in arrays, while some other (such as inserting/deleting an
element in the data) are faster in linked lists.
Following are the points in favour of Linked Lists.
(1) The size of the arrays is fixed: So we must know the upper limit on the number of elements
in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of
the usage, and in practical uses, the upper limit is rarely reached.
Q6 b Ans:
1. Check for the underflow condition: The underflow condition occurs when we
try to pop from an already empty stack. The stack will be empty if the head
pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the elements are popped only
from one end, therefore, the value stored in the head pointer must be deleted
and the node must be freed. The next node of the head node now becomes
the head node.
Time Complexity: o (n)
Q 7 a. Ans:
A function t(n) is said to be in O(g(n)), denoted as t(n) O(g(n)), if t(n) is bounded above by some
constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some
nonnegative integer n0 such that
A function t(n) is said to be in Ω(g(n)), denoted as t(n) Ω(g(n)), if t(n) is bounded below by some
positive constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some
nonnegative integer n0 such that
A function t(n) is said to be in (g(n)), denoted as t(n) (g(n)), if t(n) is bounded both above and
below by some positive constant multiples of g(n) for all large n, i.e., if there exist some positive
constant c1 and c2 and some nonnegative integer n0 such that
Similarly after the second iteration, 5 will be at the second last index,
and so on.
In Bubble Sort, n-1 comparisons will be done in the 1st pass, n-2 in
2nd pass, n-3 in 3rd pass and so on. So the total number of
comparisons will be,
(n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1
Sum = n(n-1)/2
i.e O(n2)
Also, the best case time complexity will be O(n), it is when the list
is already sorted.
Q9b Ans:
String Matching –Program
The simplest algorithm for string matching is a brute force algorithm, where we simply try to match
the first character of the pattern with the first character of the text, and if we succeed, try to match
the second character, and so on; if we hit a failure point, slide the pattern over one character and try
again. When we find a match, return its starting location. Java code for the brute force method:
int j = 0;
{ j++; }
if (j == m) return i;
return -1;
The outer loop is executed at most n-m+1 times, and the inner loop m times, for each iteration of
the outer loop. Therefore, the running time of this algorithm is in O(nm).
#include <stdio.h>
#include<string.h>
for(i=0;i<strlen(s)-strlen(p);i++)
j=0;
j=j+1;
if (j==strlen(p))
return i;
return -1;
int main()
int i;
printf("Enter String");
scanf("%s", s);
printf("Enter pattern");
scanf("%s", p);
i= SM(s,p);
if(i==-1)
else
return 0;
}
Q10 a Ans:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part at the left end and
the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is
the entire list.
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in
a linear manner.
We find that 14 is the second lowest value in the list and it should appear at the
second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted
manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
This algorithm is not suitable for large data sets as its average and worst case complexities
are of Ο(n2), where n is the number of items.
Q10 b Ans:
Depth first search (DFS) algorithm starts with the initial node of the graph G, and then
goes to deeper and deeper until we find the goal node or the node which has no
children. The algorithm, then backtracks from the dead end towards the most recent
node that is yet to be completely unexplored.
The data structure which is being used in DFS is stack. The process is similar to BFS
algorithm. In DFS, the edges that leads to an unvisited node are called discovery edges
while the edges that leads to an already visited node are called block edges.
Algorithm
o Step 1: SET STATUS = 1 (ready state) for each node in G
o Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
o Step 3: Repeat Steps 4 and 5 until STACK is empty
o Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
o Step 5: Push on the stack all the neighbours of N that are in the ready state (whose
STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
o Step 6: EXIT
Tracing of Example
cd b a e f g