0% found this document useful (0 votes)
8 views

ds_slip

The document contains multiple C programs demonstrating various data structures and algorithms, including binary search, stack operations, bubble sort, binary search tree, insertion sort, linked list operations, and postfix expression evaluation. Each program includes the necessary functions and a main function to execute the operations. The programs cover fundamental concepts in C programming related to data structures and algorithms.

Uploaded by

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

ds_slip

The document contains multiple C programs demonstrating various data structures and algorithms, including binary search, stack operations, bubble sort, binary search tree, insertion sort, linked list operations, and postfix expression evaluation. Each program includes the necessary functions and a main function to execute the operations. The programs cover fundamental concepts in C programming related to data structures and algorithms.

Uploaded by

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

Slip 1

Write a C program to search an element by using binary search method.


#include <stdio.h>

int binarySearch(int arr[], int n, int key) {


int low = 0, high = n - 1;

while (low <= high) {


int mid = (low + high) / 2;

if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; // Element not found
}

int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 10;

int result = binarySearch(arr, n, key);

if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");

return 0;
}

Write a C program to implement static stack of integer with operations: (20)


● Push ()
● Pop ()
● Empty ()
#include <stdio.h>
#define MAX 20

int stack[MAX], top = -1;

void push(int value) {


if (top == MAX - 1)
printf("Stack Overflow\n");
else
stack[++top] = value;
}

int pop() {
if (top == -1)
printf("Stack Underflow\n");
else
return stack[top--];
return -1; // Return -1 if underflow occurs
}

int empty() {
return top == -1;
}

int main() {
int choice, value;

do {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Check if Empty\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(value);
break;
case 2:
pop();
break;
case 3:
if (empty())
printf("Stack is empty.\n");
else
printf("Stack is not empty.\n");
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 4);

return 0;
}

Slip 2

Write a C program to sort n elements using Bubble Sort.


#include <stdio.h>

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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array: ");


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

return 0;
}

Write a C program to create binary search tree (BST) of integer numbers and display its in- order traversal
#include <stdio.h>
#include <stdlib.h>

// Node structure for the BST


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

// Function to create a new node


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

// Function to insert a new node in the BST


struct Node* insert(struct Node* root, int value) {
if (root == NULL)
return newNode(value);
if (value < root->data)
root->left = insert(root->left, value);
else
root->right = insert(root->right, value);
return root;
}
// Function for in-order traversal
void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}

int main() {
struct Node* root = NULL;
int arr[] = {50, 30, 20, 40, 70, 60, 80};
int n = sizeof(arr) / sizeof(arr[0]);

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


root = insert(root, arr[i]);

printf("In-order traversal: ");


inOrder(root);
printf("\n");

return 0;
}

Slip 3

Write a C program to sort n numbers using insertion sort integers.


#include <stdio.h>

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


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

// Move elements greater than key to one position ahead


while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printf("Sorted array: ");


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

return 0;
}

Write a C program to find intersection of two linked list.

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

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

// Function to create a new node


struct Node* newNode(int value) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = value;
node->next = NULL;
return node;
}
// Function to find the intersection of two linked lists
struct Node* getIntersection(struct Node* head1, struct Node* head2) {
struct Node* result = NULL, *tail = NULL;

while (head1 != NULL && head2 != NULL) {


if (head1->data == head2->data) {
struct Node* temp = newNode(head1->data);
if (result == NULL)
result = tail = temp;
else {
tail->next = temp;
tail = temp;
}
head1 = head1->next;
head2 = head2->next;
} else if (head1->data < head2->data) {
head1 = head1->next;
} else {
head2 = head2->next;
}
}
return result;
}

// Function to print a linked list


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

int main() {
// Creating first linked list: 1 -> 2 -> 3 -> 4 -> 6
struct Node* head1 = newNode(1);
head1->next = newNode(2);
head1->next->next = newNode(3);
head1->next->next->next = newNode(4);
head1->next->next->next->next = newNode(6);

// Creating second linked list: 2 -> 4 -> 6 -> 8


struct Node* head2 = newNode(2);
head2->next = newNode(4);
head2->next->next = newNode(6);
head2->next->next->next = newNode(8);

// Find intersection
struct Node* intersection = getIntersection(head1, head2);

// Print the intersection list


printf("Intersection: ");
printList(intersection);

return 0;
}

Slip 4

Write a C program to search an element using linear search method.


