0% found this document useful (0 votes)
35 views403 pages

SYBSc Computer Slips

Uploaded by

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

SYBSc Computer Slips

Uploaded by

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

SAVITIBAI PHULE UNIVERSITY OF PUNE

S. Y. B.Sc. (Computer Science) Semester III


Practical Examination
SUBJECT: CS-233 Practical course based on CS231

Time: 3 hours Max. Marks: 35

Slip1

Q1.
Implement a list library (doublylist.h) for a doubly linked list of integers with the create, display operations. Write a menu driven
program to call these operations. [10]
 #include

<stdio.h>

#include

<stdlib.h>

// Node structure for the doubly linked list

typedef struct Node {

int data;

struct Node* prev;

struct Node* next;

} Node;

// Structure for the doubly linked list

typedef struct DoublyLinkedList {

Node* head;

} DoublyLinkedList;

// Function to create a new doubly linked list

DoublyLinkedList* createList() {

DoublyLinkedList* list = (DoublyLinkedList*)malloc(sizeof(DoublyLinkedList));

list->head = NULL;

return list;

// Function to append a node to the list

void appendNode(DoublyLinkedList* list, int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

if (list->head == NULL) {

newNode->prev = NULL;

list->head = newNode;

return;

Node* last = list->head;

while (last->next != NULL) {


last = last->next;

last->next = newNode;

newNode->prev = last;

// Function to display the list

void displayList(DoublyLinkedList* list) {

Node* current = list->head;

if (current == NULL) {

printf("List is empty.\n");

return;

printf("Doubly Linked List: ");

while (current != NULL) {

printf("%d ", current->data);

current = current->next;

printf("\n");

// Main function with menu-driven interface

int main() {

DoublyLinkedList* list = createList();

int choice, data;

while (1) {

printf("Menu:\n");

printf("1. Append Node\n");

printf("2. Display List\n");

printf("3. Exit\n");

printf("Enter your choice:

"); scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter integer to append: ");


scanf("%d", &data);

appendNode(list, data);

break;

case 2:

displayList(list);

break;

case 3:

free(list);

exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

Q2. Write a program that sorts the elements of linked list using any of sorting technique.
-> #include <stdio.h>
#include <stdlib.h>
// Node structure for 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));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to append a node to the list
void appendNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// Function to display the list
void displayList(Node* head) {
Node* current = head;
if (current == NULL) {
printf("List is empty.\n");
return;
}
printf("Linked List: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Function to sort the linked list using Bubble Sort
void bubbleSort(Node* head) {
if (head == NULL) return;
int swapped;
Node *ptr1;
Node *lptr = NULL;
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
// Swap data
int temp = ptr1->data;
ptr1->data = ptr1->next->data;
ptr1->next->data = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
// Main function with menu-driven interface
int main() {
Node* head = NULL;
int choice, data;
while (1) {
printf("Menu:\n");
printf("1. Append Node\n");
printf("2. Display List\n");
printf("3. Sort List\n");
printf("4. Exit\n");
printf("Enter your choice:
"); scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter integer to append: ");
scanf("%d", &data);
appendNode(&head, data);
break;
case 2:
displayList(head);
break;
case 3:
bubbleSort(head);
printf("List sorted.\n");
break;
case 4:
// Free the list before exiting
while (head != NULL) {
Node* temp = head;
head = head->next;
free(temp);
}
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}

Slip 2
Q1.Implement a list library (singlylist.h) for a singly linked list of integer with the operations create, display. Write a menu driven
program to call these operations [10]
 #include
<stdio.h>
#include
<stdlib.h>

// Node structure for the singly 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));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to append a node to the list


void appendNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}

Node* last = *head;


while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}

// Function to display the list


void displayList(Node* head) {
Node* current = head;
if (current == NULL) {
printf("List is empty.\n");
return;
}

printf("Singly Linked List: ");


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

// Main function with menu-driven interface


int main() {
Node* head = NULL; // Initialize head of the list
int choice, data;

while (1) {
printf("Menu:\n");
printf("1. Append Node\n");
printf("2. Display List\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter integer to append: ");
scanf("%d", &data);
appendNode(&head, data);
break;
case 2:
displayList(head);
break;
case 3:
// Free the list before exiting
while (head != NULL) {
Node* temp = head;
head = head->next;
free(temp);
}
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

Q2. Write a program that copies the contents of one stack into another. Use stack library to perform basic stack operations. The
order of two stacks must be identical.(Hint: Use a temporary stack to preserve the order).
 #include
<stdio.h>
#include
<stdlib.h>

#define MAX 100


typedef struct {
int data[MAX];
int top;
} Stack;

// Function prototypes
void initStack(Stack *s);
int isFull(Stack *s);
int isEmpty(Stack *s);
void push(Stack *s, int value);
int pop(Stack *s);
void copyStack(Stack *source, Stack *destination);

int main() {
Stack stack1, stack2;
initStack(&stack1);
initStack(&stack2);

// Push some values onto stack1


push(&stack1, 10);
push(&stack1, 20);
push(&stack1, 30);

// Copy contents of stack1 to stack2


copyStack(&stack1, &stack2);

// Display contents of stack2


printf("Contents of stack2 after copying from stack1:\n");
while (!isEmpty(&stack2)) {
printf("%d\n", pop(&stack2));
}

return 0;
}

// Stack functions
void initStack(Stack *s) {
s->top = -1;
}

int isFull(Stack *s) {


return s->top == MAX - 1;
}

int isEmpty(Stack *s) {


return s->top == -1;
}

void push(Stack *s, int value) {


if (!isFull(s)) {
s->data[++s->top] = value;
} else {
printf("Stack overflow\n");
}
}
int pop(Stack *s) {
if (!isEmpty(s)) {
return s->data[s->top--];
} else {
printf("Stack underflow\n");
return -1; // Error value
}
}

void copyStack(Stack *source, Stack *destination) {


Stack temp;
initStack(&temp);

// Move items from source to temporary stack


while (!isEmpty(source)) {
push(&temp, pop(source));
}

// Move items from temporary stack to destination


while (!isEmpty(&temp)) {
int value = pop(&temp);
push(source, value); // Restore original stack
push(destination, value); // Copy to destination
}
} [20]

Slip3
Sort a random array of n integers (accept the value of n from user) in ascending order by using insertion sort algorithm.
[10]
 #include
<stdio.h>
#include
<stdlib.h>
#include
<time.h>

void insertionSort(int arr[], int n);


void printArray(int arr[], int n);

int main() {
int n;

// Seed the random number generator


srand(time(0));

// Accept the size of the array from the user


printf("Enter the number of integers (n): ");
scanf("%d", &n);

// Allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Generate random integers and fill the array


printf("Generated array:\n");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // Random integers between 0 and 99
printf("%d ", arr[i]);
}
printf("\n");

// Sort the array using insertion sort


insertionSort(arr, n);

// Print the sorted array


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

// Free the allocated memory


free(arr);

return 0;
}

// Insertion Sort Function


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

// Move elements of arr[0..i-1], that are greater than key,


// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// Function to print the array


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

Q2. Write a C program to evaluate postfix expression. [20]


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

#define MAX 100

typedef struct {
int data[MAX];
int top;
} Stack;

// Function prototypes
void initStack(Stack *s);
int isFull(Stack *s);
int isEmpty(Stack *s);
void push(Stack *s, int value);
int pop(Stack *s);
int evaluatePostfix(const char *expression);

int main() {
char expression[MAX];

// Read the postfix expression from the user


printf("Enter a postfix expression (e.g. 23 34 + 5 *) : ");
fgets(expression, sizeof(expression), stdin);

// Evaluate the postfix expression


int result = evaluatePostfix(expression);

// Print the result


printf("The result of the postfix expression is: %d\n", result);

return 0;
}

// Stack functions
void initStack(Stack *s) {
s->top = -1;
}

int isFull(Stack *s) {


return s->top == MAX - 1;
}

int isEmpty(Stack *s) {


return s->top == -1;
}

void push(Stack *s, int value) {


if (!isFull(s)) {
s->data[++s->top] = value;
} else {
printf("Stack overflow\n");
}
}

int pop(Stack *s) {


if (!isEmpty(s)) {
return s->data[s->top--];
} else {
printf("Stack underflow\n");
return -1; // Error value
}
}

// Function to evaluate postfix expression


int evaluatePostfix(const char *expression) {
Stack stack;
initStack(&stack);
int i = 0;
char token[10];
while (sscanf(expression + i, "%s", token) == 1) {
if (isdigit(token[0])) {
// Convert token to integer and push onto the stack
push(&stack, atoi(token));
} else {
// It's an operator
int b = pop(&stack);
int a = pop(&stack);
switch (token[0]) {
case '+':
push(&stack, a + b);
break;
case '-':
push(&stack, a - b);
break;
case '*':
push(&stack, a * b);
break;
case '/':
push(&stack, a / b);
break;
default:
printf("Unknown operator: %c\n", token[0]);
return -1; // Error value
}
}
// Move to the next token
i += strlen(token) + 1; // +1 for the space
}

// The result should be the only value left in the stack


return pop(&stack);
}

Slip4
Read
the ‘n’ numbers from user and sort using bubble sort. [10]

-> #include <stdio.h>

void bubbleSort(int arr[], int n);


void printArray(int arr[], int n);

int main() {
int n;

// Accept the number of integers from the user


printf("Enter the number of integers (n): ");
scanf("%d", &n);

// Declare an array to hold the numbers


int arr[n];

// Read the numbers from the user


printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort the array using bubble sort
bubbleSort(arr, n);

// Print the sorted array


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

return 0;
}

// Bubble Sort Function


void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to print the array


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

Q2. Write a program to reverse the elements of a queue using queue library.
Implement basic queue operations init, enqueue, dequeue. [20]
 #include
<stdio.h>
#include
<stdlib.h>

#define MAX 100

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

// Function prototypes
void initQueue(Queue *q);
int isFull(Queue *q);
int isEmpty(Queue *q);
void enqueue(Queue *q, int value);
int dequeue(Queue *q);
void reverseQueue(Queue *q);
void printQueue(Queue *q);

int main() {
Queue q;
initQueue(&q);
// Enqueue some values
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
enqueue(&q, 40);
enqueue(&q, 50);

printf("Original queue:\n");
printQueue(&q);

// Reverse the queue


reverseQueue(&q);

printf("Reversed queue:\n");
printQueue(&q);

return 0;
}

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

int isFull(Queue *q) {


return q->rear == MAX - 1;
}

int isEmpty(Queue *q) {


return q->front > q->rear;
}

void enqueue(Queue *q, int value) {


if (!isFull(q)) {
q->data[++q->rear] = value;
} else {
printf("Queue overflow\n");
}
}

int dequeue(Queue *q) {


if (!isEmpty(q)) {
return q->data[q->front++];
} else {
printf("Queue underflow\n");
return -1; // Error value
}
}

// Function to reverse the queue


void reverseQueue(Queue *q) {
int size = q->rear - q->front + 1;
int *temp = (int *)malloc(size * sizeof(int));

// Dequeue elements and store them in the temp array


for (int i = 0; i < size; i++) {
temp[i] = dequeue(q);
}

// Enqueue the elements back in reverse order


for (int i = size - 1; i >= 0; i--) {
enqueue(q, temp[i]);
}

// Free the temporary array


free(temp);
}

// Function to print the queue


void printQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->data[i]);
}
printf("\n");
}

Slip 5
1) Create a random array of n integers. Accept a value x from user and use linear search algorithm to check whether the number is
present in the array or not and output the position if the number is
present. [10]
 #include
<stdio.h>
#include
<stdlib.h>
#include
<time.h>

void linearSearch(int arr[], int n, int x);

int main() {
int n, x;

// Seed the random number generator


srand(time(0));

// Accept the size of the array from the user


printf("Enter the number of integers (n): ");
scanf("%d", &n);

// Allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Generate random integers and fill the array


printf("Generated array:\n");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // Random integers between 0 and 99
printf("%d ", arr[i]);
}
printf("\n");

// Accept the value to search for


printf("Enter the value to search for: ");
scanf("%d", &x);

// Perform linear search


linearSearch(arr, n, x);

// Free the allocated memory


free(arr);

return 0;
}

// Linear Search Function


void linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
printf("Value %d found at position: %d\n", x, i);
return;
}
}
printf("Value %d not found in the array.\n", x);
}

Q2. Implement a priority queue library (PriorityQ.h) of integers using a static implementation of the queue and implement the
below two operations.

1) Add an element with its priority into the queue.


2) Delete an element from queue according to its priority. [20]
- > #include <stdio.h>
#include <stdlib.h>

#define MAX 100

typedef struct {
int value; // The value stored in the queue
int priority; // The priority of the value
} Element;

typedef struct {
Element elements[MAX];
int size; // Current number of elements in the priority queue
} PriorityQueue;

// Function prototypes
void initPriorityQueue(PriorityQueue *pq);
int isFull(PriorityQueue *pq);
int isEmpty(PriorityQueue *pq);
void enqueue(PriorityQueue *pq, int value, int priority);
int dequeue(PriorityQueue *pq);
void printPriorityQueue(PriorityQueue *pq);

int main() {
PriorityQueue pq;
initPriorityQueue(&pq);

// Add some elements with priorities


enqueue(&pq, 10, 1);
enqueue(&pq, 20, 3);
enqueue(&pq, 30, 2);
enqueue(&pq, 40, 0); // Highest priority

// Print the current state of the priority queue


printf("Current Priority Queue:\n");
printPriorityQueue(&pq);

// Dequeue elements based on priority


printf("Dequeued element: %d\n", dequeue(&pq));
printf("Current Priority Queue after dequeue:\n");
printPriorityQueue(&pq);

printf("Dequeued element: %d\n", dequeue(&pq));


printf("Current Priority Queue after dequeue:\n");
printPriorityQueue(&pq);

return 0;
}

// Initialize the priority queue


void initPriorityQueue(PriorityQueue *pq) {
pq->size = 0;
}

// Check if the priority queue is full


int isFull(PriorityQueue *pq) {
return pq->size == MAX;
}

// Check if the priority queue is empty


int isEmpty(PriorityQueue *pq) {
return pq->size == 0;
}

// Add an element with its priority into the queue


void enqueue(PriorityQueue *pq, int value, int priority) {
if (isFull(pq)) {
printf("Priority Queue is full. Cannot enqueue %d.\n", value);
return;
}

Element newElement = {value, priority};


int i;

// Find the position to insert the new element based on priority


for (i = pq->size - 1; (i >= 0 && pq->elements[i].priority > priority); i--) {
pq->elements[i + 1] = pq->elements[i]; // Shift elements to the right
}
pq->elements[i + 1] = newElement; // Insert the new element
pq->size++;
}

// Delete an element from the queue according to its priority


int dequeue(PriorityQueue *pq) {
if (isEmpty(pq)) {
printf("Priority Queue is empty. Cannot dequeue.\n");
return -1; // Error value
}

return pq->elements[--pq->size].value; // Remove and return the highest priority element


}

// Print the elements of the priority queue


void printPriorityQueue(PriorityQueue *pq) {
if (isEmpty(pq)) {
printf("Priority Queue is empty.\n");
return;
}

printf("Priority Queue elements (value: priority):\n");


for (int i = 0; i < pq->size; i++) {
printf("%d: %d\n", pq->elements[i].value, pq->elements[i].priority);
}
}

Slip6
Sort a random array of n integers (accept the value of n from user) in ascending order by using selection sort algorithm.
[10]
 #include
<stdio.h>
#include
<stdlib.h>
#include
<time.h>

void selectionSort(int arr[], int n);


void printArray(int arr[], int n);

int main() {
int n;

// Seed the random number generator


srand(time(0));

// Accept the size of the array from the user


printf("Enter the number of integers (n): ");
scanf("%d", &n);

// Allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Generate random integers and fill the array


printf("Generated array:\n");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // Random integers between 0 and 99
printf("%d ", arr[i]);
}
printf("\n");

// Sort the array using selection sort


selectionSort(arr, n);

// Print the sorted array


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

// Free the allocated memory


free(arr);

return 0;
}

// Selection Sort Function


void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the minimum is the first element
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update the index of the minimum element
}
}
// Swap the found minimum element with the first element
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}

