0% found this document useful (0 votes)
17 views79 pages

Dsa Model 1 With Answer

Uploaded by

ruprdm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views79 pages

Dsa Model 1 With Answer

Uploaded by

ruprdm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

1. A server process uses a stack to temporarily store incoming requests.

The stack has a fixed size,


and the system needs to check whether the stack is full to avoid any overflow errors when adding
new requests.Write a C program to check a stack is full or not using an array
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 10
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
void initializeStack(Stack* stack) {
stack->top = -1; // Set the top to -1 to indicate the stack is empty
}
bool isStackFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
bool push(Stack* stack, int value) {
if (isStackFull(stack)) {
printf("Stack is full. Cannot push %d.\n", value);
return false;
}
stack->items[++stack->top] = value; // Increment top and add value to stack
printf("%d pushed onto the stack.\n", value);
return true;
}
void displayStack(Stack* stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->items[i]);
}
printf("\n");
}
int main() {
Stack stack;
initializeStack(&stack);
for (int i = 1; i <= 12; i++) { // Attempt to push 12 elements
push(&stack, i);
}
displayStack(&stack);

return 0;
}
2. A task manager uses a linked list to store user tasks. A new task is added at the beginning of the
list for immediate execution, and the list needs to be updated.Write a function to insert a node at
the beginning of a linked list.
Linked List: 11 7 3
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

Node* insertAtBeginning(Node* head, int newData) {


Node* newNode = createNode(newData); // Create a new node
newNode->next = head; // Point the new node to the current head
return newNode; // Return the new head of the list
}
void printList(Node* head) {
printf("Linked List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = createNode(11);
head->next = createNode(7);
head->next->next = createNode(3);
printf("Original ");
printList(head);
int newTask = 5; // New task to add
head = insertAtBeginning(head, newTask);
printf("After inserting %d at the beginning: ", newTask);
printList(head);
while (head != NULL) {
Node* temp = head;
head = head->next;
free(temp);
}
return 0;
}
3. A classroom management system stores student roll numbers in an array. The program collects
the roll numbers for 8 students and displays them in the order of input.Create a C program that
involves an integer array to store roll numbers, takes input for 8 roll numbers, and prints them.
#include <stdio.h>
#define STUDENT_COUNT 8 // Number of students
int main() {
int rollNumbers[STUDENT_COUNT]; // Array to store roll numbers
printf("Enter the roll numbers of %d students:\n", STUDENT_COUNT);
for (int i = 0; i < STUDENT_COUNT; i++) {
printf("Roll number %d: ", i + 1);
scanf("%d", &rollNumbers[i]);
}
printf("\nRoll numbers in the order of input:\n");
for (int i = 0; i < STUDENT_COUNT; i++) {
printf("%d ", rollNumbers[i]);
}
printf("\n");

return 0;
}
4. A library system uses a linked list to track borrowed books. The program counts the number of
books currently borrowed, stored as nodes in the linked list.Write a Cprogram to count the
number of nodes in a linked list
Number of nodes: 1
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char bookName[50];
struct Node* next;
} Node;
Node* createNode(char* bookName) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
snprintf(newNode->bookName, sizeof(newNode->bookName), "%s", bookName);
newNode->next = NULL;
return newNode;
}
int countNodes(Node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
int main() {
Node* head = createNode("Introduction to C Programming");
printf("Number of nodes: %d\n", countNodes(head));
free(head);
return 0;
}

5. A code editor needs to verify if a user's mathematical expression contains properly balanced
parentheses. The program checks the expression using a stack to ensure all parentheses
match.Design a C program to check for balanced parentheses using a stack.
Enter an expression: (j + k) * (l – m)
Balanced
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
void initializeStack(Stack* stack) {
stack->top = -1;
}
bool isStackEmpty(Stack* stack) {
return stack->top == -1;
}
bool isStackFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
bool push(Stack* stack, char value) {
if (isStackFull(stack)) {
printf("Error: Stack overflow while pushing '%c'\n", value);
return false;
}
stack->items[++stack->top] = value;
return true;
}
char pop(Stack* stack) {
if (isStackEmpty(stack)) {
printf("Error: Stack underflow while popping\n");
return '\0';
}
return stack->items[stack->top--];
}
bool isMatchingPair(char opening, char closing) {
return (opening == '(' && closing == ')') ||
(opening == '{' && closing == '}') ||
(opening == '[' && closing == ']');
}
bool areParenthesesBalanced(char* expression) {
Stack stack;
initializeStack(&stack);
for (int i = 0; expression[i] != '\0'; i++) {
char currentChar = expression[i];
if (currentChar == '(' || currentChar == '{' || currentChar == '[') {
if (!push(&stack, currentChar)) {
return false; // Stop if push fails
}
}
else if (currentChar == ')' || currentChar == '}' || currentChar == ']') {
if (isStackEmpty(&stack)) {
return false; // Unmatched closing parenthesis
}
char topChar = pop(&stack);
if (!isMatchingPair(topChar, currentChar)) {
return false; // Mismatched parentheses
}
}
}
return isStackEmpty(&stack);
}
int main() {
char expression[MAX_SIZE];

printf("Enter an expression: ");


if (!fgets(expression, MAX_SIZE, stdin)) {
printf("Error reading input\n");
return 1;
}
expression[strcspn(expression, "\n")] = '\0'; // Remove newline character
if (areParenthesesBalanced(expression)) {
printf("Balanced\n");
} else {
printf("Not Balanced\n");
}
return 0;
}
6. A print queue uses an array to store print jobs. The program enqueues new print jobs and
dequeues completed jobs as the printer processes each request.Design a C program to implement
a simple queue using an array
Enqueue: 3 ,Enqueue: 7, Enqueue: 10 , Dequeue: 3Enqueue: 5, Dequeue: 7

#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 100 // Define maximum queue size

// Define the queue structure


typedef struct {
int items[MAX_SIZE];
int front;
int rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue* queue) {
queue->front = -1;
queue->rear = -1;
}

// Function to check if the queue is empty


bool isQueueEmpty(Queue* queue) {
return queue->front == -1;
}

// Function to check if the queue is full


bool isQueueFull(Queue* queue) {
return queue->rear == MAX_SIZE - 1;
}

// Function to enqueue (add) an item to the queue


bool enqueue(Queue* queue, int value) {
if (isQueueFull(queue)) {
printf("Queue is full. Cannot enqueue %d.\n", value);
return false;
}
if (isQueueEmpty(queue)) {
queue->front = 0;
}
queue->rear++;
queue->items[queue->rear] = value;
printf("Enqueued: %d\n", value);
return true;
}

// Function to dequeue (remove) an item from the queue


int dequeue(Queue* queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1; // Return -1 to indicate failure
}
int value = queue->items[queue->front];
if (queue->front == queue->rear) { // Queue becomes empty
queue->front = -1;
queue->rear = -1;
} else {
queue->front++;
}
printf("Dequeued: %d\n", value);
return value;
}

