You are on page 1of 32

QUESTIONS & ANSWERS of DATA STRUCTURE in C

{3rd SEM}

1. Define Data Structure –


A Data Structure is a data organization, management and storage
format that enables efficient access and modification. It mainly
specifies four things :

• Organization of data
• Accessing methods
• Degree of associability
• Process alternatives for information

2. List out derived data types in c –

Data types are declarations for variables. This determines the type
and size of data associated with variables. Different types are
mentioned below.

Derived data types are used to store complex and huge amount of
data, they include :
• Array
• Structure
• Union
• Pointer

3. What is meant by indexed variable in linear array –

An index maps the array value to a stored object, it is also called as


subscripts. There are 3 ways in which the element of an array can be
stored
• zero-based indexing
• one-based indexing
• n-based indexing
Types of array are indexed arrays, multidimensional arrays, and
associative arrays.
 Indexed arrays store a series of one or more values.
 A multi-dimensional array is an array with more than one level
or dimension (2-d, 3-d etc..)
 An Associative array, which is like an object, is made of
unordered keys and values. Associative arrays use keys instead
of a numeric index to organize stored values.

4. How to represent two-way linked list –

1- Create a new node. allocate memory for newNode and assign the
value A to it.
2- Set prev and next pointers of new node point next of A to the B of
the doubly linked list (As shown in the above figure).
3- Make new node as head node. Point prev of the first node to A
(now the Head is A and the second node is B)
5. Define polish notation –

Polish notation is a notation form for expressing arithmetic, logic and


algebraic equations. Polish notation is also known as prefix notation.
In this notation, operator is prefixed to operands, i.e. operator is
written ahead of operands. For example, +ab. This is equivalent to its
infix notation a + b.

6. Convert the following expression to prefix –

[a] ( ( c-b )/d ) - ( ( e+f )*g )


Ans: -/-cbd*+efg {prefix exp}
[b] 24/6 - 3*7 – 6 + 10/2
Ans: --/246*37+6/102 {prefix exp}

7. What is meant by degree of a node? Write example –

The degree of node is the number of connections it has to other nodes


in the network.

Here root node A has a degree of 2 And node B-0 , C-2

8. Clarify whether Linked List is linear or Non-linear data structure –


Linked List are linear data type because they can have only one
descendant at any node. Unlike trees and Graphs which can have one
or more child(nodes) connected to a given node.

9. What is weighted graph? Explain –

A weighted graph refers to one where weights are assigned to each


edges. It can be represented in two ways directed and undirected
format. Example is given below:

TOTAL WEIGHT = 17

10. How to define the data structure of a non-weighted graph –

A Graph is a non-linear data structure consisting of nodes and edges.


The nodes are sometimes also referred to as vertices and the edges
are lines or arcs that connect any two nodes in the graph. More
formally a Graph can be defined as;
[A Graph consists of a finite set of vertices(or nodes) and set of Edges
which connect a pair of nodes. ]

11. Briefly describe the notation of the space time trade off of algorithm;

A space-time or time-memory tradeoff is a way of solving a problem


or calculation in less time by using more storage space (or
memory), or by solving a problem in very little space by spending a
long time. For example - Storing only the source and rendering it as
an image everytime the page is requested would be trading time
for space. More time used but less space , Larger code size can be
traded for higher program speed when applying loop unrolling , A
space–time tradeoff can be applied to the problem of data storage.

12. List out the applications of Data Structure –


There’s a vast kind of applications under different data types. Some
of them are listed below ; Application of Array:

• Online ticket booking.


• Contacts on a cell phone.
Applications of Linked lists:

• Used for dynamic memory allocation.


• Doubly linked list can be used in navigation systems.
Applications Stack :

• Converting infix to postfix expressions.


• Undo/Redo button/operation in word processors.
Applications of Trees:

• To search an element in a set quickly


• Compiler use a syntax tree to parse program you write.
Applications of Queues:

• Handling website traffic.


• Routers and switches in networking.
• Maintaining the playlist in media players.
Applications of Graphs:

• Finding shortest path.


