0% found this document useful (0 votes)
3 views53 pages

DSA Lab

The document outlines a series of programming tasks related to data structures and algorithms, including searching techniques, sorting algorithms, stack operations, and linked list manipulations. Each task is accompanied by example code in C, demonstrating how to implement the specified functionality. The tasks cover a range of concepts such as linear search, binary search, insertion sort, merge sort, selection sort, quick sort, and basic operations on stacks and queues.
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)
3 views53 pages

DSA Lab

The document outlines a series of programming tasks related to data structures and algorithms, including searching techniques, sorting algorithms, stack operations, and linked list manipulations. Each task is accompanied by example code in C, demonstrating how to implement the specified functionality. The tasks cover a range of concepts such as linear search, binary search, insertion sort, merge sort, selection sort, quick sort, and basic operations on stacks and queues.
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/ 53

PART A

1. Write an interactive program to search an element in the given linear array using linear and
binary searching technique.

2. Write a program to arrange numbers in ascending order using insertion sort.

3. Write a program to arrange numbers in ascending order using merge sort.

4. Write a program to arrange numbers in ascending order using selection sort.

5. Write a program to arrange numbers in ascending order using quick sort.

6. Write an interactive program to insert an element at the given position.

7. Write an interactive program to implement the following operations on stack.

8. Program to implement Tower of Hanoi problem.

PART B
1. Write program to evaluate a postfix expression.

2. Write a program to convert an expression from infix to prefix.

3. Write an interactive program to perform insertion and deletion operations in Linear Queue.

4. Write an interactive program to perform insertion and deletion operations in Circular


Queue.

5. Write a program to delete an item from the linked list.

6. Write an interactive program to implement stack operations using linked list.

7. Write an interactive program to perform insertion operation in linked list-at the beginning,
at the end and in-between.

8. Program to create a binary tree and also print the preordered values, inorder values,
postorder values.

9. Write a program to add two polynomials of one variable and_n degree and represent them
as linked list.
1. Write an interactive program to search an element in the given linear array using linear and binary searching
technique.

#include <stdio.h> // Includes standard input-output functions


#include <stdlib.h> // Includes standard library functions like exit()

// Function to perform linear search


int linearSearch(int arr[], int n, int key) {
// Loop through each element
for (int i = 0; i < n; i++) {
if (arr[i] == key) { // Check if current element matches key
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

// Function to perform binary search (array must be sorted)


int binarySearch(int arr[], int n, int key) {
int low = 0; // Starting index
int high = n - 1; // Ending index

while (low <= high) { // Repeat until low > high


int mid = (low + high) / 2; // Find middle index

if (arr[mid] == key) {
return mid; // If key found at mid
} else if (arr[mid] < key) {
low = mid + 1; // Search in right half
} else {
high = mid - 1; // Search in left half
}
}
return -1; // Return -1 if not found
}

int main() {
int arr[100], n, key, choice, result;

// Ask user for number of elements


printf("Enter the number of elements in array: ");
scanf("%d", &n); // Read the number of elements

// Ask user to enter the array elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Store each element in the array
}

// Ask for element to search


printf("Enter the element to search: ");
scanf("%d", &key); // Read the key to search for

// Ask user for choice of search method


printf("\nChoose Search Method:\n1. Linear Search\n2. Binary Search\n");
scanf("%d", &choice); // Read user choice

switch (choice) {
case 1:
result = linearSearch(arr, n, key); // Call linear search
if (result != -1)
printf("Element found at position %d (0-based index).\n", result);
else
printf("Element not found in the array.\n");
break;

case 2:
// Before binary search, make sure the array is sorted
// Simple bubble sort for sorting
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

result = binarySearch(arr, n, key); // Call binary search


if (result != -1)
printf("Element found at position %d (0-based index).\n", result);
else
printf("Element not found in the array.\n");
break;

default:
printf("Invalid choice! Please enter 1 or 2.\n"); // Handle invalid choice
}

return 0; // End of program


}
output
Enter the number of elements in array: 5
Enter 5 elements:
10 20 30 40 50
Enter the element to search: 30

Choose Search Method:


1. Linear Search
2. Binary Search
2
Element found at position 2 (0-based index).

2. Write a program to arrange numbers in ascending order using insertion sort.

#include <stdio.h> // Includes standard input-output functions

int main() {

int arr[100], n, i, j, key;


// Ask user how many numbers they want to sort

printf("Enter number of elements: ");


scanf("%d", &n); // Read the number of elements

// Ask user to input the elements

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

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

scanf("%d", &arr[i]); // Read and store each element in the array


}

// Insertion Sort starts here

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

key = arr[i]; // Take the current element as key

j = i - 1; // Start comparing with previous elements

// Move elements that are greater than key one position ahead

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j]; // Shift element to the right

j = j - 1; // Move to the previous element

arr[j + 1] = key; // Place the key in its correct position

// Display the sorted array

printf("Array in ascending order:\n");

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

printf("%d ", arr[i]); // Print each sorted element


}
printf("\n"); // Print a newline at the end