// Function to display the current queue


void displayQueue(Queue* queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d ", queue->items[i]);
}
printf("\n");
}

// Main function
int main() {
Queue queue;
initializeQueue(&queue);
// Enqueue and dequeue operations
enqueue(&queue, 3);
enqueue(&queue, 7);
enqueue(&queue, 10);
displayQueue(&queue);
dequeue(&queue);
displayQueue(&queue);
enqueue(&queue, 5);
displayQueue(&queue);
dequeue(&queue);
displayQueue(&queue);

return 0;
}

7. A student registration system needs to manage a list of student IDs for a course. The program
collects and displays the student IDs in the order they are entered into the list
Write a program in C to create and display a Singly Linked List.

Test Data :
Input the number of nodes : 3
Input data for node 1 : 5
Input data for node 2 : 6
Input data for node 3 : 7
Expected Output :
Data entered in the list :
Data = 5 ,Data = 6 , Data = 7

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node in the linked list


typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a linked list


Node* createLinkedList(int n) {
if (n <= 0) {
return NULL;
}

Node *head = NULL, *temp = NULL;


int data;

for (int i = 1; i <= n; i++) {


printf("Input data for node %d: ", i);
scanf("%d", &data);

Node* newNode = createNode(data);

if (head == NULL) {
head = newNode; // First node becomes the head
} else {
temp->next = newNode; // Link the new node to the previous one
}
temp = newNode; // Update the temp pointer to the new node
}

return head;
}

// Function to display the linked list


void displayLinkedList(Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("\nData entered in the list:\n");


while (head != NULL) {
printf("Data = %d\n", head->data);
head = head->next;
}
}

// Main function
int main() {
int n;

printf("Input the number of nodes: ");


scanf("%d", &n);

Node* head = createLinkedList(n);

displayLinkedList(head);

return 0;
}
8. A grading system stores student scores in an array. The program sorts the scores in ascending
order to display the students from lowest to highest score.Write a program in C to sort elements
of an array in ascending order.
Test Data :
Input the size of array : 5
Input 5 elements in the array :
Element – 0 : 2 , Element – 1 : 7 ,Element – 2 : 4 ,Element – 3 : 5, Element – 4 : 9
Expected Output :
Elements of array in sorted ascending order:
24579
#include <stdio.h>

// Function to sort the array in ascending order


void sortArray(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap the elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to display the elements of the array


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

// Main function
int main() {
int size;

printf("Input the size of array: ");


scanf("%d", &size);

int arr[size];
printf("Input %d elements in the array:\n", size);
for (int i = 0; i < size; i++) {
printf("Element - %d: ", i);
scanf("%d", &arr[i]);
}

// Sort the array


sortArray(arr, size);
// Display the sorted array
printf("Elements of array in sorted ascending order:\n");
displayArray(arr, size);

return 0;
}

9. A patient management system stores patient data in two sorted lists based on age groups. The
program merges these two lists to create one comprehensive sorted list.Write a C program to
merge two sorted singly linked lists into a single sorted linked list.

Test Data and Expected Output :

Two sorted singly linked lists:


1357
246

After merging the said two sorted lists:1 2 3 4 5 6 7


#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node in the linked list


typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the linked list


void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to merge two sorted linked lists


Node* mergeSortedLists(Node* list1, Node* list2) {
// Create a dummy node to help with the merge process
Node* mergedList = NULL;
Node** tail = &mergedList;

while (list1 != NULL && list2 != NULL) {


if (list1->data < list2->data) {
*tail = list1;
list1 = list1->next;
} else {
*tail = list2;
list2 = list2->next;
}
tail = &((*tail)->next);
}

// Append the remaining elements


if (list1 != NULL) {
*tail = list1;
} else {
*tail = list2;
}

return mergedList;
}

// Function to display the linked list


void displayList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

// Main function
int main() {
Node* list1 = NULL;
Node* list2 = NULL;

// Input data for list 1


printf("Enter elements for the first sorted list:\n");
insertNode(&list1, 1);
insertNode(&list1, 3);
insertNode(&list1, 5);
insertNode(&list1, 7);

// Input data for list 2


printf("Enter elements for the second sorted list:\n");
insertNode(&list2, 2);
insertNode(&list2, 4);
insertNode(&list2, 6);

// Display the original lists


printf("List 1: ");
displayList(list1);
printf("List 2: ");
displayList(list2);

// Merge the two sorted lists


Node* mergedList = mergeSortedLists(list1, list2);

// Display the merged list


printf("Merged List: ");
displayList(mergedList);

return 0;
}

10. A text editor program uses a stack to reverse a user-inputted string to support undo
functionality. The reversed string is displayed as output.Write a C program that accepts a string
and reverse it using a stack.
Expected Output:
Input a string: data
Reversed string using a stack is:atad
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100 // Define the maximum size for the stack

// Define the stack structure


typedef struct {
char items[MAX_SIZE];
int top;
} Stack;

// Function to initialize the stack


void initializeStack(Stack* stack) {
stack->top = -1;
}

// Function to check if the stack is empty


int isStackEmpty(Stack* stack) {
return stack->top == -1;
}

// Function to push an element onto the stack


void push(Stack* stack, char value) {
if (stack->top < MAX_SIZE - 1) {
stack->items[++stack->top] = value;
} else {
printf("Stack overflow\n");
}
}

// Function to pop an element from the stack


char pop(Stack* stack) {
if (!isStackEmpty(stack)) {
return stack->items[stack->top--];
}
return '\0'; // Return null character if the stack is empty
}

// Function to reverse the string using a stack


void reverseString(char* str) {
Stack stack;
initializeStack(&stack);

// Push each character of the string onto the stack


for (int i = 0; str[i] != '\0'; i++) {
push(&stack, str[i]);
}
// Pop characters from the stack and replace the original string
int i = 0;
while (!isStackEmpty(&stack)) {
str[i++] = pop(&stack);
}
str[i] = '\0'; // Null-terminate the reversed string
}

// Main function
int main() {
char str[MAX_SIZE];

printf("Input a string: ");


fgets(str, MAX_SIZE, stdin);
str[strcspn(str, "\n")] = '\0'; // Remove the trailing newline character

reverseString(str);

printf("Reversed string using a stack is: %s\n", str);

return 0;
}

11. A customer service center uses a queue to handle incoming service requests. The program
reverses the order of service requests to process the most recent ones first.Write a C program to
reverse the elements of a queue.
Expected Output:
Queue elements are:6 7 8 9
Reverse Queue, elements are:9 8 7 6
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100 // Define the maximum size for the queue

// Define the queue structure


typedef struct {
int items[MAX_SIZE];
int front;
int rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue* q) {
q->front = -1;
q->rear = -1;
}

// Function to check if the queue is empty


int isQueueEmpty(Queue* q) {
return q->front == -1;
}

// Function to check if the queue is full


int isQueueFull(Queue* q) {
return q->rear == MAX_SIZE - 1;
}

// Function to enqueue an element into the queue


void enqueue(Queue* q, int value) {
if (isQueueFull(q)) {
printf("Queue overflow\n");
} else {
if (q->front == -1) {
q->front = 0; // If the queue is empty, set the front index to 0
}
q->items[++q->rear] = value;
}
}

// Function to dequeue an element from the queue


int dequeue(Queue* q) {
if (isQueueEmpty(q)) {
printf("Queue underflow\n");
return -1; // Return an error value
} else {
int value = q->items[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1; // If the queue becomes empty, reset both indices
} else {
q->front++;
}
return value;
}
}

// Function to display the queue


void displayQueue(Queue* q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
} else {
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}
}

