Dsamodel 2 Final
Dsamodel 2 Final
The program
calculates the total of all customer transactions in the queue to generate a daily report. Write a
C program to calculate the sum of the elements in a queue.
Expected Output:
Queue elements are: 1 2 3 4 5
Sum of the elements in the queue is: 15
#include <stdio.h>
#define MAX 100 // Maximum size of the queue
// Queue structure
typedef struct {
int data[MAX];
int front;
int rear;
} Queue;
// Main function
int main() {
Queue q;
initializeQueue(&q);
return 0;
}
2. A playlist application uses a linked list to manage songs. The user requests to reverse the order
of songs in the playlist to play them in the opposite sequence. Implement a program to reverse
a linked list.
Original Linked List: 2 -> 7 -> 3 -> NULL
Reversed Linked List: 3 -> 7 -> 2 -> NULL
#include <stdio.h>
#include <stdlib.h>
// Node structure
typedef struct Node {
int data;
struct Node *next;
} Node;
// Main function
int main() {
Node *head = NULL;
return 0;
}
3. A shopping cart application calculates the total cost of items. The array stores the prices of items
in the cart, and the program computes the total sum of the cart contents..Write a C program to
find the sum of elements in an array
Sum of elements: 30
#include <stdio.h>
// Function to calculate the sum of elements in an array
int calculateSum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// Main function
int main() {
// Array to store item prices
int cart[] = {5, 10, 15}; // Example prices
int size = sizeof(cart) / sizeof(cart[0]); // Calculate the number of elements
return 0;
}
4. A file system manager organizes directories and files in a binary tree. The program calculates
the height of the tree to determine the maximum depth of the file structure Write a C program
to find the height of a binary tree.
Height of the binary tree: 2
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
// Constructing a simple binary tree
Node *root = createNode(1); // Level 0
root->left = createNode(2); // Level 1
root->right = createNode(3); // Level 1
root->left->left = createNode(4); // Level 2
root->left->right = createNode(5); // Level 2
return 0;
}
5. A library system manages a list of books. The program allows the librarian to insert a new book
at the beginning of the list, updating the order of books currently available. Write a program in
C to insert a new node at the beginning of a Singly Linked List.
Test Data and Expected Output :
Input the number of nodes : 3
Input data for node 1 : 5 , Input data for node 2 : 6, Input data for node 3 : 7
// Main function
int main() {
Node *head = NULL;
int n, data;
return 0;
}
6. An inventory management system uses a stack to store product prices. The program finds the
minimum price in the stack to identify the least expensive product. Write a C program to find
the minimum element in a stack.
Expected Output:
// Main function
int main() {
Stack stack;
initializeStack(&stack);
return 0;
}
7. A code validation tool checks whether a programmer’s code contains balanced parentheses. The
program uses a stack to verify if the parentheses are correctly matched. Write a C program that
checks whether a string of parentheses is balanced or not using stack.
Input an expression in parentheses: ((()))
The expression is balanced.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100 // Maximum size of the stack
if (ch == '(') {
push(&stack, ch);
} else if (ch == ')') {
if (isEmpty(&stack)) {
return 0; // Unmatched closing parenthesis
}
pop(&stack); // Match closing parenthesis
}
}
// Main function
int main() {
char expression[MAX];
if (isBalanced(expression)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}
return 0;
}
8. A browser history feature keeps track of recently visited pages using a stack. As pages are
visited, they are pushed onto the stack, and the program pops them when the user presses the
back button. Write a C program to implement a stack using a singly linked list.
Expected Output:
Push data 3
Push data 5
Push data 6
Push data 8
Pop data: 8
Pop data: 6
Pop data: 5
Pop data: 3
Check a stack is empty or not?
Stack is empty!
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
Node *stack = NULL;
if (isalnum(ch)) {
// Operand: Create a node and push it onto the stack
push(&stack, createNode(ch));
} else {
// Operator: Pop two nodes, create a new node, and push it
Node *node = createNode(ch);
node->right = pop(&stack);
node->left = pop(&stack);
push(&stack, node);
}
}
return pop(&stack); // The root of the tree
}
// Main function
int main() {
char postfix[100];
printf("Enter the postfix expression: ");
scanf("%s", postfix);
int main() {
int n, target, result;
int arr[n];
return 0;
}
11. A navigation system uses Dijkstra’s algorithm to find the shortest route between two locations.
The program calculates the shortest path from the user's current location to various destination
points. Write a C program that creates a function to find the shortest path from a source vertex
to all other vertices using Dijkstra's algorithm.
#include <stdio.h>
#include <limits.h>
return min_index;
}
// Function to implement Dijkstra's algorithm to find the shortest path from source to all vertices
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
int main() {
// Graph representation based on the image (Adjacency matrix)
// The graph is represented as follows:
// A = 0, B = 1, C = 2, D = 3
int graph[V][V] = {
{0, 5, 0, 8}, // A to B = 5, A to D = 8
{5, 0, 2, 7}, // B to A = 5, B to C = 2, B to D = 7
{0, 2, 0, 6}, // C to B = 2, C to D = 6
{8, 7, 6, 0} // D to A = 8, D to B = 7, D to C = 6
};
int source;
printf("Enter the source vertex (0 for A, 1 for B, 2 for C, 3 for D): ");
scanf("%d", &source);
dijkstra(graph, source);
return 0;
}
12. A ticket booking system uses a circular queue to manage reservations. As customers book and
cancel tickets, the program inserts and deletes customer requests from the queue while
maintaining a circular order. 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>
int main() {
struct CircularQueue q;
initQueue(&q);
display(&q);
// Insert one more element (should fail since the queue is full)
enqueue(&q, 6);
display(&q);
return 0;
}
13. A playlist management system finds the kth last song in a list of songs. The program traverses
the list to identify the kth last song, useful for features like "last played" or "recently added."
Write a C program to find the kth to last element in a singly linked list.
Linked List: 1 2 3 4 5
2nd to Last Element: 4
#include <stdio.h>
#include <stdlib.h>
int k = 2;
findKthToLast(head, k); // Find 2nd to last element
return 0;
}
14. A library uses a Binary Search Tree (BST) to manage book IDs, allowing efficient search and
organization. Implement a program to insert book IDs into the BST, find the minimum ID
(smallest book ID), and locate the maximum ID (largest book ID), enabling quick access to
specific records. Implement insertion, minimum, and maximum operations to locate books
quickly
#include <stdio.h>
#include <stdlib.h>
// Function to perform an inorder traversal of the BST (to display the tree in sorted order)
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left); // Traverse the left subtree
printf("%d ", root->bookID); // Visit the root node
inorder(root->right); // Traverse the right subtree
}
}
int main() {
struct Node* root = NULL;
if (minNode != NULL) {
printf("Minimum book ID: %d\n", minNode->bookID);
} else {
printf("The tree is empty.\n");
}
if (maxNode != NULL) {
printf("Maximum book ID: %d\n", maxNode->bookID);
} else {
printf("The tree is empty.\n");
}
return 0;
}
15. A symbolic computation tool demands a program to convert infix expressions to postfix notation
for easier evaluation. The program should handle expressions like ((4+8)(6-5))/((3-2)(2+2)) and
produce their postfix equivalents. A symbolic computation tool needs a converter for infix to
postfix notation. Convert expressions like ((4+8)(6-5))/((3-2)(2+2)) into postfix form
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int i = 0, j = 0;
while (infix[i] != '\0') {
char c = infix[i];
int main() {
char infix[MAX], postfix[MAX];
// Convert to postfix
infixToPostfix(infix, postfix);
return 0;
}
16. A sorting program for organizing exam scores uses the insertion sort algorithm. The program
takes an unsorted array of scores, applies insertion sort, and outputs the scores in ascending
order. Write a C program to implement the insertion sort algorithm.
Original Array: 8 3 5 1 4
After Insertion Sort:1 3 4 5 8
#include <stdio.h>
// Move elements of arr[0..i-1] that are greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
int main() {
int arr[] = {8, 3, 5, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
17. A data processing system uses a stack to temporarily store records for processing. The system
uses a fixed-size stack (int stack[5] = {30, 40, 50, 60}) and needs to ensure that no overflows
occur when new data is added. Write a program that checks if the stack is full before inserting
new records. If a user attempts to add more records than the stack's capacity, the program
should display an error message indicating that the stack is full.
Expected Output:
Error: Stack is full! Cannot add more records.
#include <stdio.h>
#include <stdlib.h>
// Stack structure
struct Stack {
int top;
int stack[MAX_SIZE];
};
int main() {
struct Stack s;
initStack(&s);
return 0;
}
18. A shopping cart system stores item prices in a queue. The program should calculate the total
cost of all the items in the cart, displaying both the prices in the queue and the calculated sum.
If a user adds or removes items, the total should be updated accordingly. The queue needs to
handle basic enqueue and dequeue operations and show how the system computes the total cost
efficiently.
Input Example: Queue elements (prices): 1, 2, 3, 4, 5
Output Example:
Queue elements: 1 2 3 4 5
Sum of elements: 15
#include <stdio.h>
#include <stdlib.h>
// Queue structure
struct Queue {
int front, rear;
int queue[MAX_SIZE];
int totalCost; // To keep track of the sum of the prices in the queue
};
int main() {
struct Queue q;
initQueue(&q);
return 0;
}
19. A system needs to convert a given decimal number to its binary equivalent for low-level
processing. The program should take a decimal number as input and output the binary
representation. It will use the division-by-2 method to generate the binary form and output the
result. This conversion helps in performing bit-level operations in various applications. Write a
C program to convert decimal to binary.
#include <stdio.h>
int main() {
int decimal;
// Convert to binary
decimalToBinary(decimal);
return 0;
}
20. A contact management system uses a hash table to store names and phone numbers. The system
should allow adding, deleting, and searching for contacts. The hash table will efficiently manage
the contacts, ensuring quick lookups and updates. The program should provide functions to
insert a new contact, delete a contact, and search for an existing one. Implement a C program
using a hash table.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Initialize the hash table
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}
printAllContacts();
// Deleting a contact
deleteContact("Bob");
printAllContacts();
return 0;
}
21. A program allows users to reverse a linked list representing a sequence of numbers. The system
should take an existing list and reverse the order of its elements using a simple linked list
algorithm. This operation is common in situations where the order of items must be flipped,
such as in undo operations.
Input Example:
Original Linked List: 2 -> 7 -> 3 -> NULL
Output Example:
Reversed Linked List: 3 -> 7 -> 2 -> NULL
#include <stdio.h>
#include <stdlib.h>
int main() {
struct Node* head = NULL;
return 0;
}
22. A class uses an array to store student roll numbers. The program should allow users to input
roll numbers for 8 students and then print them in order. This is useful for recording and
displaying student data quickly.
Input Example:
Enter 8 roll numbers: 101, 102, 103, 104, 105, 106, 107, 108
Output Example:
Roll Numbers: 101, 102, 103, 104, 105, 106, 107, 108
Design a C program for a Binary Search Tree (BST) to manage student records by their roll
numbers. The program should perform the following operations:
Insert a new student record by roll number.
Search for a student record by roll number.
Display all student records in ascending order of roll numbers
#include <stdio.h>
#include <stdlib.h>
// Function for in-order traversal to display the roll numbers in ascending order
void inOrderTraversal(struct Node* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->roll_number);
inOrderTraversal(root->right);
}
}
int main() {
struct Node* root = NULL;
int roll_number;
return 0;
}
23. Design a C program to implement Radix Sort for sorting a list of non-negative integers in
ascending order. The program sorts elements based on each digit, starting from the least
significant digit (unit place) and progressing to more significant digits (tens, hundreds, etc.).
The program will display the intermediate results after each pass and finally print the sorted
list.
#include <stdio.h>
#include <stdlib.h>
// Function to perform counting sort on the basis of the digit represented by exp
void countingSort(int arr[], int n, int exp) {
int output[n]; // Output array to store sorted numbers
int count[10] = {0}; // Count array to store frequency of digits (0-9)
// Change count[i] so that count[i] now contains the actual position of this digit in output[]
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Copy the output array to arr[], so that arr[] now contains sorted numbers based on the
current digit
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
// Do counting sort for every digit (exp is 10^i where i is the current digit number)
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; // Example array
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
24. Design a Binary Search algorithm for the ordered list of elements. The input must be random
number generated from random function, the ordered list of elements must sorted using
insertion sort algorithm. Then, search the key elements present or not, find the time complexity
and print the results. The input size is of 15 elements
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n = 15;
int arr[n];
srand(time(0)); // Initialize random number generator
return 0;
}
25. Topological sort is a method of arranging the vertices in a directed acyclic graph (DAG), as a
sequence, such that no vertex appears in the sequence before its predecessor. A directed graph
G is a DAG if it does not have any cycle. We have a set of tasks and a set of dependencies
(precedence constraints) of form “task A must be done before task B”. Design a C program to
display the ordering of the tasks that conforms with the given dependencies.
#include <stdio.h>
#include <stdlib.h>
int main() {
struct Graph graph;
initGraph(&graph);
int main() {
srand(time(0)); // Seed for random number generation
int n = 15;
int arr[n];
if (result != -1) {
printf("\nElement %d found at index %d.\n", target, result);
} else {
printf("\nElement %d not found in the list.\n", target);
}
// Time Complexity:
printf("\nTime Complexity of Insertion Sort: O(n^2)\n");
printf("Time Complexity of Binary Search: O(log n)\n");
return 0;
}
27. A job scheduling system uses a queue to manage tasks. The system needs operations such as
checking if the queue is empty or full, enqueuing and dequeuing tasks, and fetching the front
and rear tasks. Design a C program to implement these operations for managing the task queue.
Input:
Queue is empty initially.
Operations:
Enqueue tasks A, B, C, D, E.
Check if the queue is full.
Dequeue two tasks.
Check if the queue is empty.
Output:
Queue after enqueueing: A B C D E
Is the queue full? Yes
Queue after dequeuing: C D E
Is the queue empty? No
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main() {
Queue q;
initQueue(&q);
// Enqueue tasks
enqueue(&q, "A");
enqueue(&q, "B");
enqueue(&q, "C");
enqueue(&q, "D");
enqueue(&q, "E");
return 0;
}
28. In a calculator application for a mathematical expression evaluator, the user inputs a postfix
expression to compute a result. The application needs to convert the postfix expression into a
prefix format for easier evaluation using a stack-based algorithm.
Given Input:
Postfix Expression: A B + C D - *
Expected Output:
Prefix Expression: * + A B - C D
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int isOperator(char c) {
char c = postfix[i];
top++;
strcpy(stack[top], operand);
else if (isOperator(c)) {
strcpy(operand2, stack[top]);
top--;
strcpy(operand1, stack[top]);
top--;
char newExpr[MAX];
top++;
strcpy(stack[top], newExpr);
int main() {
char postfix[MAX];
scanf("%s", postfix);
postfixToPrefix(postfix);
return 0;
29. A ticket booking system requires a deque to accept input from both ends. Tickets can only be
issued (removed) from the front to maintain sequential processing for fairness. The system will
manage ticket reservations, ensuring that new bookings are added efficiently and that customers
are processed from the front of the queue. The program will allow both adding and removing
reservations dynamically. Write a C program using a deque.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int tickets[MAX];
int front, rear;
} Deque;
int main() {
Deque dq;
initializeDeque(&dq);
while (1) {
printf("\nTicket Booking System\n");
printf("1. Book a ticket (Add to rear)\n");
printf("2. Issue a ticket (Remove from front)\n");
printf("3. Display tickets\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (isFull(&dq)) {
printf("Error: Deque is full! Cannot book more tickets.\n");
} else {
printf("Enter ticket number to book: ");
scanf("%d", &ticket);
enqueueRear(&dq, ticket);
}
break;
case 2:
dequeueFront(&dq);
break;
case 3:
display(&dq);
break;
case 4:
printf("Exiting ticket booking system...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
30. A telecom company requires a linked list where each node represents a digit from a customer’s
phone number. If the number is 54681, the list should separate odd and even digits into distinct
nodes: 5 -> 6 -> 1 -> 4 -> 8. Write a C program using a single linked list
#include <stdio.h>
#include <stdlib.h>
// Function to separate odd and even digits into two linked lists
void separateDigits(Node* head, Node** oddList, Node** evenList) {
while (head != NULL) {
if (head->digit % 2 == 0) {
appendNode(evenList, head->digit); // Even digits
} else {
appendNode(oddList, head->digit); // Odd digits
}
head = head->next;
}
}
int main() {
// Input the phone number as a linked list of digits
Node* phoneNumber = NULL;
Node* oddDigits = NULL;
Node* evenDigits = NULL;
return 0;
}