return 0; // End of program

}
output

Enter number of elements: 5

Enter 5 elements:

45 12 78 23 9

Array in ascending order:

9 12 23 45 78

3. Write a program to arrange numbers in ascending order using merge sort.


#include <stdio.h> // For input and output functions

// Function to merge two sorted subarrays


void merge(int arr[], int left, int mid, int right) {
int i, j, k;

// Calculate sizes of two subarrays


int n1 = mid - left + 1;
int n2 = right - mid;

// Create temporary arrays


int L[n1], R[n2];

// Copy data into temporary arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[left + i]; // Copy from left part

for (j = 0; j < n2; j++)


R[j] = arr[mid + 1 + j]; // Copy from right part

i = 0; // Initial index of first subarray


j = 0; // Initial index of second subarray
k = left; // Initial index of merged array

// Merge the temporary arrays back into arr[]


while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i]; // Take element from L[]
i++;
} else {
arr[k] = R[j]; // Take element from R[]
j++;
}
k++; // Move to next position in merged array
}

// Copy any remaining elements from L[]


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

// Copy any remaining elements from R[]


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

// Recursive function to divide the array and sort using merge


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

// Recursively sort first and second halves


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

// Merge the sorted halves


merge(arr, left, mid, right);
}
}
int main() {
int arr[100], n;

// Ask user for number of elements


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

// Ask user to enter the elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read each element
}

// Call mergeSort to sort the array


mergeSort(arr, 0, n - 1);

// Print the sorted array


printf("Array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Print each element
}
printf("\n"); // Newline for clean output

return 0; // End of program


}

Output
Enter number of elements: 6
Enter 6 elements:
45 12 9 67 34 23
Array in ascending order:
9 12 23 34 45 67

4. Write a program to arrange numbers in ascending order using selection sort.


#include <stdio.h> // Includes input-output functions

int main() {
int arr[100], n, i, j, minIndex, temp;

// Ask user for number of elements


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

// Ask user to enter array elements


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Store each element in the array
}

// Selection Sort begins


for (i = 0; i < n - 1; i++) {
minIndex = i; // Assume the current index has the minimum value

// Find the index of the minimum element in the remaining array


for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update minIndex if a smaller element is found
}
}

// Swap the found minimum element with the first unsorted element
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

// Display the sorted array


printf("Array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]); // Print each sorted element
}
printf("\n"); // Print newline at the end

return 0; // End of program


}

Output
Enter number of elements: 5
Enter 5 elements:
23 45 12 9 34
Array in ascending order:
9 12 23 34 45

5. Write a program to arrange numbers in ascending order using quick sort.


#include <stdio.h> // For input and output functions

// Function to swap two elements


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

// Partition function to place pivot at correct position


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

// Rearranging elements around the pivot


for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++; // Move the boundary of smaller elements
swap(&arr[i], &arr[j]); // Swap if element is smaller than pivot
}
}
// Place the pivot after the last smaller element
swap(&arr[i + 1], &arr[high]);

return i + 1; // Return the pivot position


}

// Quick Sort function (recursive)


void quickSort(int arr[], int low, int high) {
if (low < high) {
// Find pivot position
int pi = partition(arr, low, high);

// Recursively sort elements before and after pivot


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[100], n;

// Ask user for number of elements


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

// Ask user to input the array elements


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Store each element
}

// Call quickSort function


quickSort(arr, 0, n - 1);

// Display the sorted array


printf("Array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Print each sorted element
}
printf("\n"); // Newline for clean output

return 0; // End of program


}

Output
Enter number of elements: 6
Enter 6 elements:
30 12 45 22 5 9
Array in ascending order:
5 9 12 22 30 45

6. Write an interactive program to insert an element at the given position.


#include <stdio.h> // For input-output functions

int main() {
int arr[100]; // Array with maximum size 100
int n, i, pos, value;

// Ask the user for the number of elements


printf("Enter number of elements: ");
scanf("%d", &n); // Read total number of elements

// Ask user to input the elements


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read and store each element
}

// Ask for position where the new element should be inserted


printf("Enter the position to insert the element (1 to %d): ", n + 1);
scanf("%d", &pos); // Read the position

// Validate position
if (pos < 1 || pos > n + 1) {
printf("Invalid position!\n");
return 1; // Exit the program with error
}

// Ask for the new element to insert


printf("Enter the value to insert: ");
scanf("%d", &value); // Read the new value

// Shift elements to the right to make space for the new element
for (i = n; i >= pos; i--) {
arr[i] = arr[i - 1];
}

// Insert the new value at the given position


arr[pos - 1] = value;

// Increase the size of the array


n++;

// Display the updated array


printf("Array after insertion:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]); // Print each element
}
printf("\n"); // Print newline for clean output