// Function to reverse the queue using recursion (or stack-based technique)


void reverseQueue(Queue* q) {
if (isQueueEmpty(q)) {
return;
}

// Dequeue the front element


int frontElement = dequeue(q);

// Reverse the remaining queue


reverseQueue(q);

// Enqueue the front element back into the queue


enqueue(q, frontElement);
}

// Main function
int main() {
Queue q;
initializeQueue(&q);

// Enqueue elements into the queue


enqueue(&q, 6);
enqueue(&q, 7);
enqueue(&q, 8);
enqueue(&q, 9);

printf("Queue elements are: ");


displayQueue(&q);

// Reverse the queue


reverseQueue(&q);

printf("Reverse Queue, elements are: ");


displayQueue(&q);

return 0;
}
12. A shopping cart application stores the prices of items in an array. The program calculates and
displays the total cost of all the items in the cart.Write a program in C to find the sum of all
elements of the array.
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
Element – 0 : 2 , Element – 1 : 5 , Element - 2 : 8
Expected Output :
Sum of all elements stored in the array is : 15
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Input the number of elements to be stored in the array: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
printf("Element - %d : ", i);
scanf("%d", &arr[i]);
}
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of all elements stored in the array is: %d\n", sum);
return 0;
}
13. A student data system manages student records in two separate lists based on enrolment periods.
The program merges these lists into one, keeping the students ordered by their enrolment
dates.Write a C program to merge two sorted singly linked lists into a single sorted linked list.
Test Data and Expected Output :
Two sorted singly linked lists:
1357
2 46
After merging the said two sorted lists: 1 2 3 4 5 6 7.

#include <stdio.h>
#include <stdlib.h>

// Define the structure for the linked list node


struct Node {
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to print the linked list


void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to merge two sorted linked lists


struct Node* mergeSortedLists(struct Node* list1, struct Node* list2) {
// Create a new dummy node to simplify the merge process
struct Node dummy;
struct Node* tail = &dummy;
dummy.next = NULL;

while (list1 != NULL && list2 != NULL) {


if (list1->data < list2->data) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}

// If one of the lists is not empty, append the remaining elements


if (list1 != NULL) {
tail->next = list1;
} else {
tail->next = list2;
}

return dummy.next;
}

// Main function
int main() {
// Create first sorted list: 1 -> 3 -> 5 -> 7
struct Node* list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);
list1->next->next->next = createNode(7);

// Create second sorted list: 2 -> 4 -> 6


struct Node* list2 = createNode(2);
list2->next = createNode(4);
list2->next->next = createNode(6);
// Print the original lists
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);

// Merge the lists


struct Node* mergedList = mergeSortedLists(list1, list2);

// Print the merged list


printf("After merging the two lists: ");
printList(mergedList);

return 0;
}
14. A customer service system handles incoming customer requests using a queue. As customers are
served, their requests are dequeued, and new requests are inserted at the rear of the queue.Write
a C program to implement a queue using an array. Programs should contain functions for
inserting elements into the queue, displaying queue elements, and checking whether the queue is
empty or not.
Expected Output:
Initialize a queue!
Check the queue is empty or not? Yes
Insert some elements into the queue:
Queue elements are: 1 2 3
Insert another element into the queue:
Queue elements are: 1 2 3 4
Check the queue is empty or not? No
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5 // Define maximum size for the queue

// Define the queue structure


typedef struct {
int items[MAX_SIZE];
int front;
int rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue* q) {
q->front = -1;
q->rear = -1;
printf("Initialize a queue!\n");
}

// Function to check if the queue is empty


int isQueueEmpty(Queue* q) {
return q->front == -1;
}

// Function to check if the queue is full


int isQueueFull(Queue* q) {
return q->rear == MAX_SIZE - 1;
}

// Function to insert an element into the queue


void enqueue(Queue* q, int value) {
if (isQueueFull(q)) {
printf("Queue overflow! Cannot insert element %d.\n", value);
} else {
if (q->front == -1) { // If queue is empty
q->front = 0;
}
q->items[++q->rear] = value;
}
}

// Function to display the queue elements


