data structure
data structure
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that
the last element added to the stack will be the first one to be removed. Think of it like a stack of
plates: you add plates to the top and also remove them from the top.
Here's a simple implementation of a stack in C:
c
#include <stdio.h>
#define MAX 10
int stack[MAX];
int top = -1;
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}
int main() {
push(10);
push(20);
printf("Popped value: %d\n", pop());
return 0;
}
ii) What is Structured Programming?
Structured programming is a programming paradigm aimed at improving the clarity, quality, and
development time of a computer program by making extensive use of subroutines, block structures,
for and while loops, and other constructs. It emphasizes breaking down a program into smaller,
manageable sections or modules, each with a single entry and exit point. This approach helps in
writing clear, understandable, and maintainable code.
iii) What are Primitive and Non-Primitive Data Structures?
Primitive Data Structures: These are the basic data types provided by a programming language.
Examples include integers, floats, characters, and pointers. They are the building blocks for data
manipulation.
Non-Primitive Data Structures: These are more complex data structures that are derived from
primitive data structures. They include arrays, linked lists, stacks, queues, trees, and graphs. Non-
primitive data structures are used to store and manage data in a more sophisticated way.
iv) Differentiate between Linked List and Array
Memory Allocation: Arrays have a fixed size and use contiguous memory locations, while
linked lists are dynamic and use non-contiguous memory locations.
Access Time: Arrays provide O(1) time complexity for accessing elements, whereas linked
lists have O(n) time complexity.
Insertion/Deletion: Inserting or deleting elements in an array is costly (O(n)), while in linked
lists, it is more efficient (O(1) if the pointer is known).
Memory Utilization: Arrays can lead to memory wastage if the allocated space is not fully
utilized, whereas linked lists use memory more efficiently as they grow and shrink
dynamically.
v) Applications of Linked List
Dynamic Memory Allocation: Linked lists are used in scenarios where the size of the data
structure is not known in advance.
Implementation of Data Structures: They are used to implement other data structures like
stacks, queues, and graphs.
Efficient Insertion/Deletion: Useful in applications where frequent insertion and deletion of
elements are required.
Memory Management: Linked lists are used in memory management systems to keep track
of free and used memory blocks.
vi) Differentiate between Recursion and Iteration
Definition: Recursion is a process where a function calls itself, while iteration is a process
where a set of instructions is repeated until a condition is met.
Memory Usage: Recursion uses more memory due to function call stack, whereas iteration
uses less memory.
Performance: Iteration is generally faster and more efficient than recursion.
Complexity: Recursion can lead to simpler and more readable code for problems that have a
recursive nature, while iteration can be more complex but is often more efficient.
vii) Difference between Single Dimension Array and Two Dimension Array
Structure: A single dimension array is a list of elements, whereas a two-dimensional array is
an array of arrays (a matrix).
Access: Elements in a single dimension array are accessed using a single index, while
elements in a two-dimensional array are accessed using two indices.
Usage: Single dimension arrays are used for linear data storage, while two-dimensional
arrays are used for tabular data storage, such as matrices and tables.
viii) Why Underflow Condition Comes in Any Data Structure?
Underflow occurs when an attempt is made to remove an element from an empty data structure.
This can happen in stacks, queues, and other data structures when there are no elements to remove.
It indicates that the data structure is empty and no further removal operations can be performed
until new elements are added.
I hope this helps! If you have any more questions or need further clarification, feel free to ask.
ix) Difference between Constants and Variables
Constants: Constants are fixed values that do not change during the execution of a program.
They are defined using the const keyword in many programming languages. For example,
const int MAX = 100; defines a constant integer with a value of 100.
Variables: Variables are storage locations that can hold different values during the execution
of a program. They are defined using variable declaration syntax, such as int x = 10;. The
value of a variable can be changed throughout the program.
x) Applications of Stack
1. Expression Evaluation: Stacks are used to evaluate expressions (infix, postfix, and prefix). For
example, converting an infix expression (like A + B) to a postfix expression (like AB+) and then
evaluating it using a stack.
2. Backtracking: Stacks are used in algorithms that involve backtracking, such as maze solving
and parsing. For example, in a maze-solving algorithm, the stack can be used to keep track of
the path taken and backtrack when a dead end is reached.
xi) Sequential Search Algorithm
c
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Key found at index i
}
}
return -1; // Key not found
}
xii) Method for Conversion from Infix to Postfix Notation
1. Initialize an empty stack and an empty postfix expression.
2. Scan the infix expression from left to right.
3. If the scanned character is an operand, add it to the postfix expression.
4. If the scanned character is an operator, pop from the stack to the postfix expression until the
stack is empty or the top of the stack has less precedence than the scanned operator. Push
the scanned operator to the stack.
5. If the scanned character is '(', push it to the stack.
6. If the scanned character is ')', pop from the stack to the postfix expression until '(' is
encountered.
7. Pop all the remaining operators from the stack to the postfix expression.
xiii) Explain Pop Operation of Stack. Write an Algorithm of this Operation.
The pop operation removes the top element from the stack.
Algorithm:
1. Check if the stack is empty.
2. If the stack is empty, return an error message.
3. If the stack is not empty, remove the top element and return it.
c
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}
xiv) What is a Tree? What is Height and Path of a Tree? Explain with Example.
A tree is a hierarchical data structure consisting of nodes, with a single node as the root and zero or
more child nodes. Each child node can have zero or more child nodes, and so on.
Height: The height of a tree is the length of the longest path from the root to a leaf node.
Path: A path in a tree is a sequence of nodes from one node to another.
Example:
A
/\
B C
/\ \
D E F
The height of this tree is 2 (A -> B -> D).
A path example is A -> C -> F.
xv) What is Sorting? Write an Algorithm for Insertion Sort
Sorting is the process of arranging data in a specific order, typically in ascending or descending order.
Sorting is a fundamental operation in computer science and is used in various applications such as
searching, data analysis, and database management.
Insertion Sort is a simple and intuitive sorting algorithm that builds the final sorted array one item at
a time. It is much like sorting playing cards in your hands. The algorithm divides the array into a
sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.
Algorithm for Insertion Sort:
1. Start with the second element (index 1) as the key.
2. Compare the key with the elements before it.
3. If the key is smaller than the compared element, shift the compared element one position to
the right.
4. Repeat step 3 until the key is larger than the compared element or you reach the beginning
of the array.
5. Insert the key at the correct position.
6. Move to the next element and repeat steps 2-5 until the entire array is sorted.
Here is the pseudocode for Insertion Sort:
c
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
int main() {
// Start with an empty list
struct Node* head = NULL;
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
In this example, the factorial function calculates the factorial of a number using recursion. The base
case is when n is 0, and the recursive case multiplies n by the factorial of n-1.
Q.33 Explain in Detail Various Operations Associated with Linked List (CO3)
Linked lists are dynamic data structures that consist of nodes. Each node contains data and a
reference (or link) to the next node in the sequence. Here are the primary operations associated with
linked lists:
1. Insertion:
o At the Beginning: Add a new node at the start of the list.
o At the End: Add a new node at the end of the list.
o After a Given Node: Add a new node after a specified node in the list.
2. Deletion:
o From the Beginning: Remove the first node of the list.
o From the End: Remove the last node of the list.
o After a Given Node: Remove a node after a specified node in the list.
3. Traversal: Access each node of the linked list to perform some operation (e.g., printing the
data).
4. Searching: Find a node with a given value.
5. Updating: Change the value of a node.
Q.34 Write a Program in C for Multiplication of Two Matrices (CO1)
Here's a simple C program to multiply two matrices:
c
#include <stdio.h>
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int result[][10], int rowFirst, int
columnFirst, int rowSecond, int columnSecond) {
for (int i = 0; i < rowFirst; ++i) {
for (int j = 0; j < columnSecond; ++j) {
result[i][j] = 0;
for (int k = 0; k < columnFirst; ++k) {
result[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}
int main() {
int firstMatrix[10][10], secondMatrix[10][10], result[10][10];
int rowFirst, columnFirst, rowSecond, columnSecond;
if (columnFirst != rowSecond) {
printf("Error! Column of the first matrix should be equal to row of the second matrix.\n");
return -1;
}
printf("Resultant matrix:\n");
for (int i = 0; i < rowFirst; ++i) {
for (int j = 0; j < columnSecond; ++j) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Q.35 Discuss the Quick Sort Algorithm with an Example (CO6)
Quick Sort is a highly efficient sorting algorithm that uses the divide-and-conquer approach. It works
by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays,
according to whether they are less than or greater than the pivot. The sub-arrays are then sorted
recursively.
Algorithm:
1. Choose a pivot element from the array.
2. Partition the array into two sub-arrays: elements less than the pivot and elements greater
than the pivot.
3. Recursively apply the above steps to the sub-arrays.
4. Combine the sorted sub-arrays and the pivot to get the final sorted array.
Example: Consider the array: [10, 7, 8, 9, 1, 5]
1. Choose the pivot (e.g., 5).
2. Partition the array: [1, 5, 7, 8, 9, 10]
3. Recursively apply quick sort to the sub-arrays [1] and [7, 8, 9, 10].
4. Combine the sorted sub-arrays and the pivot to get the final sorted array: [1, 5, 7, 8, 9, 10].
Q.36 Write Short Note on the Following (CO3)
(a) Doubly Linked List
A doubly linked list is a type of linked list in which each node contains a data part and two pointers:
one pointing to the next node and one pointing to the previous node. This allows traversal of the list
in both directions (forward and backward).
Advantages:
Easier to delete a given node without traversing the list from the head.
Can be traversed in both directions.
Disadvantages:
Requires more memory for the additional pointer.
More complex insertion and deletion operations compared to a singly linked list.
(b) Application of Queues
Queues are used in various applications where elements need to be processed in the order they
arrive. Some common applications include:
CPU Scheduling: Managing processes in an operating system.
Printer Queue: Managing print jobs in a printer.
Breadth-First Search (BFS): Traversing graphs and trees.
Customer Service Systems: Managing customers in a service line.
Q.28 Give inorder, postorder and preorder traversal of the following tree.
To provide the inorder, postorder, and preorder traversal of a binary tree, I need to see the structure
of the tree. Since the tree structure isn't provided in your message, I'll explain the traversal methods
using a sample binary tree:
A
/\
B C
/\ \
D E F
Inorder Traversal (Left, Root, Right)
1. Traverse the left subtree: D B E
2. Visit the root: A
3. Traverse the right subtree: C F
Inorder Traversal: D B E A C F
Postorder Traversal (Left, Right, Root)
1. Traverse the left subtree: D E B
2. Traverse the right subtree: F C
3. Visit the root: A
Postorder Traversal: D E B F C A
Preorder Traversal (Root, Left, Right)
1. Visit the root: A
2. Traverse the left subtree: B D E
3. Traverse the right subtree: C F
Preorder Traversal: A B D E C F
Q.35 Discuss the following terms associated with a tree (CO-5) 1. Path 2. Level 3. Degree of a Node
4. Terminal Node 5. Root Node
Sure, let's discuss these terms associated with a tree:
1. Path
A path in a tree is a sequence of nodes and edges connecting a node with a descendant. The path
length is the number of edges in the path. For example, in the tree below, the path from node A to
node E is A -> B -> E.
2. Level
The level of a node in a tree is the number of edges on the path from the root node to the node. The
root node is at level 0, its children are at level 1, and so on.
3. Degree of a Node
The degree of a node is the number of children it has. For example, in the tree below, node A has a
degree of 2 (children B and C), node B has a degree of 2 (children D and E), and node C has a degree
of 1 (child F).
4. Terminal Node
A terminal node (also known as a leaf node) is a node that does not have any children. It is the end
point of a path. For example, in the tree below, nodes D, E, and F are terminal nodes.
5. Root Node
The root node is the topmost node of a tree. It is the only node in the tree that does not have a
parent. All other nodes are descendants of the root node.
Example Tree:
A
/\
B C
/\ \
D E F
Q.36 List Various Searching Techniques. Compare them and write algorithm of anyone.
Various Searching Techniques
1. Linear Search (Sequential Search):
o Description: Checks each element in the list one by one until the desired element is
found or the list ends.
o Time Complexity: O(n)
o Best Used For: Small or unsorted lists.
2. Binary Search:
o Description: Divides the sorted list into halves to find the desired element. It
repeatedly compares the target value to the middle element of the list.
o Time Complexity: O(log n)
o Best Used For: Large, sorted lists.
3. Jump Search:
o Description: Divides the list into blocks of fixed size and performs a linear search
within the block where the target element may be.
o Time Complexity: O(√n)
o Best Used For: Sorted lists.
4. Interpolation Search:
o Description: An improved variant of binary search that works on the principle of
probing the position of the required value.
o Time Complexity: O(log log n) (average case)
o Best Used For: Uniformly distributed sorted lists.
5. Exponential Search:
o Description: Finds the range where the target element may be and then performs a
binary search within that range.
o Time Complexity: O(log n)
o Best Used For: Large, sorted lists.
Algorithm:
1. Start with the left and right pointers at the beginning and end of the list, respectively.
2. Calculate the middle index.
3. Compare the target value with the middle element.
4. If the target value is equal to the middle element, return the index.
5. If the target value is less than the middle element, move the right pointer to the middle
index - 1.
6. If the target value is greater than the middle element, move the left pointer to the middle
index + 1.
7. Repeat steps 2-6 until the target value is found or the left pointer exceeds the right pointer.
8. If the target value is not found, return -1.
Q.35 Why Stack is known as LIFO? What is the significance of TOPpointer?
Why Stack is Known as LIFO?
A stack is known as a Last In, First Out (LIFO) data structure because the last element added to the
stack is the first one to be removed. This is similar to a stack of plates where you can only add or
remove the top plate. The LIFO principle ensures that the most recently added element is always the
one that is removed first.
Significance of TOP Pointer
The TOP pointer is crucial in the implementation of a stack. It keeps track of the index of the top
element in the stack. Here are its main functions:
1. Insertion (Push Operation): When a new element is added to the stack, the TOP pointer is
incremented, and the new element is placed at the position indicated by the TOP pointer.
2. Deletion (Pop Operation): When an element is removed from the stack, the element at the
position indicated by the TOP pointer is removed, and the TOP pointer is decremented.
3. Access: The TOP pointer allows direct access to the top element of the stack, enabling
efficient push and pop operations.
Example:
c
#include <stdio.h>
#define MAX 10
int stack[MAX];
int top = -1;
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}
int main() {
push(10);
push(20);
printf("Popped value: %d\n", pop());
return 0;
}
In this example, the top pointer is used to manage the stack operations efficiently, ensuring that the
stack follows the LIFO principle.
Q.27 Write the difference between Static and Dynamic Memory allocation.
Difference Between Static and Dynamic Memory Allocation
Static Memory Allocation:
1. Definition: Memory is allocated at compile time before the program runs.
2. Size: The size of the memory block is fixed and cannot be changed during runtime.
3. Lifetime: The memory is allocated for the entire duration of the program.
4. Efficiency: Faster allocation and deallocation since it is done at compile time.
5. Example: Declaring an array with a fixed size.
c
int arr[10]; // Static memory allocation
Dynamic Memory Allocation:
1. Definition: Memory is allocated at runtime as needed.
2. Size: The size of the memory block can be changed during runtime.
3. Lifetime: The memory is allocated and deallocated as needed during the program's
execution.
4. Efficiency: Slower allocation and deallocation since it is done at runtime.
5. Example: Using functions like malloc(), calloc(), realloc(), and free() in C.
c
int *arr = (int*)malloc(10 * sizeof(int)); // Dynamic memory allocation