return 0; // End of program


}

Output
Enter number of elements: 4
Enter 4 elements:
10 20 30 40
Enter the position to insert the element (1 to 5): 3
Enter the value to insert: 25
Array after insertion:
10 20 25 30 40
7. Write an interactive program to implement the following operations on stack.
#include <stdio.h> // For standard input and output
#define SIZE 100 // Define maximum size of stack

int stack[SIZE]; // Stack array


int top = -1; // Initialize top as -1 (stack is empty)

// Function to push an element into the stack


void push() {
int value;
if (top == SIZE - 1) {
printf("Stack Overflow! Cannot insert more elements.\n");
} else {
printf("Enter value to push: ");
scanf("%d", &value);
top++; // Increase top index
stack[top] = value; // Insert value at top
printf("%d pushed to stack.\n", value);
}
}

// Function to pop (remove) the top element from the stack


void pop() {
if (top == -1) {
printf("Stack Underflow! No elements to pop.\n");
} else {
printf("%d popped from stack.\n", stack[top]);
top--; // Decrease top index
}
}

// Function to view the top element


void peek() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Top element is: %d\n", stack[top]);
}
}

// Function to display all elements in the stack


void display() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Stack elements (top to bottom):\n");
for (int i = top; i >= 0; i--) {
printf("%d\n", stack[i]); // Print from top to bottom
}
}
}

// Main function for interactive menu


int main() {
int choice;

while (1) { // Infinite loop for menu until user exits


// Menu options
printf("\n----- Stack Operations Menu -----\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Read user choice

switch (choice) {
case 1:
push(); // Call push function
break;
case 2:
pop(); // Call pop function
break;
case 3:
peek(); // Call peek function
break;
case 4:
display(); // Call display function
break;
case 5:
printf("Exiting program.\n");
return 0; // Exit the program
default:
printf("Invalid choice! Please enter 1 to 5.\n");
}
}

return 0; // Program never reaches here due to return in case 5


}
Output
----- Stack Operations Menu -----
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack.

Enter your choice: 1


Enter value to push: 20
20 pushed to stack.

Enter your choice: 4


Stack elements (top to bottom):
20
10
8. Program to implement Tower of Hanoi problem.
#include <stdio.h> // For input and output

// Recursive function to solve Tower of Hanoi


void towerOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
// Base case: only one disk, move it directly
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}

// Step 1: Move n-1 disks from source to auxiliary


towerOfHanoi(n - 1, source, auxiliary, destination);

// Step 2: Move the nth (largest) disk from source to destination


printf("Move disk %d from %c to %c\n", n, source, destination);

// Step 3: Move the n-1 disks from auxiliary to destination


towerOfHanoi(n - 1, auxiliary, destination, source);
}

int main() {
int n;

// Ask user how many disks


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

// Call the function with source='A', destination='C', auxiliary='B'


printf("\nSteps to solve Tower of Hanoi:\n");
towerOfHanoi(n, 'A', 'C', 'B');

return 0; // End of program


}

Output
Enter the number of disks: 3
Steps to solve Tower of Hanoi:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

1. Write program to evaluate a postfix expression.


#include <stdio.h> // For input-output
#include <ctype.h> // For checking if a character is a digit
#include <stdlib.h> // For atoi() and exit()

#define SIZE 100 // Max size of the stack

int stack[SIZE]; // Stack to store operands


int top = -1; // Initialize top of stack as -1

// Function to push a value onto the stack


void push(int value) {
if (top == SIZE - 1) {
printf("Stack Overflow!\n");
exit(1); // Exit if stack is full
} else {
top++;
stack[top] = value;
}
}

// Function to pop a value from the stack


int pop() {
if (top == -1) {
printf("Stack Underflow!\n");
exit(1); // Exit if stack is empty
} else {
return stack[top--];
}
}

// Function to evaluate a postfix expression


int evaluatePostfix(char* exp) {
int i;
int operand1, operand2, result;

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


char ch = exp[i];

// If character is a digit, convert to integer and push


if (isdigit(ch)) {
push(ch - '0'); // Convert character to number (e.g. '5' to 5)
} else {
// It's an operator: pop two operands
operand2 = pop();
operand1 = pop();

// Apply the operator


switch (ch) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
default:
printf("Invalid operator: %c\n", ch);
exit(1);
}

// Push result back to stack


push(result);
}
}

// Final result will be at the top of the stack


return pop();
}

int main() {
char expression[100];

// Ask user to enter postfix expression


printf("Enter a postfix expression (e.g. 53+62-*): ");
scanf("%s", expression); // Read the expression

// Call function to evaluate


int result = evaluatePostfix(expression);

// Print the result


printf("Result = %d\n", result);

return 0;
}

Output
Enter a postfix expression (e.g. 53+62-*): 53+62-*
Result = 10

2. Write a program to convert an expression from infix to prefix.


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

#define SIZE 100

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

// Push element onto stack


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