void displayQueue(Queue* q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
} else {
printf("Queue elements are: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}
}

// Main function
int main() {
Queue q;
initializeQueue(&q);

// Check if the queue is empty


printf("Check the queue is empty or not? ");
if (isQueueEmpty(&q)) {
printf("Yes\n");
} else {
printf("No\n");
}
printf("Insert some elements into the queue:\n");
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
displayQueue(&q);
printf("Insert another element into the queue:\n");
enqueue(&q, 4);
displayQueue(&q);
printf("Check the queue is empty or not? ");
if (isQueueEmpty(&q)) {
printf("Yes\n");
} else {
printf("No\n");
}

return 0;
}

15. A task management application stores pending tasks in a queue. The program sorts tasks based
on priority, ensuring that the highest priority tasks are processed first.Write a C program to sort
the elements of a queue in ascending order.
Expected Output:

Input some elements into the queue:


Elements of the queue:
42751

Sort the said queue:


Elements of the sorted queue in ascending order:
1 2457
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5 // Define maximum size for the queue

// Define the queue structure


typedef struct {
int items[MAX_SIZE];
int front;
int rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue* q) {
q->front = -1;
q->rear = -1;
printf("Initialize a queue!\n");
}

// Function to check if the queue is empty


int isQueueEmpty(Queue* q) {
return q->front == -1;
}

// Function to check if the queue is full


int isQueueFull(Queue* q) {
return q->rear == MAX_SIZE - 1;
}

// Function to insert an element into the queue


void enqueue(Queue* q, int value) {
if (isQueueFull(q)) {
printf("Queue overflow! Cannot insert element %d.\n", value);
} else {
if (q->front == -1) { // If queue is empty
q->front = 0;
}
q->items[++q->rear] = value;
}
}

// Function to display the queue elements


void displayQueue(Queue* q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
} else {
printf("Queue elements are: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}
}
int main() {
Queue q;
initializeQueue(&q);
printf("Check the queue is empty or not? ");
if (isQueueEmpty(&q)) {
printf("Yes\n");
} else {
printf("No\n");
}
printf("Insert some elements into the queue:\n");
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
displayQueue(&q);

// Insert another element into the queue


printf("Insert another element into the queue:\n");
enqueue(&q, 4);
displayQueue(&q);

// Check if the queue is empty again


printf("Check the queue is empty or not? ");
if (isQueueEmpty(&q)) {
printf("Yes\n");
} else {
printf("No\n");
}

return 0;
}
16. An equation solver uses an expression tree to solve mathematical postfix expressions. The
program takes an input expression, constructs the tree, and outputs the evaluated result.Write a
C program to build an expression tree from a postfix expression. Evaluate and display the results.
Enter a postfix expression: 23+5*
In-order Traversal of the Expression Tree: 2 + 3 * 5
Result: 25
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

// Define structure for the expression tree node


typedef struct Node {
char data;
struct Node* left;
struct Node* right;
} Node;

// Stack structure for expression tree nodes


typedef struct Stack {
Node* nodes[100];
int top;
} Stack;

// Function to initialize the stack


void initStack(Stack* stack) {
stack->top = -1;
}

// Function to push a node onto the stack


void push(Stack* stack, Node* node) {
stack->nodes[++stack->top] = node;
}

// Function to pop a node from the stack


Node* pop(Stack* stack) {
return stack->nodes[stack->top--];
}

// Function to create a new node with given data


Node* createNode(char data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to check if a character is an operator


int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to evaluate the expression tree


int evaluate(Node* root) {
if (root == NULL) {
return 0;
}

// If it's a leaf node (operand), return its integer value


if (!isOperator(root->data)) {
return root->data - '0'; // Convert char to int
}

// Otherwise, it's an operator node, evaluate left and right subtrees


int leftValue = evaluate(root->left);
int rightValue = evaluate(root->right);

switch (root->data) {
case '+': return leftValue + rightValue;
case '-': return leftValue - rightValue;
case '*': return leftValue * rightValue;
case '/': return leftValue / rightValue;
default: return 0;
}
}

// Function for in-order traversal (to print expression)


void inOrder(Node* root) {
if (root == NULL) {
return;
}

// In-order traversal: left, root, right


inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}

// Function to build the expression tree from the postfix expression


Node* buildExpressionTree(char* postfix) {
Stack stack;
initStack(&stack);
for (int i = 0; postfix[i] != '\0'; i++) {
char current = postfix[i];

if (isdigit(current)) {
// If the character is a number, create a node and push to stack
push(&stack, createNode(current));
} else if (isOperator(current)) {
// If the character is an operator, pop two nodes, create a new node and push it back
Node* operatorNode = createNode(current);
operatorNode->right = pop(&stack);
operatorNode->left = pop(&stack);
push(&stack, operatorNode);
}
}

// The final node in the stack will be the root of the expression tree
return pop(&stack);
}

// Main function
int main() {
char postfixExpression[100];

// Input the postfix expression


printf("Enter a postfix expression: ");
scanf("%s", postfixExpression);

// Build the expression tree


Node* root = buildExpressionTree(postfixExpression);
printf("In-order Traversal of the Expression Tree: ");
inOrder(root);
printf("\n");
int result = evaluate(root);
printf("Result: %d\n", result);
return 0;
}

17. An e-commerce platform sorts product prices using merge sort. The program takes unsorted
prices, sorts them in ascending order, and displays the sorted list of product prices.Write a C
program to sort a list of elements using the merge sort algorithm.
Sample Output:
Given array is :125 181 130 25 61 887
Sorted array is : 25 61 125 130 181 887
#include <stdio.h>

// Function to merge two halves of the array


void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1; // Size of left subarray
int n2 = right - mid; // Size of right subarray

// Temporary arrays to hold the left and right subarrays


int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays


for (int i = 0; i < n1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < n2; i++) {
rightArr[i] = arr[mid + 1 + i];
}

// Merge the temporary arrays back into the original array


int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}

// Copy the remaining elements of leftArr[], if any


while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}

// Copy the remaining elements of rightArr[], if any


while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}

// Function to perform merge sort on the array


void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2; // Find the middle point

// Recursively sort the two halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

// Function to print the array


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

// Main function
int main() {
int arr[] = {125, 181, 130, 25, 61, 887}; // Sample array of product prices
int n = sizeof(arr) / sizeof(arr[0]);
printf("Given array is: ");
mergeSort(arr, 0, n - 1);
printf("Sorted array is: ");
printArray(arr, n);

return 0;
}
18. A network optimization tool uses Prim’s algorithm to find the minimum spanning tree. The
program calculates the most cost-efficient way to connect all nodes in the network with the least
total cost.Write a C program that implements Prim’s algorithm to find the minimum spanning

tree of a connected, undirected graph in C.


#include <stdio.h>
#include <limits.h>

#define MAX_VERTICES 10