• Airline network.
• Social networks.
13. What will happen in a C program when you assign a value to an array
element whose subscripts exceed the size of array? Explain with
example –

The compiler will give an error because the program will crash if
some important data gets overwritten. Example;
#include<stdio.h>
int main()
{
int arr[2]=[1,2,5,6] //we can only store 3 values
printf("%d",arr[2]);
return 0;
}

14. Write an algorithm to perform insertion operation in queue –

Step 1 − Check if the queue is full.


Step 2 − If the queue is full, produce overflow error and exit. Step 3
− If the queue is not full, increment rear pointer to point the next
empty space
Step 4 − Add data element to the queue location, where the rear is
pointing.
Step 5 − return success.

15. What is priority queue –

A priority queue is a special type of queue in which each element is


associated with a priority and is served according to its priority. The
priority of the elements in a priority queue determines the order in
which elements are removed from the priority queue. Therefore all
the elements are either arranged in an ascending or descending
order.
16. Convert Prefix notation to expression tree : *++abc++def

*
+ + + +

a b b c d e e f

17. Program to sort a list in ascending order using bubble sort –

// C program for implementation of Bubble sort


#include <stdio.h>

void swap(int* xp, int* yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already in place


for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]); }

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
} int
main()
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

18. How the depth first traversal works ? Explain –

Depth first Search or Depth first traversal is a recursive algorithm


for searching all the vertices of a graph or tree data structure.
Traversal means visiting all the nodes of a graph.
DFS Algorithm in C is a Graph Traversal Technique, also known as
Depth first Search Algorithm, where user traverses with initial node
of the graph, and then gets deeper until user finds the required node
or node which has no children.

19. Different string operations –

strcpy() -Function copies string2, including the ending null character,


to the location that is specified by string1. Example is given below :

int main() {
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);

puts(str2); // C programming

return 0;
}
OUTPUT  “ C programming “

strcmp()- Compares two character strings ( str1 and str2 ) using the
standard EBCDIC collating sequence.
Eg;
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
OUTPUT  ” strcmp(str1, str2) = 1
strcmp(str1, str3) = 0 “

strlen()- Function determines the length of string excluding the


ending null character replace()- Method returns a new string with
the value(s) replaced.
Eg;
int main()
{
char a[20]="Program";
// using the %zu format specifier to print size_t
printf("Length of string a = %zu \n",strlen(a));
return 0;
}
OUTPUT  “ Length of string a = 7 “

toUpper()- Function is used to convert lowercase alphabet to


uppercase
Eg;
int main()
{
char ch;
ch = 'g';
printf("%c in uppercase is represented as %c",
ch, toupper(ch));
return 0;
}
OUTPUT  “g in uppercase is represented as G”

toLower()- Function is used to convert uppercase alphabet to


lowercase
Eg;
int main()
{
char c=’M’, result;
result = tolower(c);
printf("tolower(%c) = %c\n", c, result);
return 0;
}
OUTPUT  “ tolower(M) = m “

20. Explain different categories of Data Structure – {{A little lengthier}}

Data structures are generally classified into primitive and


nonprimitive data structures.

Primitive data structures :


- Primitive data types are predefined types of data
- Basic data structures that cannot be further divided is called
primitive data structures.
➢ It includes int, float, char, bool data types

Non primitive data structures :


Data structures that can be used for other complex storages are
called non-primitive data structures.
Non-primitive data structures are again classified as linear {A data
structure is said to be linear if its elements form a sequence}and
nonlinear data types {A non-linear data structure is one in which its
elements are not arranged in sequence.}

EXPLANATION ABOUT WHOLE CATOGORY


BECAUSE THIS is IMP :-
Arrays
A linear array or a one-dimensional array is the simplest type of data
structure. It is a list of a finite numbers.
{a_1, a_2, …, a_n}
{A(1), A(2), …, A(n)}

A two-dimensional array is a collection of similar data elements where


each element is referenced by two subscripts.
{a_{11}, a_{12}, …, a_{mn}}
2d array