// Pop element from stack


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

// Peek top of the stack


char peek() {
return stack[top];
}

// Check if character is an operator


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

// Return precedence of operators


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

// Reverse a string
void reverse(char* exp) {
int len = strlen(exp);
for (int i = 0; i < len / 2; i++) {
char temp = exp[i];
exp[i] = exp[len - i - 1];
exp[len - i - 1] = temp;
}
}

// Swap brackets (used when reversing)


void swapBrackets(char* exp) {
for (int i = 0; exp[i]; i++) {
if (exp[i] == '(')
exp[i] = ')';
else if (exp[i] == ')')
exp[i] = '(';
}
}

// Convert infix to postfix


void infixToPostfix(char* infix, char* postfix) {
int i, j = 0;
char ch;

for (i = 0; infix[i]; i++) {


ch = infix[i];

if (isalnum(ch)) {
postfix[j++] = ch; // Operand goes to output
}
else if (ch == '(') {
push(ch); // Push opening bracket
}
else if (ch == ')') {
while (top != -1 && peek() != '(') {
postfix[j++] = pop(); // Pop until '('
}
pop(); // Remove '('
}
else if (isOperator(ch)) {
while (top != -1 && precedence(peek()) >= precedence(ch)) {
postfix[j++] = pop(); // Pop operators with higher/equal precedence
}
push(ch); // Push current operator
}
}

// Pop remaining operators


while (top != -1) {
postfix[j++] = pop();
}

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


}

// Main function to convert infix to prefix


int main() {
char infix[SIZE], reversed[SIZE], postfix[SIZE], prefix[SIZE];

// Ask user for infix expression


printf("Enter an infix expression: ");
scanf("%s", infix);

// Step 1: Reverse infix


strcpy(reversed, infix);
reverse(reversed);

// Step 2: Swap brackets


swapBrackets(reversed);

// Step 3: Convert reversed infix to postfix


infixToPostfix(reversed, postfix);

// Step 4: Reverse postfix to get prefix


strcpy(prefix, postfix);
reverse(prefix);

printf("Prefix expression: %s\n", prefix);

return 0;
}

Output
Enter an infix expression: (A+B)*C
Prefix expression: *+ABC
3. Write an interactive program to perform insertion and deletion operations in Linear Queue.
#include <stdio.h> // For input and output

#define SIZE 100 // Max size of the queue

int queue[SIZE]; // Array to store queue elements


int front = -1; // Index of the front element
int rear = -1; // Index of the rear element

// Function to insert an element (Enqueue)


void enqueue() {
int value;
if (rear == SIZE - 1) {
// Queue is full
printf("Queue Overflow! Cannot insert more elements.\n");
} else {
printf("Enter value to insert: ");
scanf("%d", &value);
if (front == -1)
front = 0; // First element to insert
rear++;
queue[rear] = value;
printf("%d inserted into the queue.\n", value);
}
}

// Function to delete an element (Dequeue)