#include <stdio.h>

int linearSearch(int arr[], int size, int target) {


for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the found element
}
}
return -1; // Return -1 if not found
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int target;

printf("Enter element to search: ");


scanf("%d", &target);

int result = linearSearch(arr, size, target);


if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found in the array.\n");
}

return 0;
}
Write a C menu driven program to implement singly circular linked list of integers with Following operations: (20)
● Create
● Insert
● Delete
● Display

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

// Node structure for the circular linked list


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

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = newNode; // Points to itself
return newNode;
}

// Function to create the circular linked list


struct Node* createList() {
struct Node* head = NULL;
int value;

printf("Enter value (0 to stop): ");


while (1) {
scanf("%d", &value);
if (value == 0) break;

struct Node* newNode = createNode(value);


if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != head) // Find the last node
temp = temp->next;
temp->next = newNode; // Link the last node to the new node
}
newNode->next = head; // Link new node back to head
}
return head;
}

// Function to insert a node at the end


struct Node* insertNode(struct Node* head, int value) {
struct Node* newNode = createNode(value);
if (head == NULL) {
return newNode; // If the list is empty
}

struct Node* temp = head;


while (temp->next != head) // Find the last node
temp = temp->next;

temp->next = newNode; // Link the last node to the new node


newNode->next = head; // Link new node back to head
return head;
}

// Function to delete a node with a specific value


struct Node* deleteNode(struct Node* head, int value) {
if (head == NULL) {
printf("List is empty!\n");
return NULL;
}
struct Node *temp = head, *prev = NULL;
// Find the node to be deleted
do {
if (temp->data == value) {
if (prev != NULL)
prev->next = temp->next; // Link previous node to next
else {
// Deleting head
struct Node* last = head;
while (last->next != head) // Find the last node
last = last->next;
last->next = temp->next; // Update last node's next
head = temp->next; // Update head if needed
}
free(temp);
printf("Node with value %d deleted!\n", value);
return head;
}
prev = temp;
temp = temp->next;
} while (temp != head);

printf("Node with value %d not found!\n", value);


return head;
}

// Function to display the list


void display(struct Node* head) {
if (head == NULL) {
printf("List is empty!\n");
return;
}

struct Node* temp = head;


printf("Circular Linked List: ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}

// Main menu-driven program


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

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

switch (choice) {
case 1:
head = createList();
break;
case 2:
printf("Enter value to insert: ");
scanf("%d", &value);
head = insertNode(head, value);
break;
case 3:
printf("Enter value to delete: ");
scanf("%d", &value);
head = deleteNode(head, value);
break;
case 4:
display(head);
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 5);

return 0;
}
Slip 5

Write a C program to create and display singly linked list.


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

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

// Create a new node


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

// Create linked list and return head


struct Node* createLinkedList() {
struct Node *head = NULL, *tail = NULL;
int value;

printf("Enter values (0 to stop): ");


while (scanf("%d", &value), value) {
struct Node* newNode = createNode(value);
if (!head) head = tail = newNode; // First node
else tail->next = newNode, tail = newNode; // Link new node
}
return head;
}

// Display linked list


void displayList(struct Node* head) {
printf("Singly Linked List: ");
for (struct Node* temp = head; temp; temp = temp->next)
printf("%d -> ", temp->data);
printf("NULL\n");
}

// Main function
int main() {
displayList(createLinkedList());
return 0;
}

Write a c program to evaluate postfix expression using stack.

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

#define MAX 100

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

// Stack operations
struct Stack* createStack() {
struct Stack* s = malloc(sizeof(struct Stack));
s->top = -1;
return s;
}

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


void push(struct Stack* s, int item) { s->items[++s->top] = item; }
int pop(struct Stack* s) { return s->items[s->top--]; }

// Evaluate postfix expression


int evaluatePostfix(char* expr) {
struct Stack* s = createStack();
for (int i = 0; expr[i]; i++) {
if (isdigit(expr[i])) push(s, expr[i] - '0');
else {
int b = pop(s), a = pop(s);
switch (expr[i]) {
case '+': push(s, a + b); break;
case '-': push(s, a - b); break;
case '*': push(s, a * b); break;
case '/': push(s, a / b); break;
}
}
}
return pop(s);
}

int main() {
char expression[MAX];
printf("Enter a postfix expression: ");
fgets(expression, sizeof(expression), stdin);
printf("Result: %d\n", evaluatePostfix(expression));
return 0;
}

Slip 6

Q.1) Write a C program to reverse a string using Stack


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