Linked lists
A linked list is a collection of data elements whose order is not given by
their physical location in memory. It consists of nodes that contain data
and link to the next node. The structure allows easiness in insertion and
deletion operations. The last nodes are linked to NULL and signify the
end of the list.
Stack
Stack, LIFO(Last In First Out) system, is a linear data structure in which
insertion(PUSH) and deletion(POP) are restricted to one endpoint called
TOP.

Queue
A queue is a FIFO(First In First Out) system, in which insertion(ENQUEUE)
can take place only at an end called REAR and deletion(DEQUEUE) can
take place only at another end called FRONT.

Trees
Some data contains a hierarchical relationship between various
elements. These data are represented in the form of a Rooted tree
graph or simply Tree. Here node A is called the root of the tree.
Graphs
Sometimes data contain relationships that are not hierarchical in nature.
This type of relationship can be expressed in the form of a graph data
structure.

21. Write an algorithm to insert an element in linear linked list –

Step 1: IF PTR = NULL


Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR → NEXT
Step 4: SET NEW_NODE → DATA = VAL
Step 5: SET NEW_NODE → NEXT = HEAD
Step 6: SET HEAD = NEW_NODE Step
7: EXIT

22. Write a program to delete more than one element from


onedimensional array , use user-defined functions

#include <stdio.h>
#define MAX 100

int main()
{
int arr[MAX], n, i, j;
int num, countDel;

printf("Enter total number of elements: ");


scanf("%d", &n);

//read array elements


printf("Enter array elements:\n");
for (i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
}

printf("\nEnter number (element) to delete: ");


scanf("%d", &num);

//delete elements
countDel = 0; for (i
= 0; i < n; i++) { if
(arr[i] == num) {
countDel++;
//shift all other elements up
for (j = i; j < n; j++) {
arr[j] = arr[j + 1];
}
}
}
if (countDel)
printf("%d found %d times and deleted successfully.", num,
countDel);
else
printf("%d not found.", num);

printf("\nArray elements after deleting %d.\n", num);


for (i = 0; i < (n - countDel); i++)
{ printf("%d\n", arr[i]);
}
return 0;
}

23. What are circular queues ? Write down functions for deleting
elements from a circular queue implemented using array.

A circular queue is the extended version of a regular queue where the


last element is connected to the first element. Thus forming a circle-
like structure. The circular queue solves the major limitation of the
normal queue. In a normal queue, after a bit of insertion and
deletion, there will be non-usable empty space.
➢ deQueue() This function is used to delete an element from the
circular queue. In a circular queue, the element is always
deleted from front position.

24. What is singly linked list? Program to insert and search in SLL

A singly linked list is a type of linked list that is unidirectional, that is,
it can be traversed in only one direction from head to the last node
(tail).

#include<stdio.h>
#include<stdlib.h>
void create(int); void
search();
struct node
{
int data; struct
node *next;
};
struct node *head;
void main ()
{
int choice,item,loc;
do
{
printf("\n1.Create\n2.Search\n3.Exit\n4.Enter your choice?");
scanf("%d",&choice);
switch(choice)

{ case
1:
printf("\nEnter the item\n");
scanf("%d",&item);
create(item); break;
case 2: search();
case 3: exit(0);
break; default:
printf("\nPlease enter valid choice\n");
}

}while(choice != 3);
}
void create(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else {
ptr->data = item;
ptr->next = head; head
= ptr;
printf("\nNode inserted\n");
}

}
void search()
{
struct node *ptr;
int item,i=0,flag; ptr
= head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0; } else
{ flag=1;
}
i++;
ptr = ptr -> next;
}

if(flag==1)
{
printf("Item not found\n");
}

}
25. What are binary trees? Explain how it is represented in memory

A binary tree is a special type of tree data structure in which every


node can have a maximum of 2 children. One is known as a left child
and the other is known as right child. A tree in which every node can
have a maximum of two children is called Binary Tree.

➢ Binary trees in linked representation are stored in the memory


as linked lists. These lists have nodes that aren't stored at
adjacent or neighboring memory locations and are linked to
each other through the parent-child relationship associated
with trees.