// Function to print the array


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

Q2. Implement a queue library (dyqueue.h) of integers using a dynamic


(linked list) implementation of the queue and implement init, enqueue,
dequeue, isempty, peek operations. [20]
 #include
<stdio.h>
#include
<stdlib.h>

// Node structure for linked list


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

// Queue structure
typedef struct Queue {
Node *front;
Node *rear;
} Queue;

// Function prototypes
void initQueue(Queue *q);
int isEmpty(Queue *q);
void enqueue(Queue *q, int value);
int dequeue(Queue *q);
int peek(Queue *q);
void freeQueue(Queue *q);

int main() {
Queue q;
initQueue(&q);

// Enqueue some elements


enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);

printf("Front element: %d\n", peek(&q));

// Dequeue elements
printf("Dequeued: %d\n", dequeue(&q));
printf("Front element: %d\n", peek(&q));

// Dequeue the remaining elements


printf("Dequeued: %d\n", dequeue(&q));
printf("Dequeued: %d\n", dequeue(&q));

// Check if the queue is empty


if (isEmpty(&q)) {
printf("The queue is empty.\n");
} else {
printf("The queue is not empty.\n");
}

// Free the queue resources


freeQueue(&q);

return 0;
}

// Initialize the queue


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

// Check if the queue is empty


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

// Add an element to the queue


void enqueue(Queue *q, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;

if (isEmpty(q)) {
q->front = newNode; // If the queue is empty
q->rear = newNode; // Set front and rear to the new node
} else {
q->rear->next = newNode; // Link the new node to the end of the queue
q->rear = newNode; // Update the rear to the new node
}
}

// Remove an element from the queue


int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue underflow. Cannot dequeue.\n");
return -1; // Error value
}
Node *temp = q->front;
int value = temp->data;
q->front = q->front->next; // Move front to the next node
if (q->front == NULL) {
q->rear = NULL; // If the queue becomes empty
}
free(temp); // Free the dequeued node
return value;
}

// Peek at the front element


int peek(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot peek.\n");
return -1; // Error value
}
return q->front->data; // Return the front element
}

// Free all nodes in the queue


void freeQueue(Queue *q) {
while (!isEmpty(q)) {
dequeue(q); // Dequeue all elements to free memory
}
}

Slip 7
Sort a random array of n integers (accept the value of n from user) in ascending order by using quick sort algorithm. [10]
-> #include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function prototypes
void quickSort(int arr[], int low, int high);
int partition(int arr[], int low, int high);
void printArray(int arr[], int n);

int main() {
int n;

// Seed the random number generator


srand(time(0));

// Accept the size of the array from the user


printf("Enter the number of integers (n): ");
scanf("%d", &n);
// Allocate memory for the array
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Generate random integers and fill the array


printf("Generated array:\n");
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // Random integers between 0 and 99
printf("%d ", arr[i]);
}
printf("\n");

// Sort the array using quicksort


quickSort(arr, 0, n - 1);

// Print the sorted array


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

// Free the allocated memory


free(arr);

return 0;
}

// QuickSort Function
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high); // Partitioning index
quickSort(arr, low, pi - 1); // Sort elements before partition
quickSort(arr, pi + 1, high); // Sort elements after partition
}
}

// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choosing the last element as pivot
int i = (low - 1); // Index of the smaller element

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i + 1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1; // Return the partitioning index


}

// Function to print the array


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

Q2. Write a program that checks whether a string of characters is palindrome or not. The function should use a stack library
(cststack.h) of stack of characters using a static implementation of the stack. [20]
 #include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>
#include
<ctype.h>

#define MAX 100

// Stack structure for characters


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

// Function prototypes
void initStack(Stack *s);
int isFull(Stack *s);
int isEmpty(Stack *s);
void push(Stack *s, char item);
char pop(Stack *s);
char peek(Stack *s);
int isPalindrome(const char *str);

int main() {
char str[MAX];

// Get user input


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove newline character if present


str[strcspn(str, "\n")] = 0;

// Check if the string is a palindrome


if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}

return 0;
}

// Initialize the stack


void initStack(Stack *s) {
s->top = -1;
}
// Check if the stack is full
int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Check if the stack is empty


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

// Push an item onto the stack


void push(Stack *s, char item) {
if (!isFull(s)) {
s->items[++s->top] = item;
}
}

// Pop an item from the stack


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

// Peek at the top item of the stack


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

// Function to check if a string is a palindrome


int isPalindrome(const char *str) {
Stack s;
initStack(&s);
int length = strlen(str);

// Push characters onto the stack


for (int i = 0; i < length; i++) {
if (isalnum(str[i])) { // Check for alphanumeric characters
push(&s, tolower(str[i])); // Convert to lowercase and push onto stack
}
}

// Compare characters
for (int i = 0; i < length; i++) {
if (isalnum(str[i])) {
char topChar = pop(&s); // Pop from stack
if (tolower(str[i]) != topChar) {
return 0; // Not a palindrome
}
}
}
return 1; // It is a palindrome
}
Slip 8
1 )Implement a list library (singlylist.h) for a singly linked list of integer With the operations create, delete specific element and
display. Write a menu driven program to call these operations [10]
 #include
<stdio.h>
#include
<stdlib.h>

// Node structure for singly linked list


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

// Function prototypes
Node* createList();
void displayList(Node* head);
Node* deleteElement(Node* head, int value);
void freeList(Node* head);

int main() {
Node* head = NULL;
int choice, value;

do {
printf("\nMenu:\n");
printf("1. Create List\n");
printf("2. Display List\n");
printf("3. Delete Specific Element\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
head = createList();
printf("List created successfully.\n");
break;
case 2:
printf("List contents: ");
displayList(head);
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &value);
head = deleteElement(head, value);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

// Free the list before exiting


freeList(head);
return 0;
}
// Create a singly linked list
Node* createList() {
Node* head = NULL;
Node* tail = NULL;
int value;
char choice;

do {
printf("Enter an integer to add to the list: ");
scanf("%d", &value);

Node* newNode = (Node*)malloc(sizeof(Node));


newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
head = newNode; // First node
tail = newNode;
} else {
tail->next = newNode; // Link new node
tail = newNode; // Update tail
}

printf("Do you want to add another element? (y/n): ");


scanf(" %c", &choice); // Notice the space before %c to consume newline
} while (choice == 'y' || choice == 'Y');

return head;
}

// Display the contents of the list