void dequeue() {
if (front == -1 || front > rear) {
// Queue is empty
printf("Queue Underflow! No elements to delete.\n");
} else {
printf("%d deleted from the queue.\n", queue[front]);
front++;
}
}
// Function to display all elements
void display() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
} else {
printf("Queue elements: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}

// Main function for interactive menu


int main() {
int choice;

while (1) {
// Display menu
printf("\n--- Linear Queue Operations Menu ---\n");
printf("1. Insert (Enqueue)\n");
printf("2. Delete (Dequeue)\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

// Handle choices
switch (choice) {
case 1:
enqueue(); // Call insert function
break;
case 2:
dequeue(); // Call delete function
break;
case 3:
display(); // Call display function
break;
case 4:
printf("Exiting program.\n");
return 0; // Exit program
default:
printf("Invalid choice! Please enter 1 to 4.\n");
}
}

return 0; // Not needed but good practice


}

Output
--- Linear Queue Operations Menu ---
1. Insert (Enqueue)
2. Delete (Dequeue)
3. Display
4. Exit
Enter your choice: 1
Enter value to insert: 10
10 inserted into the queue.

Enter your choice: 1


Enter value to insert: 20
20 inserted into the queue.

Enter your choice: 3


Queue elements: 10 20

Enter your choice: 2


10 deleted from the queue.

Enter your choice: 3


Queue elements: 20
4. Write an interactive program to perform insertion and deletion operations in Circular Queue.
#include <stdio.h> // For input-output

#define SIZE 5 // Size of the circular queue

int queue[SIZE]; // Array to store queue elements


int front = -1; // Front points to the front of the queue
int rear = -1; // Rear points to the last element of the queue

// Function to insert an element into circular queue


void enqueue() {
int value;

// Check if the queue is full


if ((front == 0 && rear == SIZE - 1) || (rear + 1 == front)) {
printf("Queue Overflow! Cannot insert more elements.\n");
} else {
printf("Enter value to insert: ");
scanf("%d", &value);

// First insertion
if (front == -1) {
front = rear = 0;
}
// Wrap around
else if (rear == SIZE - 1 && front != 0) {
rear = 0;
}
else {
rear++;
}

queue[rear] = value;
printf("%d inserted into the queue.\n", value);
}
}
// Function to delete an element from circular queue
void dequeue() {
// Check if the queue is empty
if (front == -1) {
printf("Queue Underflow! No elements to delete.\n");
} else {
printf("%d deleted from the queue.\n", queue[front]);

// Only one element was present


if (front == rear) {
front = rear = -1;
}
// Wrap around
else if (front == SIZE - 1) {
front = 0;
}
else {
front++;
}
}
}

// Function to display the circular queue


void display() {
if (front == -1) {
printf("Queue is empty.\n");
return;
}

printf("Queue elements: ");


if (rear >= front) {
// Print from front to rear
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
} else {
// Queue is wrapped around
for (int i = front; i < SIZE; i++)
printf("%d ", queue[i]);
for (int i = 0; i <= rear; i++)
printf("%d ", queue[i]);
}
printf("\n");
}

// Main function with menu


int main() {
int choice;

while (1) {
// Display menu
printf("\n--- Circular Queue Menu ---\n");
printf("1. Insert (Enqueue)\n");
printf("2. Delete (Dequeue)\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

// Switch case to handle menu


switch (choice) {
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4:
printf("Exiting program.\n");
return 0;
default:
printf("Invalid choice! Enter between 1 to 4.\n");
}
}

return 0;
}
Output
#include <stdio.h> // For input-output

#define SIZE 5 // Size of the circular queue

int queue[SIZE]; // Array to store queue elements


int front = -1; // Front points to the front of the queue
int rear = -1; // Rear points to the last element of the queue

// Function to insert an element into circular queue


void enqueue() {
int value;

// Check if the queue is full


if ((front == 0 && rear == SIZE - 1) || (rear + 1 == front)) {
printf("Queue Overflow! Cannot insert more elements.\n");
} else {
printf("Enter value to insert: ");
scanf("%d", &value);

// First insertion
if (front == -1) {
front = rear = 0;
}
// Wrap around
else if (rear == SIZE - 1 && front != 0) {
rear = 0;
}
else {
rear++;
}

queue[rear] = value;
printf("%d inserted into the queue.\n", value);
}
}
// Function to delete an element from circular queue
void dequeue() {
// Check if the queue is empty
if (front == -1) {
printf("Queue Underflow! No elements to delete.\n");
} else {
printf("%d deleted from the queue.\n", queue[front]);

// Only one element was present


if (front == rear) {
front = rear = -1;
}
// Wrap around
else if (front == SIZE - 1) {
front = 0;
}
else {
front++;
}
}
}

// Function to display the circular queue


void display() {
if (front == -1) {
printf("Queue is empty.\n");
return;
}

printf("Queue elements: ");


if (rear >= front) {
// Print from front to rear
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
} else {
// Queue is wrapped around
for (int i = front; i < SIZE; i++)
printf("%d ", queue[i]);
for (int i = 0; i <= rear; i++)
printf("%d ", queue[i]);
}
printf("\n");
}

// Main function with menu


int main() {
int choice;

while (1) {
// Display menu
printf("\n--- Circular Queue Menu ---\n");
printf("1. Insert (Enqueue)\n");
printf("2. Delete (Dequeue)\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

// Switch case to handle menu


switch (choice) {
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4:
printf("Exiting program.\n");
return 0;
default:
printf("Invalid choice! Enter between 1 to 4.\n");
}
}

return 0;
}
5. Write a program to delete an item from the linked list.
#include <stdio.h> // For input/output
#include <stdlib.h> // For malloc() and free()

// Define structure for a node


struct Node {
int data; // Stores the data
struct Node* next; // Pointer to the next node
};

struct Node* head = NULL; // Start of the linked list (global pointer)

// Function to insert element at the end of the list


void insert(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Create new node
newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
head = newNode; // First node
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next; // Traverse to last node
}
temp->next = newNode; // Add new node at the end
}
}

// Function to delete a node with a given value


void deleteNode(int value) {
struct Node *temp = head, *prev = NULL;

// If list is empty
if (head == NULL) {
printf("List is empty. Nothing to delete.\n");
return;
}

// If head node itself holds the value


if (head->data == value) {
head = head->next; // Move head to next node
free(temp); // Free memory
printf("Node with value %d deleted.\n", value);
return;
}

// Search for the node to delete


while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}

// If value was not found


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

// Remove the node


prev->next = temp->next;
free(temp); // Free memory
printf("Node with value %d deleted.\n", value);
}

// Function to display the list


void display() {
struct Node* temp = head;

if (temp == NULL) {
printf("List is empty.\n");
return;
}
printf("Linked List: ");
while (temp != NULL) {
printf("%d -> ", temp->data); // Print data
temp = temp->next; // Move to next node
}
printf("NULL\n");
}

// Main menu-driven function


int main() {
int choice, value;

while (1) {
printf("\n--- Linked List Menu ---\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Read user input

switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insert(value);
break;

case 2:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(value);
break;

case 3:
display();
break;
case 4:
printf("Exiting program.\n");
return 0;

default:
printf("Invalid choice! Enter 1-4.\n");
}
}

return 0;
}

Output
--- Linked List Menu ---
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter value to insert: 10

Enter your choice: 1


Enter value to insert: 20

Enter your choice: 3


Linked List: 10 -> 20 -> NULL

Enter your choice: 2


Enter value to delete: 10
Node with value 10 deleted.

Enter your choice: 3


Linked List: 20 -> NULL
6. Write an interactive program to implement stack operations using linked list.

#include <stdio.h> // Standard input-output header


#include <stdlib.h> // For dynamic memory allocation (malloc) and exit()

// Define the structure of a node in the stack


struct Node {
int data; // Data part of node
struct Node* next; // Pointer to the next node
};

// Declare top as a global pointer to manage stack


struct Node* top = NULL;

// Function to push an element onto the stack


void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for new node
newNode->data = value; // Assign value to data field
newNode->next = top; // Make next of new node point to current top
top = newNode; // Update top to point to new node
printf("%d pushed to stack\n", value); // Print confirmation
}

// Function to pop (remove) element from the top of the stack


void pop() {
if (top == NULL) { // Check if stack is empty
printf("Stack Underflow! Cannot pop.\n"); // Error message
return; // Exit function
}
struct Node* temp = top; // Temporary pointer to current top
printf("%d popped from stack\n", top->data); // Print popped element
top = top->next; // Move top to next node
free(temp); // Free memory of popped node
}

// Function to display all elements in the stack


void display() {
if (top == NULL) { // Check if stack is empty
printf("Stack is empty.\n");
return;
}
struct Node* temp = top; // Temporary pointer to traverse stack
printf("Stack elements are: ");
while (temp != NULL) { // Loop through the stack
printf("%d ", temp->data); // Print each element
temp = temp->next; // Move to next node
}
printf("\n");
}

// Main function for menu-driven interface


int main() {
int choice, value; // Declare variables

while (1) { // Infinite loop until user exits


printf("\n--- Stack Menu ---\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n"); // Menu options
printf("Enter your choice: ");
scanf("%d", &choice); // Take user's choice

switch (choice) {
case 1: // If user chooses Push
printf("Enter value to push: ");
scanf("%d", &value);
push(value); // Call push function
break;
case 2: // If user chooses Pop
pop(); // Call pop function
break;
case 3: // If user chooses Display
display(); // Call display function
break;
case 4: // Exit the program
exit(0);
default: // Handle invalid input
printf("Invalid choice! Try again.\n");
}
}

return 0; // End of program


}

Output
--- Stack Menu ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 50
50 pushed to stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 30
30 pushed to stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements are: 30 50

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
30 popped from stack

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements are: 50

--- Stack Menu ---


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4

7. Write an interactive program to perform insertion operation in linked list-at the beginning, at the end and in-
between.
#include <stdio.h> // For input-output functions
#include <stdlib.h> // For malloc() and exit()

// Define structure for a node in the linked list


struct Node {
int data; // Stores data
struct Node* next; // Points to the next node
};

// Head pointer to keep track of the beginning of the list


struct Node* head = NULL;

// Function to insert a new node at the beginning


void insertAtBeginning(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for new node
newNode->data = value; // Assign the data to the new node
newNode->next = head; // Point new node's next to current head
head = newNode; // Update head to point to the new node
printf("%d inserted at the beginning.\n", value); // Print confirmation
}

// Function to insert a new node at the end


void insertAtEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
newNode->data = value; // Set data
newNode->next = NULL; // Set next as NULL since it will be the last node

if (head == NULL) { // If list is empty


head = newNode; // Make new node the head
} else {
struct Node* temp = head; // Temp pointer to traverse the list
while (temp->next != NULL) {
temp = temp->next; // Go to the last node
}
temp->next = newNode; // Add new node at the end
}
printf("%d inserted at the end.\n", value); // Print confirmation
}