#define MAX 100

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

// Stack operations
struct Stack* createStack() {
struct Stack* s = (struct Stack*)malloc(sizeof(struct Stack));
s->top = -1;
return s;
}

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


int isEmpty(struct Stack* s) { return s->top == -1; }
void push(struct Stack* s, char item) { if (!isFull(s)) s->items[++s->top] = item; }
char pop(struct Stack* s) { return !isEmpty(s) ? s->items[s->top--] : '\0'; }

// Function to reverse a string using stack


void reverseString(char* str) {
struct Stack* s = createStack();
int length = strlen(str);

// Push all characters of the string onto the stack


for (int i = 0; i < length; i++) {
push(s, str[i]);
}

// Pop all characters from the stack and replace the original string
for (int i = 0; i < length; i++) {
str[i] = pop(s);
}
}

int main() {
char str[MAX];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0; // Remove the newline character if present

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

return 0;
}
Write a C program to read the data from the file “employee.txt” which contains empno and empname and sort the data on
names alphabetically (use strcmp) using Bubble Sort.

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

#define MAX_EMPLOYEES 100


#define MAX_NAME_LEN 50

// Employee structure
struct Employee {
int empno;
char empname[MAX_NAME_LEN];
};

// Function to compare two employees based on their names


int compareEmployees(const void* a, const void* b) {
struct Employee* empA = (struct Employee*)a;
struct Employee* empB = (struct Employee*)b;
return strcmp(empA->empname, empB->empname);
}

// Function to perform Bubble Sort on employee array based on names


void bubbleSort(struct Employee employees[], int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (compareEmployees(&employees[j], &employees[j + 1]) > 0) {
struct Employee temp = employees[j];
employees[j] = employees[j + 1];
employees[j + 1] = temp;
}
}
}
}

int main() {
FILE* file = fopen("employee.txt", "r");
if (!file) {
printf("Error opening file.\n");
return 1;
}

struct Employee employees[MAX_EMPLOYEES];


int count = 0;

// Read data from the file


while (fscanf(file, "%d %[^\n]", &employees[count].empno, employees[count].empname) == 2) {
count++;
}
fclose(file);

// Sort the employees by name


bubbleSort(employees, count);

// Display sorted employee data


printf("Sorted Employee Data (by Name):\n");
for (int i = 0; i < count; i++) {
printf("Emp No: %d, Name: %s\n", employees[i].empno, employees[i].empname);
}

return 0;
}

Slip 7

Write a C program to find the length of singly linked list

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

// Node structure for the singly linked list


struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}

// Function to find the length of the linked list


int lengthOfList(struct Node* head) {
int length = 0;
while (head) {
length++;
head = head->next;
}
return length;
}

// Main function
int main() {
struct Node* head = NULL;
struct Node* tail = NULL;
int value;

// Creating the linked list


printf("Enter values (0 to stop): ");
while (1) {
scanf("%d", &value);
if (value == 0) break;
struct Node* newNode = createNode(value);
if (!head) head = tail = newNode; // First node
else tail->next = newNode, tail = newNode; // Link new node
}

// Find and print the length of the linked list


printf("Length of the linked list: %d\n", lengthOfList(head));
return 0;
}

Q.2) Write a C program to implement dynamic implementation of stack of integers with followingoperation:
a) push()
b) pop ()
c) isempty()
d) isfull()
e) display ()

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

struct Stack {
int *array;
int top;
int capacity;
};

// Function to create a stack of given capacity


struct Stack* createStack(int capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(capacity * sizeof(int));
return stack;
}

// Function to check if the stack is full


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

// Function to check if the stack is empty


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

// Function to add an item to stack


void push(struct Stack* stack, int item) {
if (isFull(stack)) {
printf("Stack overflow. Unable to push %d\n", item);
return;
}
stack->array[++stack->top] = item;
}

// Function to remove an item from stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow. No elements to pop.\n");
return -1; // Return an invalid value
}
return stack->array[stack->top--];
}

// Function to display the stack


void display(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->array[i]);
}
printf("\n");
}

// Main function to demonstrate stack operations