// Function to find the vertex with the minimum key value


int minKey(int key[], int mstSet[], int V) {
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++) {


if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}

// Function to implement Prim's algorithm for MST


void primMST(int graph[MAX_VERTICES][MAX_VERTICES], int V) {
int parent[V]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge
int mstSet[V]; // To represent vertices not yet included in MST

// Initialize all keys to infinity and mstSet[] to false


for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0;
}

// Always include the first vertex in the MST


key[0] = 0; // First vertex is always the root of MST
parent[0] = -1; // The root does not have a parent

// Find the MST for all vertices


for (int count = 0; count < V - 1; count++) {
// Choose the minimum key vertex that is not yet included in MST
int u = minKey(key, mstSet, V);
// Mark the picked vertex as included in MST
mstSet[u] = 1;

// Update the key and parent values of the adjacent vertices


for (int v = 0; v < V; v++) {
// Update key[v] if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
key[v] = graph[u][v];
parent[v] = u;
}
}
}

// Print the constructed MST


printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
}
}

// Main function to test the program


int main() {
int V = 5; // Number of vertices
int graph[MAX_VERTICES][MAX_VERTICES] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};

// Call Prim's algorithm to find the MST


primMST(graph, V);

return 0;
}
19. A task scheduling system uses a stack implemented with two queues. The program pushes tasks
onto the stack using two queues and pops tasks off the stack to process them in reverse order.
Write a C program to implement a stack using two queues.

Push data 1
Push data 2
Push data 3

Pop data: 3
Pop data: 2
Pop data: 1
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// Structure to represent a Queue


typedef struct {
int data[MAX_SIZE];
int front, rear;
} Queue;

// Function to initialize a queue


void initQueue(Queue *q) {
q->front = -1;
q->rear = -1;
}

// Function to check if a queue is empty


int isEmpty(Queue *q) {
return q->front == -1;
}

// Function to check if a queue is full


int isFull(Queue *q) {
return q->rear == MAX_SIZE - 1;
}

// Function to enqueue an element


void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full!\n");
return;
}
if (q->front == -1) {
q->front = 0; // first element being inserted
}
q->data[++q->rear] = value;
}

// Function to dequeue an element


int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
int value = q->data[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1; // reset queue after last element
} else {
q->front++;
}
return value;
}

// Structure to represent a Stack using two queues


typedef struct {
Queue q1, q2;
} Stack;

// Function to initialize the stack


void initStack(Stack *s) {
initQueue(&s->q1);
initQueue(&s->q2);
}

// Function to push an element onto the stack


void push(Stack *s, int value) {
enqueue(&s->q1, value);

// Move all elements from q1 to q2 to reverse their order


while (!isEmpty(&s->q1)) {
enqueue(&s->q2, dequeue(&s->q1));
}

// Move elements back to q1 to maintain the stack's LIFO order


while (!isEmpty(&s->q2)) {
enqueue(&s->q1, dequeue(&s->q2));
}
}

// Function to pop an element from the stack


int pop(Stack *s) {
if (isEmpty(&s->q1)) {
printf("Stack is empty!\n");
return -1;
}
return dequeue(&s->q1);
}

// Main function to test the stack using two queues


int main() {
Stack s;
initStack(&s);

// Pushing data onto the stack


printf("Push data 1\n");
push(&s, 1);
printf("Push data 2\n");
push(&s, 2);
printf("Push data 3\n");
push(&s, 3);

// Popping data from the stack


printf("Pop data: %d\n", pop(&s)); // Expected output: 3
printf("Pop data: %d\n", pop(&s)); // Expected output: 2
printf("Pop data: %d\n", pop(&s)); // Expected output: 1
return 0;
}
20. A contact management system uses a binary search tree to store and search for contacts. The
program can insert contacts, search by name, and retrieve the contact with the minimum and
maximum phone numbers.Implement a Binary Search Tree(BST) to insert
7,4,98,32,45,67,89,31,43,56 and perform Searching the element 56 also perform Find_Min and
Find_Max Operations
#include <stdio.h>
#include <stdlib.h>

// Structure for a node in the Binary Search Tree (BST)


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}

// Function to insert a node in the BST


struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return newNode(data); // Insert the new node
}

// Traverse the tree to find the correct position


if (data < root->data) {
root->left = insert(root->left, data); // Insert in the left subtree
} else if (data > root->data) {
root->right = insert(root->right, data); // Insert in the right subtree
}

return root;
}

// Function to search for a node in the BST


int search(struct Node* root, int key) {
if (root == NULL) {
return 0; // Not found
}

if (root->data == key) {
return 1; // Found
}

// If key is smaller, search in the left subtree


if (key < root->data) {
return search(root->left, key);
} else {
return search(root->right, key);
}
}

// Function to find the node with the minimum value


int findMin(struct Node* root) {
if (root == NULL) {
return -1; // Tree is empty
}

// Traverse to the leftmost node


while (root->left != NULL) {
root = root->left;
}
return root->data;
}

// Function to find the node with the maximum value


int findMax(struct Node* root) {
if (root == NULL) {
return -1; // Tree is empty
}

// Traverse to the rightmost node


while (root->right != NULL) {
root = root->right;
}
return root->data;
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
struct Node* root = NULL;
root = insert(root, 7);
root = insert(root, 4);
root = insert(root, 98);
root = insert(root, 32);
root = insert(root, 45);
root = insert(root, 67);
root = insert(root, 89);
root = insert(root, 31);
root = insert(root, 43);
root = insert(root, 56);
printf("In-order traversal of the BST: ");
inorder(root);
printf("\n");
int key = 56;
if (search(root, key)) {
printf("Element %d found in the tree.\n", key);
} else {
printf("Element %d not found in the tree.\n", key);
}
int min = findMin(root);
int max = findMax(root);
if (min != -1) {
printf("Minimum element in the BST: %d\n", min);
} else {
printf("BST is empty.\n");
}
if (max != -1) {
printf("Maximum element in the BST: %d\n", max);
} else {
printf("BST is empty.\n");
}
return 0;
}

21. A queue management system for parking slots operates as a circular queue. Cars enter (insert)
and exit (delete) in a circular manner, ensuring efficient management of parking spaces. Write a
C program to implement a circular queue and perform insertion and deletion operations.
Circular Queue:
Front 1 2 3 4 5 Rear

After Insertion:
Front 1 2 3 4 5 6 Rear