26. Program to sort a list of numbers using selection –

#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n); printf("Enter %d
Numbersn", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i]; a[i]=a[position];
a[position=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]); return
0;
}

27. Compare binary search and linear search

A linear search scans one item at a time, without jumping to any item

➢ The worst case complexity is O(n), sometimes known an O(n)


search
➢ Time taken to search elements keep increasing as the number
of elements are increased.
A binary search however, cut down your search to half as soon as you
find middle of a sorted list.

➢ The middle element is looked to check if it is greater than or


less than the value to be searched.
➢ Accordingly, search is done to either half of the given list

28. Write a pattern matching algorithm with example –


(a)
Algorithm :
1. SET K=1 and MAX=S-R+1.
2. Repeat Step 3 to 5 while K<=MAX:
3. Repeat for L=1 to R:
If TEXT[K+L-1] ≠ PAT[L], then: Go to Step 5.
4. SET INDEX=K, and EXIT.
5. K=K+1.
6. SET INDEX=0.
7. Exit.
Example:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10

Input: txt[] = "AABAACAADAABAABA"


pat[] = "AABA"
Output: Pattern found at index 0 Pattern
found at index 9
Pattern found at index 12
(b) Program to add two sparse matrix
#include<stdio.h>
int main()
{
int
i,j,n,c1=1,c2=1,count=1,a[10][10],b[10][10],s[20][20],t[20][20],sum[50][5
0],last[10][10];
printf("\nEnter dimension:");
scanf("%d",&n);
printf("\nEnter elements of 1st matrix:");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
printf("\nEnter elements of 2nd matrix:");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&b[i][j]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if (a[i]
[j]==0)
continue;
else {
s[c1][1]=i;
s[c1][2]=j; s[c1]
[3]=a[i][j]; c1++;

}
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{ if (b[i]
[j]==0)
continue; else
{ t[c2][1]=i;
t[c2][2]=j;
t[c2][3]=b[i][j];
c2++;
}
}
}
printf("\nThe sparse matrix form of A is:\n");
for(i=1;i<c1;i++)
{
for(j=1;j<=3;j++) printf("%d\
t",s[i][j]); printf("\n");

}
printf("\nThe sparse matrix form of B is:\n");
for(i=1;i<c2;i++)
{
for(j=1;j<=3;j++) printf("%d\
t",t[i][j]); printf("\n");
}

for(i=1;i<c1;i++)
{ for(j=1;j<c2;j+
+)
{
if ((s[i][1]==t[j][1])&&(s[i][2]==t[j][2]))
{
sum[count][1]=s[i][1];
sum[count][2]=s[i][2];
sum[count][3]=s[i][3]+t[j][3];
s[i][3]=0; t[j][3]=0;
count++;
}
}
}
for(i=1;i<c1;i++)
{ if(s[i][3]!
=0)
{
sum[count][1]=s[i][1];
sum[count][2]=s[i][2];
sum[count][3]=s[i][3]; count+
+;
}
for(i=1;i<c2;i++)
{ if(t[i][3]!
=0)
{
sum[count][1]=t[i][1];
sum[count][2]=t[i][2];
sum[count][3]=t[i][3]; count+
+;
}
}
printf("\nThe sparse matrix form of sum is:\n");
for(i=1;i<count;i++)
{
for(j=1;j<=3;j++) printf("%d\
t",sum[i][j]); printf("\n");
}

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
last[i][j]=0;
}
for(i=1;i<count;i++)
{
last[sum[i][1]][sum[i][2]]=sum[i][3];
}
printf("\nSum is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++) printf("%d\
t",last[i][j]); printf("\n");
}
}

29. (a) Define circular linked list. Write algorithm to insert elements at
the middle of a circular linked list