int main() {
int capacity;
printf("Enter stack capacity: ");
scanf("%d", &capacity);

struct Stack* stack = createStack(capacity);


int choice, value;

while (1) {
printf("\n1. Push\n2. Pop\n3. Is Empty\n4. Is Full\n5. Display\n6. Exit\n");
printf("Choose an operation: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(stack, value);
break;
case 2:
value = pop(stack);
if (value != -1) printf("Popped: %d\n", value);
break;
case 3:
printf(isEmpty(stack) ? "Stack is empty.\n" : "Stack is not empty.\n");
break;
case 4:
printf(isFull(stack) ? "Stack is full.\n" : "Stack is not full.\n");
break;
case 5:
display(stack);
break;
case 6:
free(stack->array);
free(stack);
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

Slip 8

Q.1) Write a C program to create and display doubly linked list.


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

// Node structure for the doubly linked list


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

// Function to create a new node


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

// Function to create and display the doubly linked list


void createAndDisplayDoublyLinkedList() {
struct Node* head = NULL;
struct Node* tail = NULL;
int value;

printf("Enter values for the doubly linked list (0 to stop): ");


while (1) {
scanf("%d", &value);
if (value == 0) break;

struct Node* newNode = createNode(value);


if (!head) {
head = tail = newNode; // First node
} else {
tail->next = newNode; // Link new node
newNode->prev = tail; // Set previous link
tail = newNode; // Update tail
}
}

// Display the doubly linked list


printf("Doubly Linked List: ");
struct Node* temp = head;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Main function
int main() {
createAndDisplayDoublyLinkedList();
return 0;
}

Concatenate Two Singly Linked Lists


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

// Node structure for the singly linked list


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

// Function to create a new node


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

// Function to create a singly linked list


struct Node* createLinkedList() {
struct Node* head = NULL;
struct Node* tail = NULL;
int value;

printf("Enter values for the linked list (0 to stop): ");


while (1) {
scanf("%d", &value);
if (value == 0) break;

struct Node* newNode = createNode(value);


if (!head) {
head = tail = newNode; // First node
} else {
tail->next = newNode; // Link new node
tail = newNode; // Update tail
}
}
return head;
}
// Function to concatenate two singly linked lists
struct Node* concatenateLists(struct Node* list1, struct Node* list2) {
if (!list1) return list2; // If first list is empty, return second list
if (!list2) return list1; // If second list is empty, return first list

struct Node* temp = list1;


while (temp->next) { // Traverse to the end of the first list
temp = temp->next;
}
temp->next = list2; // Link the end of the first list to the second list
return list1; // Return the concatenated list
}

// Function to display a linked list


void displayList(struct Node* head) {
struct Node* temp = head;
printf("Linked List: ");
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Main function
int main() {
printf("Create first linked list:\n");
struct Node* list1 = createLinkedList();
printf("Create second linked list:\n");
struct Node* list2 = createLinkedList();

struct Node* concatenatedList = concatenateLists(list1, list2);


displayList(concatenatedList);
return 0;
}

Slip 16
Q.1) Write a C program to sort an integer array using a recursive binary search method.
#include <stdio.h>

// Function to swap two integers


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

// Partition function for Quick Sort


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

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


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

// Recursive Quick Sort 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); // Recursively sort elements before partition
quickSort(arr, pi + 1, high); // Recursively sort elements after partition
}
}

// Function to print the array


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

int main() {
int arr[] = {34, 7, 23, 32, 5, 62};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);
quickSort(arr, 0, n - 1);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

Q2. Write a C program to convert infix expression into Postfix.


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

#define MAX 100

char stack[MAX];
int top = -1;

// Function to push an operator onto the stack


void push(char c) {
stack[++top] = c;
}

// Function to pop an operator from the stack


char pop() {
return stack[top--];
}

// Function to get the precedence of operators


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

// Function to check if the character is an operator


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

// Function to convert infix to postfix


void infixToPostfix(char* infix, char* postfix) {
int j = 0; // Index for postfix
for (int i = 0; infix[i]; i++) {
if (isalnum(infix[i])) {
postfix[j++] = infix[i]; // Add operand to postfix
} else if (infix[i] == '(') {
push(infix[i]); // Push '(' to stack
} else if (infix[i] == ')') {
while (top != -1 && stack[top] != '(') {
postfix[j++] = pop(); // Pop from stack to postfix
}
pop(); // Pop '('
} else if (isOperator(infix[i])) {
while (top != -1 && precedence(stack[top]) >= precedence(infix[i])) {
postfix[j++] = pop(); // Pop higher or equal precedence operators
}
push(infix[i]); // Push the current operator
}
}

// Pop all remaining operators in the stack


while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}

int main() {
char infix[MAX], postfix[MAX];
printf("Enter infix expression: ");
scanf("%s", infix);

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

return 0;
}
Slip 17
Q.1) Write a C program to sort an array of structure using bubblesort method. Consider an array of structure Employee
with details: emp_id, Name, Address. Sort on emp_id and display
the employee details. (10)
#include <stdio.h>
#include <string.h>