// Function to insert at a specific position (1-based index)


void insertAtPosition(int value, int position) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Create new node
newNode->data = value; // Set data

if (position == 1) { // If inserting at the first position


newNode->next = head;
head = newNode;
printf("%d inserted at position %d.\n", value, position);
return;
}
struct Node* temp = head;
for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next; // Move to node before the desired position
}

if (temp == NULL) { // If position is invalid (too far)


printf("Invalid position!\n");
free(newNode); // Free memory of unused node
return;
}

newNode->next = temp->next; // Connect new node to next node


temp->next = newNode; // Link previous node to new node
printf("%d inserted at position %d.\n", value, position);
}

// Function to display the entire list


void displayList() {
if (head == NULL) {
printf("List is empty.\n"); // No elements
return;
}

struct Node* temp = head; // Temporary pointer to traverse


printf("Linked list: ");
while (temp != NULL) {
printf("%d -> ", temp->data); // Print data of each node
temp = temp->next; // Move to next node
}
printf("NULL\n"); // Indicate end of list
}

// Main function to interact with the user


int main() {
int choice, value, position;

while (1) {
// Show the menu
printf("\n--- Linked List Insertion Menu ---\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Insert at Position\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Read user's choice

switch (choice) {
case 1:
printf("Enter value to insert at beginning: ");
scanf("%d", &value);
insertAtBeginning(value); // Call function
break;
case 2:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(value); // Call function
break;
case 3:
printf("Enter value and position to insert: ");
scanf("%d %d", &value, &position);
insertAtPosition(value, position); // Call function
break;
case 4:
displayList(); // Show current list
break;
case 5:
exit(0); // Exit program
default:
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

Output
#include <stdio.h> // For input-output functions
#include <stdlib.h> // For malloc() and exit()

// Define structure for a node in the linked list


struct Node {
int data; // Stores data
struct Node* next; // Points to the next node
};

// Head pointer to keep track of the beginning of the list


struct Node* head = NULL;

// Function to insert a new node at the beginning


void insertAtBeginning(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for new node
newNode->data = value; // Assign the data to the new node
newNode->next = head; // Point new node's next to current head
head = newNode; // Update head to point to the new node
printf("%d inserted at the beginning.\n", value); // Print confirmation
}

// Function to insert a new node at the end


void insertAtEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
newNode->data = value; // Set data
newNode->next = NULL; // Set next as NULL since it will be the last node

if (head == NULL) { // If list is empty


head = newNode; // Make new node the head
} else {
struct Node* temp = head; // Temp pointer to traverse the list
while (temp->next != NULL) {
temp = temp->next; // Go to the last node
}
temp->next = newNode; // Add new node at the end
}
printf("%d inserted at the end.\n", value); // Print confirmation
}

// Function to insert at a specific position (1-based index)


void insertAtPosition(int value, int position) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Create new node
newNode->data = value; // Set data

if (position == 1) { // If inserting at the first position


newNode->next = head;
head = newNode;
printf("%d inserted at position %d.\n", value, position);
return;
}

struct Node* temp = head;


for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next; // Move to node before the desired position
}

if (temp == NULL) { // If position is invalid (too far)


printf("Invalid position!\n");
free(newNode); // Free memory of unused node
return;
}

newNode->next = temp->next; // Connect new node to next node


temp->next = newNode; // Link previous node to new node
printf("%d inserted at position %d.\n", value, position);
}

// Function to display the entire list


void displayList() {
if (head == NULL) {
printf("List is empty.\n"); // No elements
return;
}

struct Node* temp = head; // Temporary pointer to traverse


printf("Linked list: ");
while (temp != NULL) {
printf("%d -> ", temp->data); // Print data of each node
temp = temp->next; // Move to next node
}
printf("NULL\n"); // Indicate end of list
}

// Main function to interact with the user


int main() {
int choice, value, position;

while (1) {
// Show the menu
printf("\n--- Linked List Insertion Menu ---\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Insert at Position\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Read user's choice

switch (choice) {
case 1:
printf("Enter value to insert at beginning: ");
scanf("%d", &value);
insertAtBeginning(value); // Call function
break;
case 2:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(value); // Call function
break;
case 3:
printf("Enter value and position to insert: ");
scanf("%d %d", &value, &position);
insertAtPosition(value, position); // Call function
break;
case 4:
displayList(); // Show current list
break;
case 5:
exit(0); // Exit program
default:
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

8. Program to create a binary tree and also print the preordered values, inorder values,
postorder values.
#include <stdio.h>
#include <stdlib.h>

// Define structure for a tree node


struct Node {
int data; // Value stored in node
struct Node* left; // Pointer to left child
struct Node* right; // Pointer to right child
};

// Function to create a new node with given data


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
newNode->data = value; // Assign data
newNode->left = NULL; // Initialize left child to NULL
newNode->right = NULL; // Initialize right child to NULL
return newNode; // Return pointer to new node
}

// Function to create binary tree interactively


struct Node* createTree() {
int value;
printf("Enter data (-1 for no node): ");
scanf("%d", &value); // Read input value

if (value == -1) {
return NULL; // No node created
}

struct Node* root = createNode(value); // Create root node


printf("Enter left child of %d:\n", value);
root->left = createTree(); // Recursively create left subtree

printf("Enter right child of %d:\n", value);


root->right = createTree(); // Recursively create right subtree

return root; // Return root node


}

// Inorder traversal: Left -> Root -> Right


void inorder(struct Node* root) {
if (root == NULL) return; // Base case
inorder(root->left); // Traverse left subtree
printf("%d ", root->data); // Print root
inorder(root->right); // Traverse right subtree
}

// Preorder traversal: Root -> Left -> Right


void preorder(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data); // Print root
preorder(root->left); // Traverse left
preorder(root->right); // Traverse right
}

// Postorder traversal: Left -> Right -> Root


void postorder(struct Node* root) {
if (root == NULL) return;
postorder(root->left); // Traverse left
postorder(root->right); // Traverse right
printf("%d ", root->data); // Print root
}

// Main function
int main() {
struct Node* root = NULL; // Declare root pointer

printf("Create the binary tree\n");


root = createTree(); // Call function to create tree

printf("\nInorder Traversal: ");


inorder(root); // Print inorder traversal

printf("\nPreorder Traversal: ");


preorder(root); // Print preorder traversal

printf("\nPostorder Traversal: ");


postorder(root); // Print postorder traversal

printf("\n");
return 0;
}

Output
Create the binary tree
Enter data (-1 for no node): 10
Enter left child of 10:
Enter data (-1 for no node): 20
Enter left child of 20:
Enter data (-1 for no node): -1
Enter right child of 20:
Enter data (-1 for no node): -1
Enter right child of 10:
Enter data (-1 for no node): 30
Enter left child of 30:
Enter data (-1 for no node): -1
Enter right child of 30:
Enter data (-1 for no node): -1

Inorder Traversal: 20 10 30
Preorder Traversal: 10 20 30
Postorder Traversal: 20 30 10

9. Write a program to add two polynomials of one variable and_n degree and represent them as linked list.
#include <stdio.h>
#include <stdlib.h>

// Define structure for polynomial term node


struct Node {
int coeff; // Coefficient of term
int power; // Power of x
struct Node* next; // Pointer to next term
};

// Function to create a new node


struct Node* createNode(int coeff, int power) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
newNode->coeff = coeff; // Set coefficient
newNode->power = power; // Set exponent
newNode->next = NULL; // Initialize next to NULL
return newNode;
}

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


void insertTerm(struct Node** poly, int coeff, int power) {
struct Node* newNode = createNode(coeff, power); // Create a new node
if (*poly == NULL) {
*poly = newNode; // If list is empty, make newNode the head
} else {
struct Node* temp = *poly;
while (temp->next != NULL) {
temp = temp->next; // Traverse to the end
}
temp->next = newNode; // Link the last node to new node
}
}

// Function to display a polynomial


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

// Function to add two polynomials


struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {
struct Node* result = NULL; // Resultant polynomial
while (poly1 != NULL && poly2 != NULL) {
if (poly1->power > poly2->power) {
insertTerm(&result, poly1->coeff, poly1->power); // Add term from poly1
poly1 = poly1->next;
} else if (poly1->power < poly2->power) {
insertTerm(&result, poly2->coeff, poly2->power); // Add term from poly2
poly2 = poly2->next;
} else {
int sum = poly1->coeff + poly2->coeff; // Add coefficients
if (sum != 0) {
insertTerm(&result, sum, poly1->power);
}
poly1 = poly1->next;
poly2 = poly2->next;
}
}

// Append remaining terms


while (poly1 != NULL) {
insertTerm(&result, poly1->coeff, poly1->power);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insertTerm(&result, poly2->coeff, poly2->power);
poly2 = poly2->next;
}

return result;
}

// Main function
int main() {
struct Node* poly1 = NULL;
struct Node* poly2 = NULL;
struct Node* sum = NULL;
int n, coeff, power;

// Input first polynomial


printf("Enter number of terms in first polynomial: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter coefficient and power for term %d: ", i + 1);
scanf("%d %d", &coeff, &power);
insertTerm(&poly1, coeff, power); // Insert term into poly1
}

// Input second polynomial


printf("Enter number of terms in second polynomial: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter coefficient and power for term %d: ", i + 1);
scanf("%d %d", &coeff, &power);
insertTerm(&poly2, coeff, power); // Insert term into poly2
}

// Add the two polynomials


sum = addPolynomials(poly1, poly2);

// Display results
printf("\nFirst Polynomial: ");
display(poly1);

printf("Second Polynomial: ");


display(poly2);

printf("Sum of Polynomials: ");


display(sum);

return 0;
}

Output
Enter number of terms in first polynomial: 3
Enter coefficient and power for term 1: 3 2
Enter coefficient and power for term 2: 5 1
Enter coefficient and power for term 3: 6 0
Enter number of terms in second polynomial: 3
Enter coefficient and power for term 1: 2 2
Enter coefficient and power for term 2: 1 1
Enter coefficient and power for term 3: 4 0

First Polynomial: 3x^2 + 5x^1 + 6x^0


Second Polynomial: 2x^2 + 1x^1 + 4x^0
Sum of Polynomials: 5x^2 + 6x^1 + 10x^0

You might also like