Algorithm
Define a Node class which represents a node in the list. It has two
properties data and next which will point to the next node.
Define another class for creating the circular linked list and it has two
nodes: head and tail. Variable size stores the size of the list. It has two
methods: addInMid() and display() .
addInMid() will add the node to the middle of the list:
It first checks whether the head is null (empty list), then it will insert the
node as the head.
Both head and tail will point to the newly added node.
If the list is not empty, then we calculate size and divide it by 2 to get the
mid-point.
Define node temp that will point to head and current will point to a
node previous to temp.
Iterate through the list until the middle of the list is reached by
incrementing temp to temp.next.
The new node will be inserted after current and before temp such that
current will point to the new node and the new node will point to temp.
display() will show all the nodes present in the list.
Define a new node 'current' that will point to the head.
Print current.data till current will points to head again.
Current will point to the next node in the list in each iteration.

(b) Different application of tree ?


Store hierarchical data, like folder structure, organization structure,
XML/HTML data.

30. What is insertion sort? Write a program using quicksort

Insertion sort is a simple sorting algorithm that builds the final sorted
array one item at a time. It is much less efficient on large lists than
more advanced algorithms such as quicksort, heapsort, or merge
sort.
PROGRAM
// Quick sort in C

#include <stdio.h>

// function to swap elements


void swap(int *a, int *b)
{ int t = *a; *a = *b;
*b = t;
}

// function to find the partition position int


partition(int array[], int low, int high) {

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);
// traverse each element of the array
// compare them with the pivot for
(int j = low; j < high; j++) { if (array[j]
<= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i i++;

// swap element at i with element at j


swap(&array[i], &array[j]);
}
}

// swap the pivot element with the greater element at i


swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high)


{ if (low < high) {

// find the pivot element such that


// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


void printArray(int array[], int size)
{ for (int i = 0; i < size; ++i)
{ printf("%d ", array[i]);
}
printf("\n");
}

// main function int main()


{ int data[] = {8, 7, 2, 1, 0, 9,
6};

int n = sizeof(data) / sizeof(data[0]);


printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}

31. (a) Explain different traversal method in binary search tree –

Tree Traversal algorithms can be classified broadly in two categories:


Depth-First Search (DFS) Algorithms. Breadth-First Search (BFS)
Algorithms.

Depth First Search (DFS)

The algorithm begins at the root node and then it explores each
branch before backtracking. It is implemented using stacks. Often
while writing the code, we use recursion stacks to backtrack. By using
recursion we are able to take advantage of the fact that left and right
subtrees are also trees and share the same properties.

For Binary trees, there are three types of DFS traversals.

- In-Order
- Pre-Order
- Post-Order
Breadth-First Search (BFS)

This algorithm also begins at the root node and then visits all nodes
level by level. That means after the root, it traverses all the direct
children of the root. After all direct children of the root are traversed,
it moves to their children and so on. To implement BFS we use a
queue.
(b) Explain the algorithm of evaluating postfix expression

Step 1: If a character is an operand push it to Stack


Step 2: If the character is an operator Pop two
elements from the Stack.
Operate on these elements according to the operator, and push the
result back to the Stack
Step 3: Step 1 and 2 will be repeated until the end has reached.
Step 4: The Result is stored at the top of the Stack, return it
Step 5: End

32. (a) Define Hashing. Explain the different hash functions –

Hashing in the data structure is a technique of mapping a large chunk


of data into small tables using a hashing function. It is also known as
the message digest function. It is a technique that uniquely identifies
a specific item from a collection of similar items.

Different hash functions:

➢ Division Method.
➢ Mid Square Method.
➢ Folding Method.
➢ Multiplication Method.

(b) Binary Search tree :


Binary Search Tree is a node-based binary tree data structure
which has the following properties:

➢ The left subtree of a node contains only nodes with keys


lesser than the node’s key.
➢ The right subtree of a node contains only nodes with keys
greater than the node’s key.
➢ The left and right subtree each must also be a binary search
tree

(b.1) Algorithm to find an element from an array of elements ;


Algorithm
Step 1- Start
Step 2- Iterate the array using the loop.
Step 3- Check whether the given key present in the array i.e. arr[i]
== key.
Step 4- If yes,
print "Search Found".
Step 5- Else
print "Search Not Found".
Step 6- Stop

You might also like