// Structure to store employee details


struct Employee {
int emp_id;
char name[30];
char address[50];
};

// Function to swap two employee records


void swap(struct Employee* a, struct Employee* b) {
struct Employee temp = *a;
*a = *b;
*b = temp;
}

// Bubble sort to sort employees by emp_id


void bubbleSort(struct Employee arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j].emp_id > arr[j + 1].emp_id) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}

// Function to display employee details


void display(struct Employee arr[], int n) {
for (int i = 0; i < n; i++) {
printf("ID: %d, Name: %s, Address: %s\n", arr[i].emp_id, arr[i].name, arr[i].address);
}
}

int main() {
int n = 3; // Number of employees
struct Employee employees[] = {
{102, "Alice", "123 Street"},
{101, "Bob", "456 Avenue"},
{103, "Charlie", "789 Boulevard"}
};

printf("Before sorting:\n");
display(employees, n);

bubbleSort(employees, n);

printf("\nAfter sorting by emp_id:\n");


display(employees, n);

return 0;
}

Q.2) Write a C program to check whether an expression has correct pairs of parentheses, using Stack.
#include <stdio.h>
#include <string.h>

#define MAX 100

char stack[MAX];
int top = -1;

void push(char c) { stack[++top] = c; }

char pop() { return stack[top--]; }

int isBalanced(char* expr) {


for (int i = 0; expr[i] != '\0'; i++) {
if (expr[i] == '(' || expr[i] == '{' || expr[i] == '[')
push(expr[i]);
else if (expr[i] == ')' || expr[i] == '}' || expr[i] == ']') {
if (top == -1) return 0;
char last = pop();
if ((expr[i] == ')' && last != '(') ||
(expr[i] == '}' && last != '{') ||
(expr[i] == ']' && last != '['))
return 0;
}
}
return top == -1;
}

int main() {
char expr[MAX];
printf("Enter expression: ");
scanf("%s", expr);

if (isBalanced(expr))
printf("Balanced\n");
else
printf("Unbalanced\n");

return 0;
}

Slip 18
Q.1) Write a C program to display the city code of the corresponding city name using linear search method. The structure
is:
struct city
{
int city_code;
char name[40];
}
#include <stdio.h>
#include <string.h>

// Structure to store city details


struct city {
int city_code;
char name[30];
};

// Function to search for city code by city name


int searchCity(struct city cities[], int n, char target[]) {
for (int i = 0; i < n; i++) {
if (strcmp(cities[i].name, target) == 0) {
return cities[i].city_code;
}
}
return -1; // Return -1 if city not found
}

int main() {
struct city cities[] = {
{101, "NewYork"},
{102, "London"},
{103, "Paris"}
};
int n = sizeof(cities) / sizeof(cities[0]);

char target[30];
printf("Enter city name: ");
scanf("%s", target);

int code = searchCity(cities, n, target);


if (code != -1) {
printf("City Code: %d\n", code);
} else {
printf("City not found.\n");
}

return 0;
}

Write C program to construct a graph using adjacency matrix and display its adjacency list
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

// Function to display the adjacency list


void displayAdjList(int adjMatrix[MAX][MAX], int vertices) {
for (int i = 0; i < vertices; i++) {
printf("Vertex %d: ", i);
for (int j = 0; j < vertices; j++) {
if (adjMatrix[i][j] == 1) {
printf("%d -> ", j);
}
}
printf("NULL\n");
}
}

int main() {
int vertices, edges, u, v;
int adjMatrix[MAX][MAX] = {0}; // Initialize the adjacency matrix with 0

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


scanf("%d", &vertices);

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


scanf("%d", &edges);

// Input edges for the adjacency matrix


for (int i = 0; i < edges; i++) {
printf("Enter edge (u v): ");
scanf("%d%d", &u, &v);
adjMatrix[u][v] = 1; // Marking the edge in the adjacency matrix
adjMatrix[v][u] = 1; // If undirected graph, uncomment this line
}

// Display adjacency list


printf("\nAdjacency List:\n");
displayAdjList(adjMatrix, vertices);

return 0;
}