void displayList(Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

// Delete a specific element from the list


Node* deleteElement(Node* head, int value) {
if (head == NULL) {
printf("The list is empty. Cannot delete.\n");
return NULL;
}

Node* current = head;


Node* previous = NULL;

// Traverse the list to find the value


while (current != NULL && current->data != value) {
previous = current;
current = current->next;
}

// If the value was not found


if (current == NULL) {
printf("Value %d not found in the list.\n", value);
return head;
}

// If the value is found and it's the first node


if (previous == NULL) {
head = current->next; // Update head
} else {
previous->next = current->next; // Bypass the current node
}

free(current); // Free the memory of the deleted node


printf("Value %d deleted from the list.\n", value);
return head;
}

// Free the entire list


void freeList(Node* head) {
Node* current = head;
Node* next;

while (current != NULL) {


next = current->next;
free(current);
current = next;
}
}

Q2. Write a C program to check whether the contents of two stacks are identical. Use stack library to perform basic stack operations.
Neither
stack should be changed. [20]
 #include
<stdio.h>
#include
<stdlib.h>

#define MAX 100

// Stack structure
typedef struct {
int items[MAX];
int top;
} Stack;

// Function prototypes
void initStack(Stack *s);
int isFull(Stack *s);
int isEmpty(Stack *s);
void push(Stack *s, int item);
int pop(Stack *s);
int peek(Stack *s);
int areStacksIdentical(Stack *s1, Stack *s2);

int main() {
Stack stack1, stack2;
// Initialize stacks
initStack(&stack1);
initStack(&stack2);

// Input elements for stack 1


printf("Enter 3 elements for Stack 1:\n");
for (int i = 0; i < 3; i++) {
int value;
printf("Element %d: ", i + 1);
scanf("%d", &value);
push(&stack1, value);
}

// Input elements for stack 2


printf("Enter 3 elements for Stack 2:\n");
for (int i = 0; i < 3; i++) {
int value;
printf("Element %d: ", i + 1);
scanf("%d", &value);
push(&stack2, value);
}

// Check if stacks are identical


if (areStacksIdentical(&stack1, &stack2)) {
printf("The stacks are identical.\n");
} else {
printf("The stacks are not identical.\n");
}

return 0;
}

// Initialize the stack


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

// Check if the stack is full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Check if the stack is empty


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

// Push an item onto the stack


void push(Stack *s, int item) {
if (!isFull(s)) {
s->items[++s->top] = item;
}
}

// Pop an item from the stack


int pop(Stack *s) {
if (!isEmpty(s)) {
return s->items[s->top--];
}
return -1; // Return -1 if stack is empty (error value)
}

// Peek at the top item of the stack


int peek(Stack *s) {
if (!isEmpty(s)) {
return s->items[s->top];
}
return -1; // Return -1 if stack is empty (error value)
}

// Function to check if two stacks are identical


int areStacksIdentical(Stack *s1, Stack *s2) {
// Temporary stacks to hold values for comparison
Stack temp1, temp2;
initStack(&temp1);
initStack(&temp2);

// Check if sizes are equal first


if (s1->top != s2->top) {
return 0; // Not identical if sizes are different
}

// Compare elements
for (int i = 0; i <= s1->top; i++) {
int val1 = s1->items[i];
int val2 = s2->items[i];

// Push to temporary stacks


push(&temp1, val1);
push(&temp2, val2);

// If they are not equal, the stacks are not identical


if (val1 != val2) {
return 0; // Not identical
}
}

// Restore original stacks


while (!isEmpty(&temp1)) {
push(s1, pop(&temp1));
push(s2, pop(&temp2));
}

return 1; // Stacks are identical


}
Slip 9

Q1. Write a program to convert an infix expression of the form (a*(b+c)*((d-


a)/b)) into its equivalent postfix notation. Consider usual precedence’s of operators. Use stack library of stack of characters using static
implementation.

-> #include

<stdio.h> #include

<stdlib.h>

#include <ctype.h>

#define MAX 100

// Stack structure

typedef struct {

char items[MAX];
int top;

} Stack;

// Function prototypes

void initStack(Stack *s);

int isFull(Stack *s);

int isEmpty(Stack *s);

void push(Stack *s, char item);

char pop(Stack *s);

char peek(Stack *s);

int precedence(char op);


void infixToPostfix(const char *infix, char *postfix);

int main() {

char infix[MAX];

char postfix[MAX];

// Input infix expression

printf("Enter an infix expression: ");

fgets(infix, sizeof(infix), stdin);

// Remove newline character if present


infix[strcspn(infix, "\n")] = 0;

// Convert infix to postfix

infixToPostfix(infix, postfix);

// Output postfix expression

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

return 0;

}
// Initialize the stack

void initStack(Stack *s) {

s->top = -1;

// Check if the stack is full

int isFull(Stack *s) {

return s->top == MAX - 1;

// Check if the stack is empty


int isEmpty(Stack *s) {

return s->top == -1;

// Push an item onto the stack

void push(Stack *s, char item) {

if (!isFull(s)) {

s->items[++s->top] = item;

}
// Pop an item from the stack

char pop(Stack *s) {

if (!isEmpty(s)) {

return s->items[s->top--];

return '\0'; // Return null character if stack is empty

// Peek at the top item of the stack

char peek(Stack *s) {

if (!isEmpty(s)) {
return s->items[s->top];

return '\0'; // Return null character if stack is empty

// Function to determine precedence of operators

int precedence(char op) {

switch (op) {

case '+':

case '-':

return 1;
case '*':

case '/':

return 2;

case '^':

return 3; // Assuming right associativity for exponentiation

default:

return 0;

// Function to convert infix expression to postfix


void infixToPostfix(const char *infix, char *postfix) {

Stack stack;

initStack(&stack);

int j = 0; // Index for postfix array

for (int i = 0; infix[i] != '\0'; i++) {

char current = infix[i];

if (isalnum(current)) { // If the character is an operand

postfix[j++] = current; // Add operand to postfix

} else if (current == '(') {


push(&stack, current); // Push '(' onto stack

} else if (current == ')') {

while (!isEmpty(&stack) && peek(&stack) != '(') {

postfix[j++] = pop(&stack); // Pop until '('

pop(&stack); // Pop the '('

} else { // Operator

while (!isEmpty(&stack) && precedence(peek(&stack)) >= precedence(current)) {

postfix[j++] = pop(&stack); // Pop operators with higher or equal precedence

push(&stack, current); // Push current operator onto stack


}

// Pop all remaining operators from the stack

while (!isEmpty(&stack)) {

postfix[j++] = pop(&stack);

postfix[j] = '\0'; // Null-terminate the postfix string

} [10]
Q2 Read the data from the ‘employee.txt’ file and sort on age using Counting sort or Quick sort and write the sorted data to another
file 'sortedemponage.txt'.
#include <stdio.h>

-> #include

<stdlib.h>

#include <string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

// Employee structure

typedef struct {

char name[NAME_LENGTH];

int age;
} Employee;

// Function prototypes

void readEmployees(const char *filename, Employee employees[], int *count);

void writeEmployees(const char *filename, Employee employees[], int count);

void quickSort(Employee employees[], int low, int high);

int partition(Employee employees[], int low, int high);

void swap(Employee *a, Employee *b);

int main() {

Employee employees[MAX_EMPLOYEES];

int count = 0;
// Read employees from the file

readEmployees("employee.txt", employees, &count);

// Sort employees by age

quickSort(employees, 0, count - 1);

// Write sorted employees to the output file

writeEmployees("sortedemponage.txt", employees, count);

printf("Employees sorted by age have been written to 'sortedemponage.txt'.\n");


return 0;

// Function to read employees from a file

void readEmployees(const char *filename, Employee employees[], int *count) {

FILE *file = fopen(filename, "r");

if (file == NULL) {

perror("Could not open file for reading");

exit(EXIT_FAILURE);

while (fscanf(file, "%s %d", employees[*count].name, &employees[*count].age) != EOF) {


(*count)++;

if (*count >= MAX_EMPLOYEES) {

break; // Avoid exceeding array size

fclose(file);

// Function to write employees to a file

void writeEmployees(const char *filename, Employee employees[], int count) {

FILE *file = fopen(filename, "w");


if (file == NULL) {

perror("Could not open file for writing");

exit(EXIT_FAILURE);

for (int i = 0; i < count; i++) {

fprintf(file, "%s %d\n", employees[i].name, employees[i].age);

fclose(file);

}
// Quick Sort function

void quickSort(Employee employees[], int low, int high) {

if (low < high) {

int pi = partition(employees, low, high);

quickSort(employees, low, pi - 1);

quickSort(employees, pi + 1, high);

// Partition function for Quick Sort

int partition(Employee employees[], int low, int high) {

int pivot = employees[high].age;


int i = (low - 1); // Index of smaller element

for (int j = low; j < high; j++) {

if (employees[j].age < pivot) {

i++;

swap(&employees[i], &employees[j]);

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

return (i + 1);

}
// Swap function

void swap(Employee *a, Employee *b) {

Employee temp = *a;

*a = *b;

*b = temp;

} [20]

Slip 10
Implement a linear queue library (st_queue.h) of integers using a static implementation of the queue and implementing the init(Q),
add(Q) and peek(Q) operations. Write a program that includes queue library and calls different
queue operations [10]

 #include

<stdio.h>

#include

<stdlib.h>
#define MAX 100

// Queue structure

typedef struct {

int items[MAX];

int front;

int rear;

} Queue;

// Function prototypes

void initQueue(Queue *q);


int isFull(Queue *q);

int isEmpty(Queue *q);

void add(Queue *q, int item);

int peek(Queue *q);

void displayQueue(Queue *q);

int main() {

Queue q;

initQueue(&q);

// Adding elements to the queue


add(&q, 10);

add(&q, 20);

add(&q, 30);

printf("Queue after adding elements:\n");

displayQueue(&q);

// Peek at the front element

printf("Front element: %d\n", peek(&q));

// Add more elements


add(&q, 40);

add(&q, 50);

printf("Queue after adding more elements:\n");

displayQueue(&q);

return 0;

// Initialize the queue

void initQueue(Queue *q) {


q->front = -1;

q->rear = -1;

// Check if the queue is full

int isFull(Queue *q) {

return q->rear == MAX - 1;

// Check if the queue is empty

int isEmpty(Queue *q) {


return q->front == -1 || q->front > q->rear;

// Add an item to the queue

void add(Queue *q, int item) {

if (isFull(q)) {

printf("Queue is full. Cannot add %d\n", item);

return;

if (isEmpty(q)) {

q->front = 0; // Set front to 0 if queue was empty


}

q->items[++q->rear] = item; // Increment rear and add item

// Peek at the front item of the queue

int peek(Queue *q) {

if (isEmpty(q)) {

printf("Queue is empty. Nothing to peek.\n");

return -1; // Return -1 if queue is empty

return q->items[q->front]; // Return front item


}

// Display the elements in the queue

void displayQueue(Queue *q) {

if (isEmpty(q)) {

printf("Queue is empty.\n");

return;

printf("Queue elements: ");

for (int i = q->front; i <= q->rear; i++) {

printf("%d ", q->items[i]);


}

printf("\n");

Q2. Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection
sort. [20]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50
// Employee structure

typedef struct {

char name[NAME_LENGTH];

int age;

} Employee;

// Function prototypes

void readEmployees(const char *filename, Employee employees[], int *count);

void writeEmployees(const char *filename, Employee employees[], int count);

void bubbleSort(Employee employees[], int count);

int main() {

Employee employees[MAX_EMPLOYEES];
int count = 0;

// Read employees from the file

readEmployees("employee.txt", employees, &count);

// Sort employees by name

bubbleSort(employees, count);

// Write sorted employees to the output file

writeEmployees("sorted_employees.txt", employees, count);

printf("Employees sorted by name have been written to 'sorted_employees.txt'.\n");


return 0;

// Function to read employees from a file

void readEmployees(const char *filename, Employee employees[], int *count) {

FILE *file = fopen(filename, "r");

if (file == NULL) {

perror("Could not open file for reading");

exit(EXIT_FAILURE);

while (fscanf(file, "%s %d", employees[*count].name, &employees[*count].age) != EOF) {

(*count)++;
if (*count >= MAX_EMPLOYEES) {

break; // Avoid exceeding array size

fclose(file);

// Function to write employees to a file

void writeEmployees(const char *filename, Employee employees[], int count) {

FILE *file = fopen(filename, "w");

if (file == NULL) {

perror("Could not open file for writing");


exit(EXIT_FAILURE);

for (int i = 0; i < count; i++) {

fprintf(file, "%s %d\n", employees[i].name, employees[i].age);

fclose(file);

// Bubble Sort function to sort employees by name

void bubbleSort(Employee employees[], int count) {

for (int i = 0; i < count - 1; i++) {


for (int j = 0; j < count - i - 1; j++) {

if (strcmp(employees[j].name, employees[j + 1].name) > 0) {

// Swap employees[j] and employees[j + 1]

Employee temp = employees[j];

employees[j] = employees[j + 1];

employees[j + 1] = temp;

Slip 11
Accept n values in array from user. Accept a value x from user and use sentinel linear search algorithm to check whether the number is
present in the array or not and output the position if the number is present. [10]
 #include <stdio.h>

int sentinelLinearSearch(int arr[], int n, int x);

int main() {

int n, x;

// Accept the number of elements in the array

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

scanf("%d", &n);

int arr[n];
// Accept values in the array

printf("Enter %d values:\n", n);

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

scanf("%d", &arr[i]);

// Accept the value to search

printf("Enter the value to search for: ");

scanf("%d", &x);

// Perform sentinel linear search


int position = sentinelLinearSearch(arr, n, x);

// Output the result

if (position != -1) {

printf("Value %d found at position: %d\n", x, position);

} else {

printf("Value %d not found in the array.\n", x);

return 0;

}
// Sentinel Linear Search function

int sentinelLinearSearch(int arr[], int n, int x) {

// Store the last element

int last = arr[n - 1];

arr[n - 1] = x; // Place x at the end of the array as a sentinel

int i = 0;

while (arr[i] != x) {

i++;

// Restore the last element


arr[n - 1] = last;

// If found, return the position; if not, return -1

if (i < n - 1 || arr[n - 1] == x) {

return i; // Return index if found

} else {

return -1; // Return -1 if not found

Q2. Implement a priority queue library (PriorityQ.h) of integers using a static implementation of the queue and implementing the below
two operations. Write a driver program that includes queue library and calls different queue operations.

1) Add an element with its priority into the queue.


2) Delete an element from queue according to its priority. [20]

-> #include <stdio.h>

#include <stdlib.h>

#define MAX 100

// Structure to represent a priority queue element


typedef struct {
int data; // The data of the element
int priority; // The priority of the element
} Element;

// Priority Queue structure


typedef struct {
Element items[MAX];
int front;
int rear;
} PriorityQueue;

// Function prototypes
void initQueue(PriorityQueue *pq);
int isFull(PriorityQueue *pq);
int isEmpty(PriorityQueue *pq);
void add(PriorityQueue *pq, int data, int priority);
Element delete(PriorityQueue *pq);
void displayQueue(PriorityQueue *pq);

int main() {
PriorityQueue pq;
initQueue(&pq);

// Adding elements with priority


add(&pq, 10, 1);
add(&pq, 20, 3);
add(&pq, 30, 2);
add(&pq, 40, 5);
add(&pq, 50, 4);

printf("Priority Queue after adding elements:\n");


displayQueue(&pq);

// Deleting elements according to priority


printf("Deleted element: %d\n", delete(&pq).data);
printf("Deleted element: %d\n", delete(&pq).data);

printf("Priority Queue after deletions:\n");


displayQueue(&pq);

return 0;
}

// Initialize the priority queue


void initQueue(PriorityQueue *pq) {
pq->front = -1;
pq->rear = -1;
}

// Check if the priority queue is full


int isFull(PriorityQueue *pq) {
return pq->rear == MAX - 1;
}

// Check if the priority queue is empty


int isEmpty(PriorityQueue *pq) {
return pq->front == -1 || pq->front > pq->rear;
}

// Add an element with priority to the queue


void add(PriorityQueue *pq, int data, int priority) {
if (isFull(pq)) {
printf("Priority Queue is full. Cannot add %d\n", data);
return;
}
if (isEmpty(pq)) {
pq->front = 0; // Set front to 0 if queue was empty
}

// Find the position to insert the new element


int i;
for (i = pq->rear; (i >= pq->front) && (priority < pq->items[i].priority); i--) {
pq->items[i + 1] = pq->items[i]; // Shift elements to make space
}
pq->items[i + 1].data = data; // Insert the new element
pq->items[i + 1].priority = priority;
pq->rear++; // Increment rear
}

// Delete the highest priority element from the queue


Element delete(PriorityQueue *pq) {
if (isEmpty(pq)) {
printf("Priority Queue is empty. Cannot delete.\n");
Element empty = { -1, -1 }; // Return an invalid element
return empty;
}

Element item = pq->items[pq->front]; // Get the highest priority element


pq->front++; // Move front forward

if (pq->front > pq->rear) {


pq->front = pq->rear = -1; // Reset queue if it becomes empty
}

return item;
}

// Display the elements in the priority queue


void displayQueue(PriorityQueue *pq) {
if (isEmpty(pq)) {
printf("Priority Queue is empty.\n");
return;
}
printf("Priority Queue elements (data:priority): ");
for (int i = pq->front; i <= pq->rear; i++) {
printf("%d:%d ", pq->items[i].data, pq->items[i].priority);
}
printf("\n");
}

Slip12
Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use linear
search algorithm to check whether the name is present in the file and output the STD code,
otherwise output “city not in the list”. [10]

-> #include <stdio.h>

#include <stdlib.h>

#include <string.h>
#define MAX_CITIES 100

#define NAME_LENGTH 50

#define CODE_LENGTH 10

typedef struct {

char name[NAME_LENGTH];

char std_code[CODE_LENGTH];

} City;

// Function prototypes

void readCities(const char *filename, City cities[], int *count);


char* searchCity(City cities[], int count, const char *city_name);

int main() {

City cities[MAX_CITIES];

int count = 0;

// Read cities from the file

readCities("cities.txt", cities, &count);

// Accept city name from user

char city_name[NAME_LENGTH];

printf("Enter the name of the city: ");


fgets(city_name, sizeof(city_name), stdin);

city_name[strcspn(city_name, "\n")] = '\0'; // Remove newline character

// Search for the city and get the STD code

char *std_code = searchCity(cities, count, city_name);

// Output the result

if (std_code) {

printf("The STD code for %s is: %s\n", city_name, std_code);

} else {

printf("City not in the list.\n");

}
return 0;

// Function to read cities from a file

void readCities(const char *filename, City cities[], int *count) {

FILE *file = fopen(filename, "r");

if (file == NULL) {

perror("Could not open file for reading");

exit(EXIT_FAILURE);

}
while (fscanf(file, "%49s %9s", cities[*count].name, cities[*count].std_code) != EOF) {

(*count)++;

if (*count >= MAX_CITIES) {

break; // Avoid exceeding array size

fclose(file);

// Function to search for a city in the array

char* searchCity(City cities[], int count, const char *city_name) {


for (int i = 0; i < count; i++) {

if (strcmp(cities[i].name, city_name) == 0) {

return cities[i].std_code; // Return the STD code if found

return NULL; // Return NULL if city not found

Q2. Implement a circular queue library (cir_queue.h) of integers using a dynamic (circular linked list) implementation of the queue and
implementing init(Q), AddQueue(Q) and DeleteQueue(Q) operations. Write a menu driven program that includes queue library and
calls different queue operations. [20]

 #include

<stdio.h>

#include

<stdlib.h>
// Node structure for circular linked list

typedef struct Node {

int data;

struct Node* next;

} Node;

// Circular Queue structure

typedef struct {

Node* front;

Node* rear;

} CircularQueue;
// Function prototypes

void initQueue(CircularQueue* q);

int isEmpty(CircularQueue* q);

void addQueue(CircularQueue* q, int data);

int deleteQueue(CircularQueue* q);

void displayQueue(CircularQueue* q);

void freeQueue(CircularQueue* q);

int main() {

CircularQueue q;

initQueue(&q);
int choice, value;

while (1) {

printf("\nCircular Queue Menu:\n");

printf("1. Add to Queue\n");

printf("2. Delete from Queue\n");

printf("3. Display Queue\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {
case 1:

printf("Enter value to add: ");

scanf("%d", &value);

addQueue(&q, value);

break;

case 2:

if (!isEmpty(&q)) {

int deletedValue = deleteQueue(&q);

printf("Deleted value: %d\n", deletedValue);

} else {

printf("Queue is empty. Cannot delete.\n");

}
break;

case 3:

displayQueue(&q);

break;

case 4:

freeQueue(&q);

exit(0);

default:

printf("Invalid choice. Please try again.\n");

}
return 0;

// Initialize the circular queue

void initQueue(CircularQueue* q) {

q->front = NULL;

q->rear = NULL;

// Check if the queue is empty

int isEmpty(CircularQueue* q) {

return (q->front == NULL);


}

// Add an element to the queue

void addQueue(CircularQueue* q, int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

if (isEmpty(q)) {

q->front = newNode;

q->rear = newNode;

newNode->next = newNode; // Point to itself


} else {

q->rear->next = newNode;

newNode->next = q->front; // Point new node to front

q->rear = newNode; // Update rear to new node

printf("Added %d to the queue.\n", data);

// Delete an element from the queue

int deleteQueue(CircularQueue* q) {

if (isEmpty(q)) {

return -1; // Queue is empty


}

int data = q->front->data;

Node* temp = q->front;

if (q->front == q->rear) {

// Only one element in the queue

q->front = NULL;

q->rear = NULL;

} else {

// More than one element in the queue

q->front = q->front->next;
q->rear->next = q->front; // Update rear to point to new front

free(temp);

return data;

// Display the elements in the queue

void displayQueue(CircularQueue* q) {

if (isEmpty(q)) {

printf("Queue is empty.\n");

return;
}

Node* current = q->front;

printf("Circular Queue elements: ");

do {

printf("%d ", current->data);

current = current->next;

} while (current != q->front);

printf("\n");

// Free the queue


void freeQueue(CircularQueue* q) {

while (!isEmpty(q)) {

deleteQueue(q);

Slip13
Implement a stack library (ststack.h) of integers using a static implementation of the stack and implementing the operations like init(S),
S=push(S) and S=pop(S). Write a driver program that includes stack library
and calls different stack operations. [10]

 #include

<stdio.h>

#include

<stdlib.h>

#define MAX 100


// Stack structure

typedef struct {

int items[MAX];

int top;

} Stack;

// Function prototypes

void initStack(Stack* s);

int isFull(Stack* s);

int isEmpty(Stack* s);

void push(Stack* s, int value);


int pop(Stack* s);

void displayStack(Stack* s);

int main() {

Stack s;

initStack(&s);

int choice, value;

while (1) {

printf("\nStack Menu:\n");

printf("1. Push onto Stack\n");


printf("2. Pop from Stack\n");

printf("3. Display Stack\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to push: ");

scanf("%d", &value);

push(&s, value);

break;
case 2:

if (!isEmpty(&s)) {

int poppedValue = pop(&s);

printf("Popped value: %d\n", poppedValue);

} else {

printf("Stack is empty. Cannot pop.\n");

break;

case 3:

displayStack(&s);

break;

case 4:
exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

// Initialize the stack

void initStack(Stack* s) {

s->top = -1; // Stack is initially empty


}

// Check if the stack is full

int isFull(Stack* s) {

return s->top == MAX - 1;

// Check if the stack is empty

int isEmpty(Stack* s) {

return s->top == -1;

}
// Push an element onto the stack

void push(Stack* s, int value) {

if (isFull(s)) {

printf("Stack is full. Cannot push %d\n", value);

return;

s->items[++(s->top)] = value; // Increment top and add value

printf("Pushed %d onto the stack.\n", value);

// Pop an element from the stack

int pop(Stack* s) {
if (isEmpty(s)) {

printf("Stack is empty. Cannot pop.\n");

return -1; // Return -1 if stack is empty

return s->items[(s->top)--]; // Return value and decrement top

// Display the elements in the stack

void displayStack(Stack* s) {

if (isEmpty(s)) {

printf("Stack is empty.\n");

return;
}

printf("Stack elements: ");

for (int i = 0; i <= s->top; i++) {

printf("%d ", s->items[i]);

printf("\n");

Q2. Write a program that sorts the elements of linked list using bubble sort
technique. [20]

 #include

<stdio.h>

#include

<stdlib.h>
// Node structure for linked list

typedef struct Node {

int data;

struct Node* next;

} Node;

// Function prototypes

Node* createNode(int data);

void insertEnd(Node** head, int data);

void bubbleSort(Node** head);

void displayList(Node* head);

void freeList(Node* head);


int main() {

Node* head = NULL;

int n, value;

// Accept number of elements from user

printf("Enter the number of elements in the linked list: ");

scanf("%d", &n);

// Input elements into the linked list

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

printf("Enter element %d: ", i + 1);


scanf("%d", &value);

insertEnd(&head, value);

printf("Original Linked List: ");

displayList(head);

// Sort the linked list using bubble sort

bubbleSort(&head);

printf("Sorted Linked List: ");

displayList(head);
// Free the allocated memory

freeList(head);

return 0;

// Create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

return newNode;
}

// Insert a node at the end of the linked list

void insertEnd(Node** head, int data) {

Node* newNode = createNode(data);

if (*head == NULL) {

*head = newNode;

return;

Node* current = *head;

while (current->next != NULL) {


current = current->next;

current->next = newNode;

// Bubble sort for linked list

void bubbleSort(Node** head)

if (*head == NULL) return;

int swapped;

Node* ptr1;

Node* lptr = NULL;


do {

swapped = 0;

ptr1 = *head;

while (ptr1->next != lptr) {

if (ptr1->data > ptr1->next->data) {

// Swap data

int temp = ptr1->data;

ptr1->data = ptr1->next->data;

ptr1->next->data = temp;

swapped = 1;
}

ptr1 = ptr1->next;

lptr = ptr1;

} while (swapped);

// Display the linked list

void displayList(Node* head) {

Node* current = head;

while (current != NULL) {

printf("%d ", current->data);


current = current->next;

printf("\n");

// Free the linked list

void freeList(Node* head) {

Node* current = head;

Node* next;

while (current != NULL) {

next = current->next;
free(current);

current = next;

}
Slip14

Q1. Create a random array of n integers. Accept a value x from user and use linear search algorithm to check whether the number is
present in the array or not and output the position if the number is present. [10]

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Function prototypes

void generateRandomArray(int arr[], int n);

int linearSearch(int arr[], int n, int x);

int main() {

int n, x;

// Seed the random number generator

srand(time(0));
// Accept the size of the array from the user

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Create an array of size n

int arr[n];

// Generate a random array

generateRandomArray(arr, n);

// Display the generated array

printf("Generated Array: ");

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

printf("%d ", arr[i]);

}
printf("\n");

// Accept the value to search from the user

printf("Enter a value to search: ");

scanf("%d", &x);

// Perform linear search

int position = linearSearch(arr, n, x);

// Output the result

if (position != -1) {

printf("Value %d found at position: %d\n", x, position);

} else {

printf("Value %d not found in the array.\n", x);

}
return 0;

// Function to generate a random array of integers

void generateRandomArray(int arr[], int n) {

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

arr[i] = rand() % 100; // Random number between 0 and 99

// Function to perform linear search

int linearSearch(int arr[], int n, int x) {

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

if (arr[i] == x) {
return i; // Return the index if found

return -1; // Return -1 if not found

Q2. A doubly ended queue allows additions and deletions from both the ends that is front and rear. Initially additions from the front
will not be possible. To avoid this situation, the array can be treated as if it were circular. Implement a queue library
(dstqueue.h) of integers using a static implementation of the circular queue and implementing the following
operations. [20] a. isFull(Q)

b. addFront(Q)

c. getRear(Q)

d. deleteRear(Q)

-> #include <stdio.h>

#include <stdlib.h>

#define MAX 100


typedef struct {

int items[MAX];

int front;

int rear;

} Deque;

// Function prototypes

void initDeque(Deque* dq);

int isFull(Deque* dq);

void addRear(Deque* dq, int value);

int getRear(Deque* dq);

void deleteRear(Deque* dq);

void displayDeque(Deque* dq);

int main() {
Deque dq;

initDeque(&dq);

int choice, value;

while (1) {

printf("\nDeque Menu:\n");

printf("1. Add to Rear\n");

printf("2. Get Rear\n");

printf("3. Delete Rear\n");

printf("4. Display Deque\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);
switch (choice) {

case 1:

if (isFull(&dq)) {

printf("Deque is full. Cannot add to rear.\n");

} else {

printf("Enter value to add to rear: ");

scanf("%d", &value);

addRear(&dq, value);

break;

case 2:

if (dq.rear == dq.front) {

printf("Deque is empty. Cannot get rear.\n");

} else {

printf("Rear element: %d\n", getRear(&dq));


}

break;

case 3:

if (dq.rear == dq.front) {

printf("Deque is empty. Cannot delete rear.\n");

} else {

deleteRear(&dq);

printf("Deleted rear element.\n");

break;

case 4:

displayDeque(&dq);

break;

case 5:

exit(0);
default:

printf("Invalid choice. Please try again.\n");

return 0;

// Initialize the deque

void initDeque(Deque* dq) {

dq->front = 0;

dq->rear = 0;

// Check if the deque is full


int isFull(Deque* dq) {

return (dq->rear + 1) % MAX == dq->front;

// Add an element to the rear of the deque

void addRear(Deque* dq, int value) {

dq->items[dq->rear] = value;

dq->rear = (dq->rear + 1) % MAX; // Move rear forward

printf("Added %d to the rear.\n", value);

// Get the rear element of the deque

int getRear(Deque* dq) {

return dq->items[(dq->rear - 1 + MAX) % MAX]; // Adjust for circular index

}
// Delete an element from the rear of the deque

void deleteRear(Deque* dq) {

dq->rear = (dq->rear - 1 + MAX) % MAX; // Move rear back

// Display the elements in the deque

void displayDeque(Deque* dq) {

if (dq->rear == dq->front) {

printf("Deque is empty.\n");

return;

printf("Deque elements: ");

int i = dq->front;

while (i != dq->rear) {
printf("%d ", dq->items[i]);

i = (i + 1) % MAX;

printf("\n");

Slip15

Q1. Sort a random array of n integers (accept the value of n from user) in ascending order by using selection sort algorithm.
[10]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<time.h>

// Function prototypes

void generateRandomArray(int arr[], int n);

void selectionSort(int arr[], int n);

void displayArray(int arr[], int n);


int main() {

int n;

// Seed the random number generator

srand(time(0));

// Accept the size of the array from the user

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Create an array of size n

int arr[n];

// Generate a random array


generateRandomArray(arr, n);

printf("Generated Array: ");

displayArray(arr, n);

// Sort the array using selection sort

selectionSort(arr, n);

printf("Sorted Array: ");

displayArray(arr, n);

return 0;

// Function to generate a random array of integers


void generateRandomArray(int arr[], int n) {

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

arr[i] = rand() % 100; // Random number between 0 and 99

// Function to perform selection sort

void selectionSort(int arr[], int n) {

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

int minIndex = i;

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

if (arr[j] < arr[minIndex])

minIndex = j;

}
// Swap the found minimum element with the first element

if (minIndex != i) {

int temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

// Function to display the elements of the array

void displayArray(int arr[], int n) {

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

printf("%d ", arr[i]);

printf("\n");
}

Q2. Implement a linear queue library (dyqueue.h) of integers using a dynamic


(circular linked list) implementation of the queue and implementing the
queue operations as (init(Q), AddQueue(Q, x), X=peek(Q)) [20]

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

// Node structure for the circular linked list


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

// Queue structure
typedef struct {
Node* front;
Node* rear;
} Queue;

// Function prototypes
void init(Queue* q);
void addQueue(Queue* q, int x);
int peek(Queue* q);
void freeQueue(Queue* q);
// Main function to demonstrate the queue operations
int main() {
Queue q;
init(&q);

int choice, value;

while (1) {
printf("\nQueue Menu:\n");
printf("1. Add to Queue\n");
printf("2. Peek\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to add to queue: ");
scanf("%d", &value);
addQueue(&q, value);
printf("Added %d to the queue.\n", value);
break;
case 2:
if (q.front == NULL) {
printf("Queue is empty.\n");
} else {
printf("Front element: %d\n", peek(&q));
}
break;
case 3:
freeQueue(&q);
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

// Initialize the queue


void init(Queue* q) {
q->front = NULL;
q->rear = NULL;
}

// Add an element to the queue


void addQueue(Queue* q, int x) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;

if (q->rear == NULL) {
// Queue is empty
q->front = newNode;
q->rear = newNode;
newNode->next = newNode; // Point to itself
} else {
// Add new node to the end and update rear
q->rear->next = newNode;
q->rear = newNode;
q->rear->next = q->front; // Make it circular
}
}

// Peek at the front element of the queue


int peek(Queue* q) {
return q->front->data;
}

// Free the queue


void freeQueue(Queue* q) {
if (q->front == NULL) return;

Node* current = q->front;


Node* nextNode;
do {
nextNode = current->next;
free(current);
current = nextNode;
} while (current != q->front);
q->front =
NULL; q->rear =
NULL;
}

Slip 16
Q1) Sort a random array of n integers (accept the value of n from user) in ascending order by using Counting sort algorithm.
[10]

-> #include

<stdio.h> #include

<stdlib.h>

#include <time.h>

// Function prototypes

void generateRandomArray(int arr[], int n);

void countingSort(int arr[], int n);

void displayArray(int arr[], int n);

int main() {
int n;

// Seed the random number generator

srand(time(0));

// Accept the size of the array from the user

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Create an array of size n

int arr[n];

// Generate a random array

generateRandomArray(arr, n);
printf("Generated Array: ");

displayArray(arr, n);

// Sort the array using counting sort

countingSort(arr, n);

printf("Sorted Array: ");

displayArray(arr, n);

return 0;

// Function to generate a random array of integers

void generateRandomArray(int arr[], int n) {

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


arr[i] = rand() % 100; // Random number between 0 and 99

// Function to perform counting sort

void countingSort(int arr[], int n) {

int output[n]; // Output array

int count[100] = {0}; // Count array for numbers in range [0, 99]

// Store the count of each number

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

count[arr[i]]++;

// Update the output array


for (int i = 0, j = 0; i < 100; i++) {

while (count[i] > 0) {

output[j++] = i;

count[i]--;

// Copy the sorted elements into the original array

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

arr[i] = output[i];

// Function to display the elements of the array

void displayArray(int arr[], int n) {


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

printf("%d ", arr[i]);

printf("\n");

Q2. A postfix expression of the form ab+cd-*ab/ is to be evaluated after accepting the values of a, b, c and d. The value should be
accepted only once and the same value is to be used for repeated occurrence of same symbol in the expression. Formulate the
problem and write a C program to solve the problem
by using stack [20]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<ctype.h>

#define MAX 100

// Stack structure
typedef struct {

int top;

float items[MAX];

} Stack;

// Function prototypes

void initStack(Stack* s);

int isFull(Stack* s);

int isEmpty(Stack* s);

void push(Stack* s, float value);

float pop(Stack* s);

float evaluatePostfix(const char* expression, float a, float b, float c, float d);

int main() {

char expression[] = "ab+cd-*ab/";


float a, b, c, d;

// Accept values for a, b, c, d

printf("Enter the value for a: ");

scanf("%f", &a);

printf("Enter the value for b: ");

scanf("%f", &b);

printf("Enter the value for c: ");

scanf("%f", &c);

printf("Enter the value for d: ");

scanf("%f", &d);

// Evaluate the postfix expression

float result = evaluatePostfix(expression, a, b, c, d);

printf("The result of the postfix expression '%s' is: %.2f\n", expression, result);
return 0;

// Function to initialize the stack

void initStack(Stack* s) {

s->top = -1;

// Function to check if the stack is full

int isFull(Stack* s) {

return s->top == MAX - 1;

// Function to check if the stack is empty


int isEmpty(Stack* s) {

return s->top == -1;

// Function to push a value onto the stack

void push(Stack* s, float value) {

if (!isFull(s)) {

s->items[++(s->top)] = value;

} else {

printf("Stack is full!\n");

// Function to pop a value from the stack

float pop(Stack* s) {
if (!isEmpty(s)) {

return s->items[(s->top)--];

} else {

printf("Stack is empty!\n");

return 0; // Error value

// Function to evaluate a postfix expression

float evaluatePostfix(const char* expression, float a, float b, float c, float d) {

Stack stack;

initStack(&stack);

for (const char* p = expression; *p; p++) {

if (isdigit(*p) || isalpha(*p)) {
// Push the corresponding value onto the stack

float value;

switch (*p) {

case 'a': value = a; break;

case 'b': value = b; break;

case 'c': value = c; break;

case 'd': value = d; break;

default: value = 0; // Unrecognized variable

push(&stack, value);

} else {

// Operator: pop two values and apply the operator

float operand2 = pop(&stack);

float operand1 = pop(&stack);

switch (*p) {
case '+': push(&stack, operand1 + operand2); break;

case '-': push(&stack, operand1 - operand2); break;

case '*': push(&stack, operand1 * operand2); break;

case '/':

if (operand2 != 0) {

push(&stack, operand1 / operand2);

} else {

printf("Error: Division by zero.\n");

return 0; // Error value

break;

default:

printf("Error: Unknown operator '%c'.\n", *p);

return 0; // Error value

}
}

return pop(&stack); // Final result

Slip17
Q1 Implement a list library (singlylist.h) for a singly linked list. Create a linked list, reverse it and display reversed linked list. [10]

-> #include <stdio.h>

#include <stdlib.h>

// Node structure for the singly linked list

typedef struct Node {

int data;

struct Node* next;

} Node;
// Function prototypes

Node* createNode(int data);

void insertEnd(Node** head, int data);

void reverseList(Node** head);

void displayList(Node* head);

void freeList(Node* head);

int main() {

Node* head = NULL;

int n, data;

// Accept the number of elements from the user

printf("Enter the number of elements in the list: ");

scanf("%d", &n);
// Create the linked list

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

printf("Enter element %d: ", i + 1);

scanf("%d", &data);

insertEnd(&head, data);

printf("Original List: ");

displayList(head);

// Reverse the linked list

reverseList(&head);

printf("Reversed List: ");


displayList(head);

// Free the allocated memory

freeList(head);

return 0;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

return newNode;

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

void insertEnd(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 reverse the linked list

void reverseList(Node** head) {

Node* prev = NULL;

Node* current = *head;

Node* next = NULL;

while (current != NULL) {

next = current->next; // Store next node

current->next = prev; // Reverse current node's pointer

prev = current; // Move pointers one position ahead

current = next;

*head = prev; // Update head to the new front of the list

}
// Function to display the linked list

void displayList(Node* head) {

Node* temp = head;

while (temp != NULL) {

printf("%d -> ", temp->data);

temp = temp->next;

printf("NULL\n");

// Function to free the linked list

void freeList(Node* head) {

Node* temp;

while (head != NULL) {

temp = head;
head = head->next;

free(temp);

Q2 Write a program that copies the contents of one stack into another. Use stack library to perform basic stack operations. The order
of two stacks must be identical.(Hint: Use a temporary stack to preserve the order). [20]

 #include

<stdio.h>

#include

<stdlib.h>

#define MAX 100

// Stack structure

typedef struct {

int top;

int items[MAX];
} Stack;

// Function prototypes

void initStack(Stack* s);

int isFull(Stack* s);

int isEmpty(Stack* s);

void push(Stack* s, int value);

int pop(Stack* s);

int peek(Stack* s);

void copyStack(Stack* source, Stack* destination);

int main() {

Stack source, destination;

// Initialize the stacks


initStack(&source);

initStack(&destination);

// Push some values onto the source stack

push(&source, 10);

push(&source, 20);

push(&source, 30);

push(&source, 40);

push(&source, 50);

// Copy the contents of the source stack to the destination stack

copyStack(&source, &destination);

// Display the contents of the destination stack

printf("Contents of the destination stack (copied from source):\n");


while (!isEmpty(&destination)) {

printf("%d\n", pop(&destination));

return 0;

// Function to initialize the stack

void initStack(Stack* s) {

s->top = -1;

// Function to check if the stack is full

int isFull(Stack* s) {

return s->top == MAX - 1;


}

// Function to check if the stack is empty

int isEmpty(Stack* s) {

return s->top == -1;

// Function to push a value onto the stack

void push(Stack* s, int value) {

if (!isFull(s)) {

s->items[++(s->top)] = value;

} else {

printf("Stack is full!\n");

}
// Function to pop a value from the stack

int pop(Stack* s) {

if (!isEmpty(s)) {

return s->items[(s->top)--];

} else {

printf("Stack is empty!\n");

return -1; // Error value

// Function to peek at the top value of the stack

int peek(Stack* s) {

if (!isEmpty(s)) {

return s->items[s->top];
} else {

printf("Stack is empty!\n");

return -1; // Error value

// Function to copy the contents of one stack to another

void copyStack(Stack* source, Stack* destination) {

Stack temp;

initStack(&temp);

// Move elements from source to temp

while (!isEmpty(source)) {

push(&temp, pop(source));

}
// Move elements from temp to destination and back to source

while (!isEmpty(&temp)) {

int value = pop(&temp);

push(destination, value);

push(source, value); // Restore the original stack

Slip18
Sort a random array of n integers (accept the value of n from user) in ascending order by using Selection sort algorithm [10]

-> #include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Function prototypes
void selectionSort(int arr[], int n);

void printArray(int arr[], int n);

int main() {

int n;

// Seed the random number generator

srand(time(0));

// Accept the size of the array from the user

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Create an array of size n


int arr[n];

// Generate random integers and fill the array

printf("Random array elements:\n");

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

arr[i] = rand() % 100; // Random integers between 0 and 99

printf("%d ", arr[i]);

printf("\n");

// Sort the array using selection sort

selectionSort(arr, n);

// Print the sorted array


printf("Sorted array elements:\n");

printArray(arr, n);

return 0;

// Function to perform selection sort

void selectionSort(int arr[], int n) {

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

int minIndex = i;

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

if (arr[j] < arr[minIndex])

minIndex = j;

}
}

// Swap the found minimum element with the first element

if (minIndex != i) {

int temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

// Function to print the array

void printArray(int arr[], int n) {

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

printf("%d ", arr[i]);


}

printf("\n");

Q2. Write a program that multiply two single variable polynomials. Each polynomial should be represented as a list with linked list
implementation

 #include

<stdio.h>

#include

<stdlib.h>

// Node structure for the polynomial linked list

typedef struct Node {

int coeff; // Coefficient

int exp; // Exponent

struct Node* next;

} Node;
// Function prototypes

Node* createNode(int coeff, int exp);

void insertEnd(Node** head, int coeff, int exp);

Node* multiplyPolynomials(Node* poly1, Node* poly2);

void displayPolynomial(Node* head);

void freePolynomial(Node* head);

int main() {

Node* poly1 = NULL;

Node* poly2 = NULL;

// Input first polynomial

printf("Enter the first polynomial (coeff exp), end with -1 -1:\n");

while (1) {
int coeff, exp;

scanf("%d %d", &coeff, &exp);

if (coeff == -1 && exp == -1) break;

insertEnd(&poly1, coeff, exp);

// Input second polynomial

printf("Enter the second polynomial (coeff exp), end with -1 -1:\n");

while (1) {

int coeff, exp;

scanf("%d %d", &coeff, &exp);

if (coeff == -1 && exp == -1) break;

insertEnd(&poly2, coeff, exp);

}
// Multiply the polynomials

Node* result = multiplyPolynomials(poly1, poly2);

// Display the result

printf("Resultant polynomial after multiplication:\n");

displayPolynomial(result);

// Free the allocated memory

freePolynomial(poly1);

freePolynomial(poly2);

freePolynomial(result);

return 0;
}

// Function to create a new polynomial node

Node* createNode(int coeff, int exp) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->coeff = coeff;

newNode->exp = exp;

newNode->next = NULL;

return newNode;

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

void insertEnd(Node** head, int coeff, int exp) {

Node* newNode = createNode(coeff, exp);


if (*head == NULL) {

*head = newNode;

} else {

Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

// Function to multiply two polynomials

Node* multiplyPolynomials(Node* poly1, Node* poly2) {

Node* result = NULL;


for (Node* p1 = poly1; p1 != NULL; p1 = p1->next) {

for (Node* p2 = poly2; p2 != NULL; p2 = p2->next) {

int coeff = p1->coeff * p2->coeff;

int exp = p1->exp + p2->exp;

insertEnd(&result, coeff, exp);

// Combine like terms

Node* combined = NULL;

while (result != NULL) {

int coeff = result->coeff;

int exp = result->exp;


Node* nextResult = result->next;

free(result);

// Combine terms with the same exponent

while (nextResult != NULL && nextResult->exp == exp) {

coeff += nextResult->coeff;

Node* temp = nextResult;

nextResult = nextResult->next;

free(temp);

insertEnd(&combined, coeff, exp);

result = nextResult;

}
return combined;

// Function to display the polynomial

void displayPolynomial(Node* head) {

if (head == NULL) {

printf("0\n");

return;

while (head != NULL) {

printf("%dx^%d", head->coeff, head->exp);

head = head->next;
if (head != NULL) {

printf(" + ");

printf("\n");

// Function to free the allocated memory for the polynomial

void freePolynomial(Node* head) {

while (head != NULL) {

Node* temp = head;

head = head->next;

free(temp);

}
Slip19
Sort a random array of n integers (accept the value of n from user) in ascending order by using selection sort algorithm [10]

-> #include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Function prototypes

void selectionSort(int arr[], int n);

void printArray(int arr[], int n);

int main() {

int n;
// Seed the random number generator

srand(time(0));

// Accept the size of the array from the user

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

// Create an array of size n

int arr[n];

// Generate random integers and fill the array

printf("Random array elements:\n");


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

arr[i] = rand() % 100; // Random integers between 0 and 99

printf("%d ", arr[i]);

printf("\n");

// Sort the array using selection sort

selectionSort(arr, n);

// Print the sorted array

printf("Sorted array elements:\n");

printArray(arr, n);
return 0;

// Function to perform selection sort

void selectionSort(int arr[], int n) {

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

int minIndex = i;

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

if (arr[j] < arr[minIndex])

minIndex = j;

}
}

// Swap the found minimum element with the first element

if (minIndex != i) {

int temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

// Function to print the array

void printArray(int arr[], int n) {


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

printf("%d ", arr[i]);

printf("\n");

Q2. There are lists where insertion should ensure the ordering of data elements. Since the elements are in ascending order the search
can terminate once equal or greater element is found. Implement a doubly linked list of ordered integers
(ascending/descending) with insert, search and display operations.
[20]

 #include

<stdio.h>

#include

<stdlib.h>

// Node structure for the doubly linked list

typedef struct Node {


int data;

struct Node* next;

struct Node* prev;

} Node;

// Function prototypes

Node* createNode(int data);

void insert(Node** head, int data);

Node* search(Node* head, int data);

void display(Node* head);

void freeList(Node* head);


int main() {

Node* head = NULL;

int choice, value;

while (1) { printf("\nMenu:\

n"); printf("1. Insert\n");

printf("2. Search\n");

printf("3. Display\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);
switch (choice) {

case 1:

printf("Enter the integer to insert: ");

scanf("%d", &value);

insert(&head, value);

break;

case 2:

printf("Enter the integer to search for: ");

scanf("%d", &value);

Node* result = search(head, value);

if (result != NULL) {
printf("Element %d found in the list.\n", result->data);

} else {

printf("Element %d not found in the list.\n", value);

break;

case 3:

display(head);

break;

case 4:

freeList(head);

return 0;

default:
printf("Invalid choice! Please try again.\n");

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

newNode->prev = NULL;

return newNode;
}

// Function to insert a node in ascending order

void insert(Node** head, int data) {

Node* newNode = createNode(data);

if (*head == NULL) {

*head = newNode;

} else {

Node* current = *head;

// Traverse to find the correct position

while (current != NULL && current->data < data) {

current = current->next;
}

// If the new node is to be inserted at the beginning

if (current == *head) {

newNode->next = *head;

(*head)->prev = newNode;

*head = newNode;

} else {

// Insert in the middle or end

newNode->prev = current ? current->prev : NULL;

if (newNode->prev) {

newNode->prev->next = newNode;

}
if (current) {

newNode->next = current;

current->prev = newNode;

// Function to search for a node in the list

Node* search(Node* head, int data) {

Node* current = head;

while (current != NULL) {


if (current->data == data) {

return current; // Element found

if (current->data > data) {

return NULL; // Element not found, since list is ordered

current = current->next;

return NULL; // Reached end of the list

// Function to display the list


void display(Node* head) {

if (head == NULL) {

printf("The list is empty.\n");

return;

Node* current = head;

printf("Doubly linked list: ");

while (current != NULL) {

printf("%d ", current->data);

current = current->next;

printf("\n");
}

// Function to free the allocated memory for the list

void freeList(Node* head) {

while (head != NULL) {

Node* temp = head;

head = head->next;

free(temp);

}
Slip20

Q1) Implement a stack library (ststack.h) of integers using a static implementation of the stack and implementing the operations like
init(S), S=push(S), isFull(S). Write a driver program that includes stack library and
calls different stack operations. [10]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<stdbool.h>

#define MAX 100 // Maximum size of the stack

// Stack structure

typedef struct {

int items[MAX];

int top;
} Stack;

// Function prototypes

void init(Stack* s);

bool isFull(Stack* s);

bool isEmpty(Stack* s);

void push(Stack* s, int value);

int pop(Stack* s);

int peek(Stack* s);

void display(Stack* s);

// Main function
int main() {

Stack s;

init(&s);

int choice, value;

while (1) { printf("\

nMenu:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Display\n");

printf("5. Check if full\n");


printf("6. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter an integer to push: ");

scanf("%d", &value);

if (isFull(&s)) {

printf("Stack is full! Cannot push %d\n", value);

} else {

push(&s, value);
printf("%d pushed to stack\n", value);

break;

case 2:

if (isEmpty(&s)) {

printf("Stack is empty! Cannot pop.\n");

} else {

value = pop(&s);

printf("%d popped from stack\n", value);

break;

case 3:
if (isEmpty(&s)) {

printf("Stack is empty! No top element.\n");

} else {

value = peek(&s);

printf("Top element is %d\n", value);

break;

case 4:

display(&s);

break;

case 5:

if (isFull(&s)) {
printf("Stack is full.\n");

} else {

printf("Stack is not full.\n");

break;

case 6:

printf("Exiting...\n");

exit(0);

default:

printf("Invalid choice! Please try again.\n");

}
return 0;

// Function to initialize the stack

void init(Stack* s) {

s->top = -1; // Stack is initially empty

// Function to check if the stack is full

bool isFull(Stack* s) {

return s->top == MAX - 1;


}

// Function to check if the stack is empty

bool isEmpty(Stack* s) {

return s->top == -1;

// Function to push an element onto the stack

void push(Stack* s, int value) {

if (!isFull(s)) {

s->items[++s->top] = value; // Increment top and add value

}
}

// Function to pop an element from the stack

int pop(Stack* s) {

if (!isEmpty(s)) {

return s->items[s->top--]; // Return value and decrement top

return -1; // Return -1 if the stack is empty (error case)

// Function to get the top element of the stack

int peek(Stack* s) {
if (!isEmpty(s)) {

return s->items[s->top]; // Return top value

return -1; // Return -1 if the stack is empty (error case)

// Function to display the stack

void display(Stack* s) {

if (isEmpty(s)) {

printf("Stack is empty.\n");

return;

}
printf("Stack elements: ");

for (int i = s->top; i >= 0; i--) {

printf("%d ", s->items[i]);

printf("\n");

Q2. There are lists where new elements are always appended at the end of the list. The list can be implemented as a circular list with
the external pointer pointing to the last element of the list. Implement singly linked circular list of integers with append and display
operations. The operation append(L, n),
appends to the end of the list, n integers either accepted from user or randomly
generated. [20]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<time.h>
// Node structure for the circular linked list

typedef struct Node {

int data;

struct Node* next;

} Node;

// Function prototypes

Node* createNode(int data);

void append(Node** last, int data);

void display(Node* last);

void freeList(Node* last);


int main() {

Node* last = NULL; // Initialize the last node of the circular list

int n, choice;

printf("Enter the number of elements to append: ");

scanf("%d", &n);

printf("Choose input method:\n");

printf("1. Randomly generate numbers\n");

printf("2. Accept numbers from user\n");

printf("Enter your choice: ");


scanf("%d", &choice);

if (choice == 1) {

// Seed for random number generation

srand(time(NULL));

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

int randomValue = rand() % 100; // Generate random numbers from 0 to 99

append(&last, randomValue);

printf("Appended: %d\n", randomValue);

} else if (choice == 2) {

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


int userValue;

printf("Enter integer %d: ", i + 1);

scanf("%d", &userValue);

append(&last, userValue);

} else {

printf("Invalid choice! Exiting...\n");

return 1;

// Display the circular list

printf("Elements in the circular linked list:\n");


display(last);

// Free the allocated memory

freeList(last);

return 0;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;
newNode->next = NULL;

return newNode;

// Function to append a node at the end of the circular linked list

void append(Node** last, int data) {

Node* newNode = createNode(data);

if (*last == NULL) {

// If the list is empty

*last = newNode;

newNode->next = newNode; // Point to itself

} else {
// If the list is not empty

newNode->next = (*last)->next; // New node points to the first node

(*last)->next = newNode; // Last node points to the new node

*last = newNode; // Update last to the new node

// Function to display the circular linked list

void display(Node* last) {

if (last == NULL) {

printf("The list is empty.\n");

return;
}

Node* current = last->next; // Start from the first node

do {

printf("%d ", current->data);

current = current->next; // Move to the next node

} while (current != last->next); // Stop when we loop back to the first node

printf("\n");

// Function to free the allocated memory for the circular linked list

void freeList(Node* last) {


if (last == NULL) return; // If the list is empty

Node* current = last->next; // Start from the first node

Node* nextNode;

do {

nextNode = current->next; // Store next node

free(current); // Free current node

current = nextNode; // Move to the next node

} while (current != last->next); // Stop when we loop back to the first node

Slip21
Q1. Write a program that reverses a string of characters. The function should use a stack library (cststack.h). Use a static
implementation of the stack. [10]
 #include

<stdio.h>

#include

<string.h>

#include

<stdlib.h>

#include

<stdbool.h>

#define MAX 100 // Maximum size of the stack

// Stack structure

typedef struct {

char items[MAX];

int top;

} Stack;
// Function prototypes

void init(Stack* s);

bool isFull(Stack* s);

bool isEmpty(Stack* s);

void push(Stack* s, char value);

char pop(Stack* s);

void reverseString(char* str);

int main() {

char str[MAX];
printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Remove the newline character from fgets input

str[strcspn(str, "\n")] = '\0';

reverseString(str);

printf("Reversed string: %s\n", str);

return 0;

}
// Function to initialize the stack

void init(Stack* s) {

s->top = -1; // Stack is initially empty

// Function to check if the stack is full

bool isFull(Stack* s) {

return s->top == MAX - 1;

// Function to check if the stack is empty

bool isEmpty(Stack* s) {
return s->top == -1;

// Function to push a character onto the stack

void push(Stack* s, char value) {

if (!isFull(s)) {

s->items[++s->top] = value; // Increment top and add value

// Function to pop a character from the stack

char pop(Stack* s) {
if (!isEmpty(s)) {

return s->items[s->top--]; // Return value and decrement top

return '\0'; // Return null character if the stack is empty

// Function to reverse a string using a stack

void reverseString(char* str) {

Stack s;

init(&s);

// Push all characters of the string onto the stack


for (int i = 0; i < strlen(str); i++) {

push(&s, str[i]);

// Pop all characters from the stack and put them back into the string

for (int i = 0; i < strlen(str); i++) {

str[i] = pop(&s);

Q2. Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using insertion sort or selection sort
[20]

#include <stdio.h>

#include <stdlib.h>
#include <string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

// Structure to hold employee data

typedef struct {

char name[NAME_LENGTH];

int age;

} Employee;

// Function prototypes
void readEmployees(const char* filename, Employee employees[], int* count);

void insertionSort(Employee employees[], int count);

void printEmployees(const Employee employees[], int count);

int main() {

Employee employees[MAX_EMPLOYEES];

int count = 0;

// Read employee data from file

readEmployees("employee.txt", employees, &count);

// Sort employees by name using insertion sort


insertionSort(employees, count);

// Print sorted employee names

printf("Sorted Employee Names:\n");

printEmployees(employees, count);

return 0;

// Function to read employee data from a file

void readEmployees(const char* filename, Employee employees[], int* count) {

FILE* file = fopen(filename, "r");


if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);

while (fscanf(file, "%49s %d", employees[*count].name, &employees[*count].age) == 2) {

(*count)++;

if (*count >= MAX_EMPLOYEES) {

break; // Prevent overflow

}
fclose(file);

// Function to sort employees by name using insertion sort

void insertionSort(Employee employees[], int count) {

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

Employee key = employees[i];

int j = i - 1;

// Move elements of employees[0..i-1], that are greater than key.name,

// to one position ahead of their current position

while (j >= 0 && strcmp(employees[j].name, key.name) > 0) {


employees[j + 1] = employees[j];

j--;

employees[j + 1] = key;

// Function to print employee names

void printEmployees(const Employee employees[], int count) {

for (int i = 0; i < count; i++) {

printf("%s\n", employees[i].name);

}
Slip 22

Q1. Implement a linear queue library (st_queue.h) of integers using a static implementation of the queue and implementing the
operations like init (Q), AddQueue(Q, x) and X=DeleteQueue(Q). Write a program that includes queue library and calls different queue
operations. [10]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<stdbool.h>

#define MAX 100 // Maximum size of the queue

// Queue structure

typedef struct {
int items[MAX];

int front;

int rear;

} Queue;

// Function prototypes

void init(Queue* q);

bool isFull(Queue* q);

bool isEmpty(Queue* q);

void AddQueue(Queue* q, int x);


int DeleteQueue(Queue* q);

void displayQueue(Queue* q);

int main() {

Queue q;

init(&q);

int choice, value;

while (1) {
printf("\nQueue Operations Menu:\n");

printf("1. Add to Queue\n");

printf("2. Delete from Queue\n");

printf("3. Display Queue\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:
printf("Enter an integer to add to the queue: ");

scanf("%d", &value);

AddQueue(&q, value);

break;

case 2:

value = DeleteQueue(&q);

if (value != -1) {

printf("Deleted value: %d\n", value);

break;
case 3:

displayQueue(&q);

break;

case 4:

exit(0);

default:

printf("Invalid choice! Please try again.\n");

}
return 0;

// Function to initialize the queue

void init(Queue* q) {

q->front = -1; // No elements in the queue

q->rear = -1;

// Function to check if the queue is full


bool isFull(Queue* q) {

return (q->rear + 1) % MAX == q->front; // Circular condition

// Function to check if the queue is empty

bool isEmpty(Queue* q) {

return q->front == -1; // No elements in the queue

// Function to add an element to the queue


void AddQueue(Queue* q, int x) {

if (isFull(q)) {

printf("Queue is full! Cannot add %d\n", x);

return;

if (isEmpty(q)) {

q->front = 0; // First element added

q->rear = (q->rear + 1) % MAX; // Circular increment


q->items[q->rear] = x; // Add item to the queue

// Function to delete an element from the queue

int DeleteQueue(Queue* q) {

if (isEmpty(q)) {

printf("Queue is empty! Cannot delete.\n");

return -1; // Indicate failure

}
int deletedValue = q->items[q->front]; // Get front item

if (q->front == q->rear) {

// Queue has only one element

q->front = -1; // Reset the queue

q->rear = -1;

} else {

q->front = (q->front + 1) % MAX; // Circular increment

return deletedValue; // Return deleted value


}

// Function to display the queue

void displayQueue(Queue* q) {

if (isEmpty(q)) {

printf("Queue is empty.\n");

return;

printf("Queue elements: ");


int i = q->front;

while (1) {

printf("%d ", q->items[i]);

if (i == q->rear) break; // Exit condition

i = (i + 1) % MAX; // Circular increment

printf("\n");

Q2. Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use
sentinel linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not
in the list”. [20]
 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_CITIES 100

#define NAME_LENGTH 50

// Structure to hold city data

typedef struct {

char name[NAME_LENGTH];

int std_code;
} City;

// Function prototypes

void readCities(const char* filename, City cities[], int* count);

int sentinelLinearSearch(City cities[], int count, const char* cityName);

int main() {

City cities[MAX_CITIES];

int count = 0;

char cityName[NAME_LENGTH];
// Read city data from file

readCities("cities.txt", cities, &count);

// Accept city name from user

printf("Enter the name of the city: ");

scanf("%49s", cityName);

// Perform sentinel linear search

int std_code = sentinelLinearSearch(cities, count, cityName);

// Output result
if (std_code != -1) {

printf("The STD code for %s is: %d\n", cityName, std_code);

} else {

printf("City not in the list.\n");

return 0;

// Function to read city data from a file

void readCities(const char* filename, City cities[], int* count) {


FILE* file = fopen(filename, "r");

if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);

while (fscanf(file, "%49s %d", cities[*count].name, &cities[*count].std_code) == 2) { (*count)

++;

if (*count >= MAX_CITIES) {

break; // Prevent overflow

}
}

fclose(file);

// Function to perform sentinel linear search

int sentinelLinearSearch(City cities[], int count, const char* cityName) {

if (count == 0) return -1; // Empty list

// Place the last element in the sentinel position

City lastCity = cities[count - 1];


strcpy(cities[count - 1].name, cityName); // Copy search city to the last position

int i = 0;

while (strcmp(cities[i].name, cityName) != 0) {

i++;

// Restore the last city

cities[count - 1] = lastCity;

if (i < count - 1 || strcmp(lastCity.name, cityName) == 0) {


return cities[i].std_code; // Found the city, return STD code

} else {

return -1; // City not found

Slip23
Implement a priority queue library (PriorityQ.h) of integers using a static implementation of the queue and implementing the below
operation [10]

Add an element with its priority into the queue - >

-> #include <stdio.h>

#include <stdlib.h>
#define MAX_SIZE 100

typedef struct {

int data[MAX_SIZE];

int priority[MAX_SIZE];

int size;

} PriorityQueue;
// Function prototypes

void init(PriorityQueue* pq);

int isFull(PriorityQueue* pq);

int isEmpty(PriorityQueue* pq);

void addWithPriority(PriorityQueue* pq, int value, int priority);

int removeHighestPriority(PriorityQueue* pq);

void displayQueue(PriorityQueue* pq);

int main() {
PriorityQueue pq;

init(&pq);

int choice, value, priority;

while (1) {

printf("\nPriority Queue Operations Menu:\n");

printf("1. Add an element with priority\n");

printf("2. Remove highest priority element\n");


printf("3. Display queue\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value: ");

scanf("%d", &value);
printf("Enter priority (higher number means higher priority): ");

scanf("%d", &priority);

addWithPriority(&pq, value, priority);

break;

case 2:

value = removeHighestPriority(&pq);

if (value != -1) {

printf("Removed value: %d\n", value);

}
break;

case 3:

displayQueue(&pq);

break;

case 4:

exit(0);

default:

printf("Invalid choice! Please try again.\n");

}
}

return 0;

// Initialize the priority queue

void init(PriorityQueue* pq) {

pq->size = 0;

}
// Check if the queue is full

int isFull(PriorityQueue* pq) {

return pq->size == MAX_SIZE;

// Check if the queue is empty

int isEmpty(PriorityQueue* pq) {

return pq->size == 0;
}

// Add an element with its priority

void addWithPriority(PriorityQueue* pq, int value, int priority) {

if (isFull(pq)) {

printf("Priority queue is full! Cannot add %d\n", value);

return;

}
int i;

for (i = pq->size - 1; (i >= 0 && pq->priority[i] < priority); i--) {

pq->data[i + 1] = pq->data[i];

pq->priority[i + 1] = pq->priority[i];

pq->data[i + 1] = value;

pq->priority[i + 1] = priority;

pq->size++;
}

// Remove the element with the highest priority

int removeHighestPriority(PriorityQueue* pq) {

if (isEmpty(pq)) {

printf("Priority queue is empty! Cannot remove.\n");

return -1; // Indicate failure

return pq->data[--pq->size]; // Return the highest priority element


}

// Display the contents of the queue

void displayQueue(PriorityQueue* pq) {

if (isEmpty(pq)) {

printf("Priority queue is empty.\n");

return;

}
printf("Priority Queue contents:\n");

for (int i = 0; i < pq->size; i++) {

printf("Value: %d, Priority: %d\n", pq->data[i], pq->priority[i]);

Q2. Read the data from file ‘sortedcities.txt’ containing sorted names of cities and their STD codes. Accept a name of the city from user
and use binary search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not
in the list”. [20]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>
#define MAX_CITIES 100

#define NAME_LENGTH 50

typedef struct {

char name[NAME_LENGTH];

int std_code;

} City;

// Function prototypes

void readCities(const char* filename, City cities[], int* count);


int binarySearch(City cities[], int count, const char* cityName);

int main() {

City cities[MAX_CITIES];

int count = 0;

char cityName[NAME_LENGTH];

// Read city data from file

readCities("sortedcities.txt", cities, &count);

// Accept city name from user


printf("Enter the name of the city: ");

scanf("%49s", cityName);

// Perform binary search

int std_code = binarySearch(cities, count, cityName);

// Output result

if (std_code != -1) {

printf("The STD code for %s is: %d\n", cityName, std_code);

} else {

printf("City not in the list.\n");


}

return 0;

// Function to read city data from a file

void readCities(const char* filename, City cities[], int* count) {

FILE* file = fopen(filename, "r");

if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);
}

while (fscanf(file, "%49s %d", cities[*count].name, &cities[*count].std_code) == 2) {

(*count)++;

if (*count >= MAX_CITIES) {

break; // Prevent overflow

fclose(file);

}
// Function to perform binary search

int binarySearch(City cities[], int count, const char* cityName) {

int left = 0;

int right = count - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

int cmp = strcmp(cities[mid].name, cityName);

if (cmp == 0) {
return cities[mid].std_code; // Found the city

} else if (cmp < 0) {

left = mid + 1; // Search in the right half

} else {

right = mid - 1; // Search in the left half

return -1; // City not found

}
Slip 24

Q1) Implement a circular queue library (cir_queue.h) of integers using a static (linked list) implementation of the queue and
implementing the operations like init (Q), AddQueue(Q, x) and X=peek (Q)). Write a menu driven program that includes queue library
and calls different queue operations.

 #include

<stdio.h>

#include

<stdlib.h>

typedef struct Node {

int data;

struct Node* next;

} Node;
typedef struct CircularQueue {

Node* front;

Node* rear;

} CircularQueue;

// Function prototypes

void init(CircularQueue* q);

int isEmpty(CircularQueue* q);


void addQueue(CircularQueue* q, int x);

int peek(CircularQueue* q);

void displayQueue(CircularQueue* q);

void freeQueue(CircularQueue* q);

int main() {

CircularQueue q;

init(&q);
int choice, value;

while (1) {

printf("\nCircular Queue Operations Menu:\n");

printf("1. Add an element to the queue\n");

printf("2. Peek at the front element\n");

printf("3. Display queue\n");

printf("4. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value: ");

scanf("%d", &value);

addQueue(&q, value);

break;

case 2:
value = peek(&q);

if (value != -1) {

printf("Front element is: %d\n", value);

break;

case 3:

displayQueue(&q);

break;

case 4:
freeQueue(&q);

exit(0);

default:

printf("Invalid choice! Please try again.\n");

return 0;

}
// Initialize the circular queue

void init(CircularQueue* q) {

q->front = NULL;

q->rear = NULL;

// Check if the queue is empty

int isEmpty(CircularQueue* q) {
return (q->front == NULL);

// Add an element to the circular queue

void addQueue(CircularQueue* q, int x) {

Node* newNode = (Node*)malloc(sizeof(Node));

if (!newNode) {

printf("Memory allocation failed!\n");

return;
}

newNode->data = x;

newNode->next = NULL;

if (isEmpty(q)) {

q->front = newNode;

q->rear = newNode;

newNode->next = newNode; // Point to itself

} else {
q->rear->next = newNode;

newNode->next = q->front; // Link new node to front

q->rear = newNode; // Update rear

// Peek at the front element of the queue

int peek(CircularQueue* q) {

if (isEmpty(q)) {
printf("Queue is empty! Cannot peek.\n");

return -1; // Indicate failure

return q->front->data;

// Display the elements of the queue

void displayQueue(CircularQueue* q) {

if (isEmpty(q)) {
printf("Queue is empty.\n");

return;

Node* current = q->front;

printf("Circular Queue contents: ");

do {

printf("%d ", current->data);

current = current->next;
} while (current != q->front);

printf("\n");

// Free the memory allocated for the queue

void freeQueue(CircularQueue* q) {

if (isEmpty(q)) return;

Node* current = q->front;


Node* temp;

do {

temp = current;

current = current->next;

free(temp);

} while (current != q->front);

q->front = NULL;

q->rear = NULL;
}

Q2. Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using insertion sort or selection
sort. [20]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

typedef struct {
char name[NAME_LENGTH];

int id; // Assuming there is an ID field; you can change this as necessary

} Employee;

// Function prototypes

void readEmployees(const char* filename, Employee employees[], int* count);

void insertionSort(Employee employees[], int count);

void displayEmployees(const Employee employees[], int count);

int main() {

Employee employees[MAX_EMPLOYEES];
int count = 0;

// Read employee data from file

readEmployees("employee.txt", employees, &count);

// Sort employees by name

insertionSort(employees, count);

// Display sorted employees

displayEmployees(employees, count);
return 0;

// Function to read employee data from a file

void readEmployees(const char* filename, Employee employees[], int* count) {

FILE* file = fopen(filename, "r");

if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);

}
while (fscanf(file, "%49s %d", employees[*count].name, &employees[*count].id) == 2) {

(*count)++;

if (*count >= MAX_EMPLOYEES) {

break; // Prevent overflow

fclose(file);

// Function to perform insertion sort on employee names


void insertionSort(Employee employees[], int count) {

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

Employee key = employees[i];

int j = i - 1;

// Move elements that are greater than key

while (j >= 0 && strcmp(employees[j].name, key.name) > 0) {

employees[j + 1] = employees[j];

j--;

employees[j + 1] = key;
}

// Function to display the employees

void displayEmployees(const Employee employees[], int count) {

printf("Sorted Employee List:\n");

for (int i = 0; i < count; i++) {

printf("Name: %s, ID: %d\n", employees[i].name, employees[i].id);

}
Slip 25

Q1) Read the data from the ‘employee.txt’ file and sort on age using Count sort and write the sorted data to another file
'sortedemponage.txt'.
 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

#define MAX_AGE 100 // Assumption: Age will be in the range 0-99

typedef struct {
char name[NAME_LENGTH];

int age;

} Employee;

// Function prototypes

void readEmployees(const char* filename, Employee employees[], int* count);

void countingSort(Employee employees[], int count);

void writeSortedEmployees(const char* filename, Employee employees[], int count);

int main() {
Employee employees[MAX_EMPLOYEES];

int count = 0;

// Read employee data from file

readEmployees("employee.txt", employees, &count);

// Sort employees by age

countingSort(employees, count);

// Write sorted employees to file


writeSortedEmployees("sortedemponage.txt", employees, count);

printf("Sorted employee data written to 'sortedemponage.txt'\n");

return 0;

// Function to read employee data from a file

void readEmployees(const char* filename, Employee employees[], int* count) {

FILE* file = fopen(filename, "r");


if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);

while (fscanf(file, "%49s %d", employees[*count].name, &employees[*count].age) == 2) {

(*count)++;

if (*count >= MAX_EMPLOYEES) {

break; // Prevent overflow

}
}

fclose(file);

// Function to perform counting sort on employee ages

void countingSort(Employee employees[], int count) {

int ageCount[MAX_AGE + 1] = {0}; // Initialize count array

Employee output[MAX_EMPLOYEES];
// Count occurrences of each age

for (int i = 0; i < count; i++) {

ageCount[employees[i].age]++;

// Cumulative count

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

ageCount[i] += ageCount[i - 1];

}
// Build the output array

for (int i = count - 1; i >= 0; i--) {

output[ageCount[employees[i].age] - 1] = employees[i];

ageCount[employees[i].age]--;

// Copy the sorted employees back to the original array

for (int i = 0; i < count; i++) {

employees[i] = output[i];

}
}

// Function to write sorted employee data to a file

void writeSortedEmployees(const char* filename, Employee employees[], int count) {

FILE* file = fopen(filename, "w");

if (file == NULL) {

perror("Unable to open file");

exit(EXIT_FAILURE);

}
for (int i = 0; i < count; i++) {

fprintf(file, "%s %d\n", employees[i].name, employees[i].age);

fclose(file);

Q2. Write a program to convert an infix expressionof the form (a*(b+c)*((d-


a)/b)) into its equivalent postfix notation. Consider usual precedence’s of operators. Use stack library of stack of characters using static
implementation

-> #include
<stdio.h> #include

<stdlib.h>
#include <ctype.h>

#include <string.h>

#define MAX_SIZE 100

typedef struct {

char items[MAX_SIZE];

int top;

} Stack;
// Stack functions

void init(Stack* s) {

s->top = -1;

int isFull(Stack* s) {

return s->top == MAX_SIZE - 1;

int isEmpty(Stack* s) {
return s->top == -1;

void push(Stack* s, char item) {

if (!isFull(s)) {

s->items[++(s->top)] = item;

char pop(Stack* s) {
if (!isEmpty(s)) {

return s->items[(s->top)--];

return '\0'; // Return null character if stack is empty

char peek(Stack* s) {

if (!isEmpty(s)) {

return s->items[s->top];

}
return '\0';

// Function to check precedence of operators

int precedence(char operator) {

switch (operator) {

case '+':

case '-':

return 1;

case '*':
case '/':

return 2;

case '^':

return 3;

default:

return 0;

// Function to convert infix to postfix


void infixToPostfix(const char* infix, char* postfix) {

Stack stack;

init(&stack);

int j = 0; // Index for postfix

for (int i = 0; infix[i] != '\0'; i++) {

char token = infix[i];

if (isalnum(token)) { // If the token is an operand

postfix[j++] = token;
} else if (token == '(') {

push(&stack, token);

} else if (token == ')') {

while (!isEmpty(&stack) && peek(&stack) != '(') {

postfix[j++] = pop(&stack);

pop(&stack); // Pop the '(' from the stack

} else { // The token is an operator

while (!isEmpty(&stack) && precedence(peek(&stack)) >= precedence(token)) {

postfix[j++] = pop(&stack);
}

push(&stack, token);

// Pop all the remaining operators from the stack

while (!isEmpty(&stack)) {

postfix[j++] = pop(&stack);

postfix[j] = '\0'; // Null-terminate the postfix string


}

int main() {

char infix[MAX_SIZE] = "(a*(b+c)*((d-a)/b))";

char postfix[MAX_SIZE];

infixToPostfix(infix, postfix);

printf("Infix Expression: %s\n", infix);

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


return 0;
}

}
Slip26

Q1. Implement a stack library (ststack.h) of integers using a static implementation of the stack and implementing the operations like
init(S), S=Push(S,x) and isEmpty(S). Write a driver program that includes stack library
and calls different stack operations. [10]

 #include

<stdio.h>

#include

<stdlib.h>

#define MAX_SIZE 100

// Stack structure definition

typedef struct {

int items[MAX_SIZE];

int top;
} Stack;

// Function to initialize the stack

void init(Stack* s) {

s->top = -1;

// Function to check if the stack is empty

int isEmpty(Stack* s) {

return s->top == -1;

}
// Function to push an element onto the stack

int push(Stack* s, int item) {

if (s->top < MAX_SIZE - 1) {

s->items[++(s->top)] = item;

return 1; // Success

return 0; // Stack overflow

// Function to pop an element from the stack


int pop(Stack* s) {

if (!isEmpty(s)) {

return s->items[(s->top)--];

return -1; // Stack underflow

// Function to peek at the top element of the stack

int peek(Stack* s) {

if (!isEmpty(s)) {

return s->items[s->top];
}

return -1; // Stack is empty

// Driver program to demonstrate stack operations

int main() {

Stack s;

init(&s);

printf("Stack operations:\n");
// Push elements onto the stack

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

if (push(&s, i)) {

printf("Pushed %d onto the stack.\n", i);

} else {

printf("Failed to push %d: Stack overflow.\n", i);

// Peek at the top element

int top = peek(&s);


if (top != -1) {

printf("Top element is: %d\n", top);

} else {

printf("Stack is empty.\n");

// Pop elements from the stack

while (!isEmpty(&s)) {

printf("Popped %d from the stack.\n", pop(&s));

}
// Check if the stack is empty

if (isEmpty(&s)) {

printf("Stack is now empty.\n");

} else {

printf("Stack is not empty.\n");

return 0;

Q2. There are lists where insertion should ensure the ordering of data elements. Since the elements are in ascending order the search
can terminate once equal or greater element is found. Implement a singly linked list of ordered integers(ascending/descending) with
insert, search, and display operations.
 #include

<stdio.h>

#include

<stdlib.h>

// Node structure definition

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(EXIT_FAILURE);

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to insert an element in ascending order


void insert(Node** head, int data) {

Node* newNode = createNode(data);

if (*head == NULL || (*head)->data >= newNode->data) {

newNode->next = *head;

*head = newNode;

} else {

Node* current = *head;

while (current->next != NULL && current->next->data < newNode->data) {

current = current->next;

newNode->next = current->next;
current->next = newNode;

// Function to search for an element in the list

Node* search(Node* head, int data) {

Node* current = head;

while (current != NULL) {

if (current->data == data) {

return current; // Element found

}
if (current->data > data) {

return NULL; // No need to continue searching

current = current->next;

return NULL; // Element not found

// Function to display the linked list

void display(Node* head) {

Node* current = head;


while (current != NULL) {

printf("%d -> ", current->data);

current = current->next;

printf("NULL\n");

// Main function to demonstrate the linked list operations

int main() {

Node* head = NULL;

int choice, value;


while (1) { printf("\

nMenu:\n");

printf("1. Insert an element\n");

printf("2. Search for an element\n");

printf("3. Display the list\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {
case 1:

printf("Enter the value to insert: ");

scanf("%d", &value);

insert(&head, value);

break;

case 2:

printf("Enter the value to search: ");

scanf("%d", &value);

if (search(head, value)) {

printf("Element %d found in the list.\n", value);

} else {
printf("Element %d not found in the list.\n", value);

break;

case 3:

display(head);

break;

case 4:

exit(0);

default:

printf("Invalid choice! Please try again.\n");

}
}

return 0;

}
Slip 27

Q1. Read the data from the file and sort on names in alphabetical order (use strcmp) using Merge sort and write the sorted data to
another file
'sortedemponname.txt' [10]

 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_NAME_LENGTH 100

#define MAX_EMPLOYEES 100

// Function to merge two halves

void merge(char names[][MAX_NAME_LENGTH], int left, int mid, int right) {


int i, j, k;

int n1 = mid - left + 1;

int n2 = right - mid;

// Create temporary arrays

char L[n1][MAX_NAME_LENGTH], R[n2][MAX_NAME_LENGTH];

// Copy data to temp arrays L[] and R[]

for (i = 0; i < n1; i++)

strcpy(L[i], names[left + i]);

for (j = 0; j < n2; j++)


strcpy(R[j], names[mid + 1 + j]);

// Merge the temporary arrays back into names[left..right]

i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = left; // Initial index of merged subarray

while (i < n1 && j < n2) {

if (strcmp(L[i], R[j]) <= 0) {

strcpy(names[k], L[i]);

i++;

} else {
strcpy(names[k], R[j]);

j++;

} k+

+;

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

while (i < n1) {

strcpy(names[k], L[i]);

i++;

k++;
}

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

while (j < n2) {

strcpy(names[k], R[j]);

j++;

k++;

// Function to implement merge sort


void mergeSort(char names[][MAX_NAME_LENGTH], int left, int right) {

if (left < right) {

int mid = left + (right - left) / 2;

// Sort first and second halves

mergeSort(names, left, mid);

mergeSort(names, mid + 1, right);

merge(names, left, mid, right);

}
int main() {

FILE *inputFile, *outputFile;

char names[MAX_EMPLOYEES][MAX_NAME_LENGTH];

int count = 0;

// Open the input file

inputFile = fopen("employee.txt", "r");

if (inputFile == NULL) {

printf("Error opening file.\n");

return 1;

}
// Read names from the file

while (fgets(names[count], MAX_NAME_LENGTH, inputFile) != NULL) {

// Remove newline character if present

names[count][strcspn(names[count], "\n")] = 0;

count++;

fclose(inputFile);

// Sort names using merge sort

mergeSort(names, 0, count - 1);


// Open the output file

outputFile = fopen("sortedemponname.txt", "w");

if (outputFile == NULL) {

printf("Error opening output file.\n");

return 1;

// Write sorted names to the output file

for (int i = 0; i < count; i++) {

fprintf(outputFile, "%s\n", names[i]);


}

fclose(outputFile);

printf("Names sorted and written to 'sortedemponname.txt'.\n");

return 0;

Q2. Write a program that adds two single variable polynomials. Each polynomial should be represented as a list with linked list
implementation.

 #include

<stdio.h>

#include

<stdlib.h>
// Node structure for polynomial terms

typedef struct Node {

int coefficient;

int exponent;

struct Node* next;

} Node;

// Function to create a new polynomial term

Node* createTerm(int coeff, int exp) {

Node* newTerm = (Node*)malloc(sizeof(Node));

newTerm->coefficient = coeff;
newTerm->exponent = exp;

newTerm->next = NULL;

return newTerm;

// Function to insert a term in the polynomial

void insertTerm(Node** poly, int coeff, int exp) {

Node* newTerm = createTerm(coeff, exp);

if (*poly == NULL || (*poly)->exponent < exp) {

newTerm->next = *poly;

*poly = newTerm;
} else {

Node* current = *poly;

while (current->next != NULL && current->next->exponent >= exp) {

current = current->next;

if (current->exponent == exp) {

current->coefficient += coeff; // Combine coefficients if exponents are equal

free(newTerm); // Free the newly created term

} else {

newTerm->next = current->next;

current->next = newTerm;
}

// Function to add two polynomials

Node* addPolynomials(Node* poly1, Node* poly2) {

Node* result = NULL;

while (poly1 != NULL) {

insertTerm(&result, poly1->coefficient, poly1->exponent);

poly1 = poly1->next;
}

while (poly2 != NULL) {

insertTerm(&result, poly2->coefficient, poly2->exponent);

poly2 = poly2->next;

return result;

// Function to display the polynomial


void displayPolynomial(Node* poly) {

Node* current = poly;

while (current != NULL) {

printf("%dx^%d", current->coefficient, current->exponent);

current = current->next;

if (current != NULL) {

printf(" + ");

printf("\n");

}
// Main function to demonstrate polynomial addition

int main() {

Node* poly1 = NULL;

Node* poly2 = NULL;

// First polynomial: 5x^2 + 4x^1 + 2

insertTerm(&poly1, 5, 2);

insertTerm(&poly1, 4, 1);

insertTerm(&poly1, 2, 0);
// Second polynomial: 3x^1 + 7x^0

insertTerm(&poly2, 3, 1);

insertTerm(&poly2, 7, 0);

printf("First Polynomial: ");

displayPolynomial(poly1);

printf("Second Polynomial: ");

displayPolynomial(poly2);

Node* result = addPolynomials(poly1, poly2);


printf("Resultant Polynomial: ");

displayPolynomial(result);

// Freeing memory (not shown here for brevity)

return 0;

Slip 28
Q1. Implement a stack library (ststack.h) of integers using a static implementation of the stack and implementing the above six
operations. Write a driver program that includes stack library and calls different stack operations.
 #include

<stdio.h>

#include

<stdlib.h>
#define MAX_SIZE 100

// Stack structure

typedef struct Stack {

int items[MAX_SIZE];

int top;

} Stack;

// Function to initialize the stack


void init(Stack* s) {

s->top = -1;

// Function to check if the stack is full

int isFull(Stack* s) {

return s->top == MAX_SIZE - 1;

// Function to check if the stack is empty


int isEmpty(Stack* s) {

return s->top == -1;

// Function to push an element onto the stack

void push(Stack* s, int value) {

if (isFull(s)) {

printf("Stack overflow! Cannot push %d\n", value);

return;

}
s->items[++(s->top)] = value;

printf("%d pushed onto stack\n", value);

// Function to pop an element from the stack

int pop(Stack* s) {

if (isEmpty(s)) {

printf("Stack underflow! Cannot pop from empty stack\n");

return -1; // Return a sentinel value

}
return s->items[(s->top)--];

// Function to peek at the top element of the stack

int peek(Stack* s) {

if (isEmpty(s)) {

printf("Stack is empty! Cannot peek\n");

return -1; // Return a sentinel value

return s->items[s->top];
}

// Function to display the stack elements

void display(Stack* s) {

if (isEmpty(s)) {

printf("Stack is empty!\n");

return;

printf("Stack elements: ");

for (int i = s->top; i >= 0; i--) {


printf("%d ", s->items[i]);

printf("\n");

// Driver program

int main() {

Stack s;

init(&s);
int choice, value;

while (1) {

printf("\nStack Operations:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Check if Empty\n");

printf("5. Check if Full\n");

printf("6. Display Stack\n");


printf("7. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to push: ");

scanf("%d", &value);

push(&s, value);

break;
case 2:

value = pop(&s);

if (value != -1) {

printf("%d popped from stack\n", value);

break;

case 3:

value = peek(&s);

if (value != -1) {

printf("Top element is: %d\n", value);


}

break;

case 4:

if (isEmpty(&s)) {

printf("Stack is empty\n");

} else {

printf("Stack is not empty\n");

break;

case 5:
if (isFull(&s)) {

printf("Stack is full\n");

} else {

printf("Stack is not full\n");

break;

case 6:

display(&s);

break;

case 7:
printf("Exiting...\n");

exit(0);

default:

printf("Invalid choice! Please try again.\n");

return 0;

} [10]
Q2. Read the data from the ‘employee.txt’ file and sort on age using Merge sort or Quick sort and write the sorted data to another file
'sortedemponage.txt'.

 #include

<stdio.h>

#include

<stdlib.h>

#include

<string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

// Structure to hold employee data

typedef struct {

char name[NAME_LENGTH];
int age;

} Employee;

// Function to swap two employees

void swap(Employee* a, Employee* b) {

Employee temp = *a;

*a = *b;

*b = temp;

// Partition function for Quick Sort


int partition(Employee arr[], int low, int high) {

int pivot = arr[high].age; // choosing the last element as pivot

int i = low - 1; // index of smaller element

for (int j = low; j < high; j++) {

if (arr[j].age < pivot) {

i++;

swap(&arr[i], &arr[j]);

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

return i + 1;
}

// Quick Sort function

void quickSort(Employee arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

}
// Function to read employee data from file

int readEmployees(const char* filename, Employee employees[]) {

FILE* file = fopen(filename, "r");

if (!file) {

perror("Unable to open file");

return 0;

int count = 0;

while (fscanf(file, "%49[^,],%d\n", employees[count].name, &employees[count].age) == 2) {

count++;
if (count >= MAX_EMPLOYEES) {

break; // Prevent overflow

fclose(file);

return count;

// Function to write sorted employee data to file

void writeEmployees(const char* filename, Employee employees[], int count) {

FILE* file = fopen(filename, "w");


if (!file) {

perror("Unable to open file");

return;

for (int i = 0; i < count; i++) {

fprintf(file, "%s,%d\n", employees[i].name, employees[i].age);

fclose(file);

}
int main() {

Employee employees[MAX_EMPLOYEES];

int count = readEmployees("employee.txt", employees);

if (count == 0) {

printf("No employees found or unable to read file.\n");

return 1;

// Sorting employees by age

quickSort(employees, 0, count - 1);


// Writing sorted employees to file

writeEmployees("sortedemponage.txt", employees, count);

printf("Employees sorted by age and written to 'sortedemponage.txt'.\n");

return 0;

Slip29
Q1. Implement a stack library (ststack.h) of integers using a static implementation of the stack and implementing the operations like
init(S), S=push(S), and X=peek(S). Write a driver program that includes stack library and calls different stack operations. [10]

 #include

<stdio.h>

#include

<stdlib.h>
#define MAX_SIZE 100

// Stack structure definition

typedef struct Stack {

int items[MAX_SIZE];

int top;

} Stack;

// Function to initialize the stack

void init(Stack* s) {
s->top = -1; // Stack is initially empty

// Function to check if the stack is full

int isFull(Stack* s) {

return s->top == MAX_SIZE - 1;

// Function to check if the stack is empty

int isEmpty(Stack* s) {

return s->top == -1;


}

// Function to push an element onto the stack

void push(Stack* s, int value) {

if (isFull(s)) {

printf("Stack overflow! Cannot push %d\n", value);

return;

s->items[++(s->top)] = value;

printf("%d pushed onto stack\n", value);

}
// Function to peek at the top element of the stack

int peek(Stack* s) {

if (isEmpty(s)) {

printf("Stack is empty! Cannot peek\n");

return -1; // Return a sentinel value

return s->items[s->top];

// Driver program
int main() {

Stack s;

init(&s);

int choice, value;

while (1) {

printf("\nStack Operations:\n");

printf("1. Push\n");

printf("2. Peek\n");

printf("3. Check if Empty\n");


printf("4. Check if Full\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to push: ");

scanf("%d", &value);

push(&s, value);

break;
case 2:

value = peek(&s);

if (value != -1) {

printf("Top element is: %d\n", value);

break;

case 3:

if (isEmpty(&s)) {

printf("Stack is empty\n");

} else {

printf("Stack is not empty\n");


}

break;

case 4:

if (isFull(&s)) {

printf("Stack is full\n");

} else {

printf("Stack is not full\n");

break;

case 5:

printf("Exiting...\n");
exit(0);

default:

printf("Invalid choice! Please try again.\n");

return 0;

Q2. There are lists where new elements are always appended at the end of the list. The list can be implemented as a circular list with
the external pointer pointing to the last element of the list. Implement singly linked circular list of integers with append and display
operations. The operation append(L, n), appends to the end of the list, n integers accepted from user. [20]

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

// Node structure definition

typedef struct Node {

int data;

struct Node* next;

} Node;

// Circular linked list structure

typedef struct CircularLinkedList {

Node* last;

} CircularLinkedList;
// Function to initialize the circular linked list

void initList(CircularLinkedList* list) {

list->last = NULL; // List is initially empty

// Function to append a new element to the circular linked list

void append(CircularLinkedList* list, int value) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = value;

if (list->last == NULL) {
// List is empty

newNode->next = newNode; // Point to itself

list->last = newNode;

} else {

// List is not empty

newNode->next = list->last->next; // New node points to first node

list->last->next = newNode; // Last node points to new node

list->last = newNode; // Update last to new node

printf("%d appended to the list.\n", value);

}
// Function to display the circular linked list

void display(CircularLinkedList* list) {

if (list->last == NULL) {

printf("The list is empty.\n");

return;

Node* current = list->last->next; // Start from the first node

do {

printf("%d -> ", current->data);

current = current->next;
} while (current != list->last->next);

printf("(back to start)\n");

// Driver program

int main() {

CircularLinkedList list;

initList(&list);

int n, value;

printf("Enter the number of integers to append: ");


scanf("%d", &n);

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

printf("Enter integer %d: ", i + 1);

scanf("%d", &value);

append(&list, value);

printf("The circular linked list is:\n");

display(&list);

return 0;
}

Slip30
Q1. Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort [10]

-> #include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_EMPLOYEES 100

#define NAME_LENGTH 50

// Structure to hold employee data


typedef struct {

char name[NAME_LENGTH];

int age;

// You can add more fields here if needed

} Employee;

// Function to swap two employees

void swap(Employee* a, Employee* b) {

Employee temp = *a;

*a = *b;

*b = temp;
}

// Bubble sort function to sort employees by name

void bubbleSort(Employee employees[], int n) {

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

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

if (strcmp(employees[j].name, employees[j + 1].name) > 0) {

swap(&employees[j], &employees[j + 1]);

}
}

// Function to read employees from file

int readEmployeesFromFile(const char* filename, Employee employees[]) {

FILE* file = fopen(filename, "r");

if (file == NULL) {

printf("Could not open file %s\n", filename);

return 0;

int count = 0;
while (fscanf(file, "%49s %d", employees[count].name, &employees[count].age) == 2) {

count++;

fclose(file);

return count;

// Function to write sorted employees to a new file

void writeSortedEmployeesToFile(const char* filename, Employee employees[], int n) {

FILE* file = fopen(filename, "w");


if (file == NULL) {

printf("Could not open file %s\n", filename);

return;

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

fprintf(file, "%s %d\n", employees[i].name, employees[i].age);

fclose(file);

}
int main() {

Employee employees[MAX_EMPLOYEES];

int n = readEmployeesFromFile("employee.txt", employees);

if (n == 0) {

printf("No employee data found or file could not be read.\n");

return 1;

bubbleSort(employees, n);
// Write sorted data to a new file

writeSortedEmployeesToFile("sorted_employees.txt", employees, n);

printf("Employee data sorted by name and saved to 'sorted_employees.txt'.\n");

return 0;

Q2. Write a program that merges two ordered linked lists into third new list. When two lists are merged the data in the resulting list are
also ordered. The two original lists should be left unchanged. That is merged list should be new
one. Use linked implementation. [20]

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

// Node structure for 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));


newNode->data = data;

newNode->next = NULL;

return newNode;

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

void insertEnd(Node** head, int data) {

Node* newNode = createNode(data);

if (*head == NULL) {

*head = newNode;

return;
}

Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

// Function to display the linked list

void display(Node* head) {

Node* temp = head;


while (temp != NULL) {

printf("%d -> ", temp->data);

temp = temp->next;

printf("NULL\n");

// Function to merge two ordered linked lists

Node* mergeOrderedLists(Node* list1, Node* list2) {

Node* mergedList = NULL;

Node** lastPtrRef = &mergedList;


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

if (list1->data <= list2->data) {

*lastPtrRef = createNode(list1->data);

list1 = list1->next;

} else {

*lastPtrRef = createNode(list2->data);

list2 = list2->next;

lastPtrRef = &((*lastPtrRef)->next);

}
// Append remaining elements from list1, if any

while (list1 != NULL) {

*lastPtrRef = createNode(list1->data);

lastPtrRef = &((*lastPtrRef)->next);

list1 = list1->next;

// Append remaining elements from list2, if any

while (list2 != NULL) {

*lastPtrRef = createNode(list2->data);
lastPtrRef = &((*lastPtrRef)->next);

list2 = list2->next;

return mergedList;

// Driver program

int main() {

Node* list1 = NULL;

Node* list2 = NULL;


// Create first ordered list

insertEnd(&list1, 1);

insertEnd(&list1, 3);

insertEnd(&list1, 5);

// Create second ordered list

insertEnd(&list2, 2);

insertEnd(&list2, 4);

insertEnd(&list2, 6);
printf("List 1: ");

display(list1);

printf("List 2: ");

display(list2);

// Merge the two lists

Node* mergedList = mergeOrderedLists(list1, list2);

printf("Merged List: ");

display(mergedList);
// Free allocated memory (optional, but good practice)

// Implement free function to avoid memory leaks if needed

return 0;

You might also like