After Deletion:
Front 2 3 4 5 6 Rear
#include <stdio.h>
#include <stdlib.h>

#define MAX 5 // Maximum size of the queue

// Structure for circular queue


struct CircularQueue {
int arr[MAX];
int front;
int rear;
};

// Function to initialize the queue


void initQueue(struct CircularQueue* queue) {
queue->front = -1;
queue->rear = -1;
}

// Function to check if the queue is full


int isFull(struct CircularQueue* queue) {
return (queue->rear + 1) % MAX == queue->front;
}

// Function to check if the queue is empty


int isEmpty(struct CircularQueue* queue) {
return queue->front == -1;
}

// Function to insert an element into the queue (enqueue operation)


void enqueue(struct CircularQueue* queue, int value) {
if (isFull(queue)) {
printf("Queue is full, cannot insert %d\n", value);
return;
}

// If the queue is empty, set both front and rear to 0


if (isEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
// Increment rear in a circular manner
queue->rear = (queue->rear + 1) % MAX;
}

queue->arr[queue->rear] = value;
printf("Inserted %d into the queue\n", value);
}

// Function to delete an element from the queue (dequeue operation)


void dequeue(struct CircularQueue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty, cannot delete\n");
return;
}

int deletedValue = queue->arr[queue->front];


printf("Deleted %d from the queue\n", deletedValue);

// If there is only one element in the queue


if (queue->front == queue->rear) {
queue->front = -1;
queue->rear = -1;
} else {
// Increment front in a circular manner
queue->front = (queue->front + 1) % MAX;
}
}

// Function to display the elements of the queue


void displayQueue(struct CircularQueue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return;
}

printf("Circular Queue: ");


int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->arr[i]);
i = (i + 1) % MAX;
}
printf("%d ", queue->arr[queue->rear]); // Display the last element
printf("\n");
}

// Main function to test the circular queue operations


int main() {
struct CircularQueue queue;
initQueue(&queue);

// Display the initial state of the queue


printf("Initial state of the queue:\n");
displayQueue(&queue);

// Perform insertions (enqueue operations)


enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
enqueue(&queue, 4);
enqueue(&queue, 5); // Queue is full now

// Display the queue after insertions


printf("After insertions:\n");
displayQueue(&queue);

// Perform a deletion (dequeue operation)


dequeue(&queue);

// Display the queue after deletion


printf("After deletion:\n");
displayQueue(&queue);

// Insert a new element after deletion


enqueue(&queue, 6);

// Display the final state of the queue


printf("After insertion of 6:\n");
displayQueue(&queue);

return 0;
}
22. A mathematical expression evaluator uses stacks to convert infix expressions to postfix format.
The program then evaluates the postfix expression to compute the result of complex
mathematical operations.Write a C program to convert an infix expression to a postfix expression
using a stack.
Infix Expression: (3 + 5) * 2 / (7 - 4)

Postfix Expression: 3 5 + 2 * 7 4 - /
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 100

// Stack structure
struct Stack {
char arr[MAX];
int top;
};
// Function to initialize the stack
void initStack(struct Stack *stack) {
stack->top = -1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack *stack) {
return stack->top == -1;
}

// Function to push an element onto the stack


void push(struct Stack *stack, char value) {
if (stack->top == MAX - 1) {
printf("Stack overflow\n");
return;
}
stack->arr[++stack->top] = value;
}

// Function to pop an element from the stack


char pop(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack underflow\n");
return -1;
}
return stack->arr[stack->top--];
}

// Function to get the top element of the stack without popping it


char peek(struct Stack *stack) {
if (isEmpty(stack)) {
return -1;
}
return stack->arr[stack->top];
}

// Function to check the precedence of operators


int precedence(char operator) {
if (operator == '*' || operator == '/') {
return 2;
} else if (operator == '+' || operator == '-') {
return 1;
}
return 0;
}

// Function to check if a character is an operator


int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to convert infix to postfix


void infixToPostfix(char *infix, char *postfix) {
struct Stack stack;
initStack(&stack);
int i = 0, k = 0;

while (infix[i] != '\0') {


char currentChar = infix[i];

// If the current character is an operand, add it to the postfix expression


if (isdigit(currentChar)) {
postfix[k++] = currentChar;
}
// If the current character is '(', push it to the stack
else if (currentChar == '(') {
push(&stack, currentChar);
}
// If the current character is ')', pop from the stack until '(' is encountered
else if (currentChar == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[k++] = pop(&stack);
}
pop(&stack); // Discard the '(' from the stack
}
// If the current character is an operator, pop operators from the stack with higher
precedence
else if (isOperator(currentChar)) {
while (!isEmpty(&stack) && precedence(peek(&stack)) >= precedence(currentChar)) {
postfix[k++] = pop(&stack);
}
push(&stack, currentChar);
}
i++;
}
// Pop all the remaining operators from the stack
while (!isEmpty(&stack)) {
postfix[k++] = pop(&stack);
}

postfix[k] = '\0'; // Null terminate the postfix expression


}

// Main function to test the program


int main() {
char infix[MAX], postfix[MAX];

printf("Enter an infix expression: ");


scanf("%[^\n]", infix); // Read a line of input, including spaces

infixToPostfix(infix, postfix);

printf("Postfix expression: %s\n", postfix);

return 0;
}
23. A customer service system implements a queue using two stacks. The program uses two stacks to
enqueue and dequeue customers efficiently, ensuring the first customer in is the first to be
served.Write a C program to implement a queue using two stacks.
Enqueue data 1
Enqueue data 2
Enqueue data 3

Dequeue data: 1
Dequeue data: 2
Dequeue data: 3
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100


// Stack structure
struct Stack {
int arr[MAX_SIZE];
int top;
};

// Function to initialize the stack


void initStack(struct Stack* stack) {
stack->top = -1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* stack) {
return stack->top == -1;
}

// Function to push an element onto the stack


void push(struct Stack* stack, int value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
return;
}
stack->arr[++stack->top] = value;
}

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow\n");
return -1;
}
return stack->arr[stack->top--];
}

// Queue structure that uses two stacks


struct Queue {
struct Stack stack1;
struct Stack stack2;
};

// Function to initialize the queue


void initQueue(struct Queue* queue) {
initStack(&queue->stack1);
initStack(&queue->stack2);
}

// Function to enqueue an element to the queue