Slip 19
Q.1) Write a C program to create and display singly Linked List.
#include <stdio.h>
#include <stdlib.h>

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

// Function to create a new node


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

// Function to insert a node at the end


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

// Function to display the linked list


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

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

// Inserting nodes into the linked list


insertEnd(&head, 10);
insertEnd(&head, 20);
insertEnd(&head, 30);
// Display the linked list
printf("Singly Linked List: ");
displayList(head);

return 0;
}

Write a C program to display addition of two polynomials using singly linked list.
#include <stdio.h>
#include <stdlib.h>

// Node structure for the polynomial


struct Node {
int coeff, pow;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int c, int p) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->coeff = c;
newNode->pow = p;
newNode->next = NULL;
return newNode;
}

// Function to add a term to the polynomial


void addTerm(struct Node** poly, int c, int p) {
struct Node* newNode = createNode(c, p);
newNode->next = *poly;
*poly = newNode;
}

// Function to add two polynomials


struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {
struct Node* sum = NULL;
while (poly1 != NULL && poly2 != NULL) {
if (poly1->pow > poly2->pow) {
addTerm(&sum, poly1->coeff, poly1->pow);
poly1 = poly1->next;
} else if (poly1->pow < poly2->pow) {
addTerm(&sum, poly2->coeff, poly2->pow);
poly2 = poly2->next;
} else {
addTerm(&sum, poly1->coeff + poly2->coeff, poly1->pow);
poly1 = poly1->next;
poly2 = poly2->next;
}
}

while (poly1 != NULL) {


addTerm(&sum, poly1->coeff, poly1->pow);
poly1 = poly1->next;
}

while (poly2 != NULL) {


addTerm(&sum, poly2->coeff, poly2->pow);
poly2 = poly2->next;
}

return sum;
}

// Function to display the polynomial


void display(struct Node* poly) {
while (poly != NULL) {
printf("%dx^%d", poly->coeff, poly->pow);
poly = poly->next;
if (poly != NULL) printf(" + ");
}
printf("\n");
}

int main() {
struct Node *poly1 = NULL, *poly2 = NULL, *sum = NULL;

// First polynomial: 3x^2 + 5x + 6


addTerm(&poly1, 6, 0);
addTerm(&poly1, 5, 1);
addTerm(&poly1, 3, 2);
// Second polynomial: 4x^2 + 2x + 1
addTerm(&poly2, 1, 0);
addTerm(&poly2, 2, 1);
addTerm(&poly2, 4, 2);

// Display polynomials
printf("First Polynomial: ");
display(poly1);

printf("Second Polynomial: ");


display(poly2);

// Add polynomials
sum = addPolynomials(poly1, poly2);

// Display the sum


printf("Sum of Polynomials: ");
display(sum);

return 0;
}

Slip 20

Q.1) Write a C program to sort an array using insertion sort method..


#include <stdio.h>

// Function to perform insertion sort


void insertionSort(int array[], int size) {
for (int i = 1; i < size; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}

// Function to print the array


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

int main() {
int array[] = {12, 11, 13, 5, 6};
int size = sizeof(array) / sizeof(array[0]);

printf("Original array: \n");


printArray(array, size);

insertionSort(array, size);

printf("Sorted array: \n");


printArray(array, size);

return 0;
}

Q2. Write a C program to evaluate a postfix expression


#include <stdio.h>
#include <ctype.h>
#define MAX 100

int stack[MAX];
int top = -1;

void push(int value) {


stack[++top] = value;
}

int pop() {
return stack[top--];
}

int evaluatePostfix(char* expr) {


for (int i = 0; expr[i] != '\0'; i++) {
if (isdigit(expr[i])) {
push(expr[i] - '0'); // Convert char to int
} else {
int val2 = pop();
int val1 = pop();
switch (expr[i]) {
case '+': push(val1 + val2); break;
case '-': push(val1 - val2); break;
case '*': push(val1 * val2); break;
case '/': push(val1 / val2); break;
}
}
}
return pop();
}

int main() {
char expr[] = "231*+9-"; // Example postfix expression: (2 + (3 * 1)) - 9
printf("Result: %d\n", evaluatePostfix(expr));
return 0;
}

You might also like