void enqueue(struct Queue* queue, int value) {
push(&queue->stack1, value);
printf("Enqueue data %d\n", value);
}

// Function to dequeue an element from the queue


int dequeue(struct Queue* queue) {
// If stack2 is empty, transfer all elements from stack1 to stack2
if (isEmpty(&queue->stack2)) {
while (!isEmpty(&queue->stack1)) {
int value = pop(&queue->stack1);
push(&queue->stack2, value);
}
}

// If stack2 is empty, queue is empty


if (isEmpty(&queue->stack2)) {
printf("Queue is empty\n");
return -1; // Queue is empty
}

// Pop from stack2 (this gives the oldest element)


int value = pop(&queue->stack2);
printf("Dequeue data: %d\n", value);
return value;
}

// Main function
int main() {
struct Queue queue;
initQueue(&queue);

// Enqueue data
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
// Dequeue data
dequeue(&queue);
dequeue(&queue);
dequeue(&queue);

return 0;
}
24. A program sorts employee ID numbers using the shell sort algorithm, which efficiently sorts an
array by comparing and swapping elements at intervals, improving on basic sorting techniques
like bubble sort.Write a C program to implement the shell sort algorithm.
Original Array: 6 2 9 5 7

After Shell Sort:


25679
#include <stdio.h>

// Function to perform Shell Sort


void shellSort(int arr[], int n) {
// Start with a large gap and reduce it
for (int gap = n / 2; gap > 0; gap /= 2) {
// Perform a gapped insertion sort for this gap size.
for (int i = gap; i < n; i++) {
// Store the current element to be compared
int temp = arr[i];
int j = i;

// Shift earlier gap-sorted elements up until the correct location for arr[i] is found
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = temp;
}
}
}

// Function to print the array


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

int main() {
int arr[] = {6, 2, 9, 5, 7}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");


printArray(arr, n);

// Perform Shell Sort


shellSort(arr, n);

printf("After Shell Sort: ");


printArray(arr, n);

return 0;
}

25. A report generation system sorts transaction amounts using merge sort. The program takes a
large list of unsorted transaction amounts, applies merge sort, and produces the sorted list for
further analysis.Write a C program to implement the merge sort algorithm.
Original Array: 4 1 7 3 9
After Merge Sort:
13479
#include <stdio.h>

// Merge two halves of the array


void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

// Temporary arrays to hold the values


int L[n1], R[n2];
// Copy data into temporary arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int i = 0; i < n2; i++)
R[i] = arr[mid + 1 + i];

// Merge the temporary arrays back into arr[]


int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Merge Sort function


void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;

// Sort the first half


mergeSort(arr, left, mid);

// Sort the second half


mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

// Function to print the array


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

int main() {
int arr[] = {4, 1, 7, 3, 9}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");


printArray(arr, n);

// Perform Merge Sort


mergeSort(arr, 0, n - 1);

printf("After Merge Sort: ");


printArray(arr, n);

return 0;
}
26. A priority queue in a task management system uses heap sort to organize tasks based on priority.
The program sorts tasks using heap sort, ensuring the highest priority tasks are processed
first.Write a C program to implement the heap sort algorithm.
Original Array: 5 9 3 1 7
After Heap Sort:
13579
#include <stdio.h>

// Function to heapify a subtree rooted at index i


void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child index
int right = 2 * i + 2; // Right child index

// If left child is larger than root


if (left < n && arr[left] > arr[largest]) {
largest = left;
}

// If right child is larger than the largest so far


if (right < n && arr[right] > arr[largest]) {
largest = right;
}

// If largest is not root


if (largest != i) {
// Swap the elements
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

// Recursively heapify the affected subtree


heapify(arr, n, largest);
}
}

// Function to perform heap sort


void heapSort(int arr[], int n) {
// Build a max-heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

// One by one extract elements from heap


for (int i = n - 1; i > 0; i--) {
// Move the current root to the end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

// Call heapify on the reduced heap


heapify(arr, i, 0);
}
}

// Function to print the array


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

int main() {
int arr[] = {5, 9, 3, 1, 7}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array: ");
printArray(arr, n);
heapSort(arr, n);
printf("After Heap Sort: ");
printArray(arr, n);
return 0;
}
27. A navigation system calculates the shortest path between two locations using Dijkstra’s
algorithm. The program processes the weighted map and provides the optimal route, considering
distance or travel time.Write a C program to implement Dijkstra's algorithm for finding the
shortest path in a weighted graph.

#include <stdio.h>
#include <limits.h>

#define V 9 // Number of vertices in the graph

// Function to find the vertex with the minimum distance value


int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (sptSet[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}

// Function to implement Dijkstra's algorithm


void dijkstra(int graph[V][V], int src) {
int dist[V]; // The output array, dist[i] holds the shortest distance from src to i
int sptSet[V]; // sptSet[i] will be true if vertex i is included in the shortest path tree

// Initialize all distances as INFINITE and sptSet[] as false


for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}

// Distance from the source to itself is always 0


dist[src] = 0;

// Find the shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = 1;

// Update dist[] values of the adjacent vertices of the picked vertex


for (int v = 0; v < V; v++) {
// Update dist[v] if and only if the current vertex u is not in
// the shortest path tree and there is an edge from u to v, and
// the new calculated distance is smaller than the current distance
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

// Print the constructed distance array


printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}

int main() {
// Graph represented as an adjacency matrix
int graph[V][V] = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 0, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 0, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
int source = 0; // Source vertex (can be changed)
dijkstra(graph, source);

return 0;
}
28. A network design system uses Kruskal's algorithm to find the minimal connection cost between
various data nodes. The program calculates the minimum spanning tree of the network,
optimizing installation costs.Write a C program to implement kruskal's algorithm for finding the
shortest path in a weighted graph

#include <stdio.h>
#include <stdlib.h>

// Structure to represent an edge


struct Edge {
int src, dest, weight;
};

// Structure to represent a subset for union-find


struct Subset {
int parent;
int rank;
};

// Function to compare two edges based on their weight


int compareEdges(const void *a, const void *b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}

// Find function of the Union-Find structure (with path compression)


int find(struct Subset subsets[], int i) {
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].parent);
}
return subsets[i].parent;
}

// Union function of the Union-Find structure (union by rank)


void unionSets(struct Subset subsets[], int x, int y) {
int rootX = find(subsets, x);
int rootY = find(subsets, y);

if (rootX != rootY) {
// Union by rank
if (subsets[rootX].rank < subsets[rootY].rank) {
subsets[rootX].parent = rootY;
} else if (subsets[rootX].rank > subsets[rootY].rank) {
subsets[rootY].parent = rootX;
} else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}
}
// Function to implement Kruskal's Algorithm
void kruskal(struct Edge edges[], int V, int E) {
struct Edge result[V]; // Store the final MST
int e = 0; // Count of edges in MST
int i = 0; // Initial index of sorted edges
struct Subset subsets[V]; // Subsets for union-find

// Step 1: Sort all edges in non-decreasing order of their weight


qsort(edges, E, sizeof(edges[0]), compareEdges);

// Initialize subsets: create V single node sets


for (int v = 0; v < V; v++) {
subsets[v].parent = v;
subsets[v].rank = 0;
}

// Step 2: Pick the smallest edge. Check if it forms a cycle.


while (e < V - 1 && i < E) {
struct Edge nextEdge = edges[i++];
int x = find(subsets, nextEdge.src);
int y = find(subsets, nextEdge.dest);

// If including this edge does not cause a cycle, include it in the result
if (x != y) {
result[e++] = nextEdge;
unionSets(subsets, x, y);
}
}

// Step 3: Print the final MST


printf("Edges in the Minimum Spanning Tree:\n");
for (int i = 0; i < e; i++) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
}
}

// Main function
int main() {
int V = 4; // Number of vertices
int E = 5; // Number of edges

// Create a graph with 4 vertices and 5 edges


struct Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};

// Call Kruskal's algorithm to find the MST


kruskal(edges, V, E);

return 0;
}
29. An inventory management system uses closed hashing to handle product IDs. The program
handles collisions by using a fixed table size and a hashing function to resolve conflicts and
maintain fast lookups, insertions, and deletions.Design a program for closed hashing to resolving
the collision. Implement the insertion, deletion and searching operations.
Note:
Choose your fixed table size
hashIndex = key % Table size
#include <stdio.h>
#include <stdlib.h>

#define TABLE_SIZE 10 // Fixed table size

// Structure to represent a product ID entry in the table


struct Product {
int productID;
int isOccupied; // Flag to indicate whether a slot is occupied
};

// Function to initialize the hash table


void initializeTable(struct Product table[]) {
for (int i = 0; i < TABLE_SIZE; i++) {
table[i].isOccupied = 0; // Mark all slots as empty
}
}

// Hash function to get index for product ID


int hashFunction(int key) {
return key % TABLE_SIZE;
}
// Function to insert a product ID into the hash table
void insert(struct Product table[], int productID) {
int index = hashFunction(productID);

// Linear probing to find the next available slot


int originalIndex = index;
while (table[index].isOccupied == 1) {
index = (index + 1) % TABLE_SIZE; // Move to the next slot
if (index == originalIndex) {
printf("Hash table is full, cannot insert %d\n", productID);
return;
}
}

// Insert the product ID into the table


table[index].productID = productID;
table[index].isOccupied = 1;
printf("Product ID %d inserted at index %d\n", productID, index);
}

// Function to delete a product ID from the hash table


void delete(struct Product table[], int productID) {
int index = hashFunction(productID);

// Linear probing to find the product ID


int originalIndex = index;
while (table[index].isOccupied == 1) {
if (table[index].productID == productID) {
table[index].isOccupied = 0; // Mark the slot as empty
printf("Product ID %d deleted from index %d\n", productID, index);
return;
}
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
break; // We've cycled through the table
}
}

// If product ID is not found


printf("Product ID %d not found\n", productID);
}

// Function to search for a product ID in the hash table


void search(struct Product table[], int productID) {
int index = hashFunction(productID);

// Linear probing to find the product ID


int originalIndex = index;
while (table[index].isOccupied == 1) {
if (table[index].productID == productID) {
printf("Product ID %d found at index %d\n", productID, index);
return;
}
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
break; // We've cycled through the table
}
}

// If product ID is not found


printf("Product ID %d not found\n", productID);
}

// Function to display the contents of the hash table


void display(struct Product table[]) {
printf("Hash Table Contents:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[i].isOccupied == 1) {
printf("Index %d: Product ID %d\n", i, table[i].productID);
} else {
printf("Index %d: Empty\n", i);
}
}
}

// Main function to test the hash table operations


int main() {
struct Product table[TABLE_SIZE]; // Create the hash table
initializeTable(table); // Initialize the table

// Insert product IDs


insert(table, 23);
insert(table, 45);
insert(table, 33);
insert(table, 56);
insert(table, 79);
insert(table, 32);
display(table);
search(table, 45);
search(table, 79);
search(table, 100); // This ID does not exist

// Delete product IDs


delete(table, 33);
delete(table, 79);
delete(table, 100); // This ID does not exist
display(table);

return 0;
}
30. Design a C program for Binary Search Tree ADT operations. The operations are insertion, find
minimum and find maximum and display.

#include <stdio.h>
#include <stdlib.h>

// Define structure for a node in the Binary Search Tree


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}

// Function to insert a new node in the BST


struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return newNode(data);
}

if (data < root->data) {


root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}

// Function to find the minimum value node in a BST


struct Node* findMin(struct Node* root) {
if (root == NULL) {
return NULL;
}
while (root->left != NULL) {
root = root->left;
}
return root;
}

// Function to find the maximum value node in a BST


struct Node* findMax(struct Node* root) {
if (root == NULL) {
return NULL;
}
while (root->right != NULL) {
root = root->right;
}
return root;
}

// Function to perform an inorder traversal of the BST (Left, Root, Right)


void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

// Main function to test the BST operations


int main() {
struct Node* root = NULL;

// Insert nodes into the BST


root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

// Display the elements of the BST using inorder traversal


printf("Inorder traversal of the BST: ");
inorder(root);
printf("\n");

// Find and display the minimum and maximum values


struct Node* minNode = findMin(root);
struct Node* maxNode = findMax(root);

if (minNode != NULL) {
printf("Minimum value in the BST: %d\n", minNode->data);
} else {
printf("The BST is empty.\n");
}

if (maxNode != NULL) {
printf("Maximum value in the BST: %d\n", maxNode->data);
} else {
printf("The BST is empty.\n");
}

return 0;
}

Internal Examiner 1 HoD/CSE Dean Academics

You might also like