0% found this document useful (0 votes)
4 views106 pages

Menu-Driven Array Operations

Raju pepsi 54

Uploaded by

AAYUSH
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)
4 views106 pages

Menu-Driven Array Operations

Raju pepsi 54

Uploaded by

AAYUSH
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

Program.

1: Write a menu driven program for insertion, deletion and traversal in a one-
dimensional Array.

#include <stdio.h>
#define MAX 5 // Maximum size of the array
void displayMenu() {
printf("\nMenu:\n");
printf("1. Insert Element\n");
printf("2. Delete Element\n");
printf("3. Traverse (Display) Array\n");
printf("4. Exit\n");
}
// Function to insert an element at a specified position
void insertElement(int arr[], int *size) {
if (*size == MAX) {
printf("Array is full, cannot insert more elements.\n");
return;
}
int element, position,i;
printf("Enter the element to insert: ");
scanf("%d", &element);
printf("Enter the position (0 to %d): ", *size);
scanf("%d", &position);

if (position < 0 || position > *size) {


printf("Invalid position!\n");
} else {
for ( i = *size; i > position; i--) {
arr[i] = arr[i - 1]; // Shift elements to the right
}
arr[position] = element;
(*size)++;
printf("Element %d inserted at position %d.\n", element, position);
}
}
// Function to delete an element from a specified position
void deleteElement(int arr[], int *size) {
int i;
if (*size == 0) {
printf("Array is empty, nothing to delete!\n");
return;
}
int position;
printf("Enter the position (0 to %d) of the element to delete: ", *size - 1);
scanf("%d", &position);
if (position < 0 || position >= *size) {
printf("Invalid position!\n");
} else {
int deleted_element = arr[position];
for ( i = position; i < *size - 1; i++) {
arr[i] = arr[i + 1]; // Shift elements to the left
}
(*size)--;
printf("Element %d at position %d deleted.\n", deleted_element, position);
}
}
// Function to traverse and display the array
void traverseArray(int arr[], int size) {
int i;
if (size == 0) {
printf("Array is empty!\n");
} else {
printf("Current Array: ");
for ( i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
}
int main() {
printf("Name: Gautam Garg \n Roll No. : 23049561");
int arr[MAX];
int size = 0;
int choice;

while (1) {
displayMenu();
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
insertElement(arr, &size);
break;
case 2:
deleteElement(arr, &size);
break;
case 3:
traverseArray(arr, size);
break;
case 4:
printf("Exiting the program.\n");
return 0;
default:
printf("Invalid choice! Please choose a valid option.\n");
} }
return 0;
}
Output:
Program.2: Write a menu driven program for insertion, deletion and traversal in a 2-
dimensional Array:

#include <stdio.h>

#define MAX_ROWS 100 // Maximum rows for the 2D array


#define MAX_COLS 100 // Maximum columns for the 2D array

int i; // Declare i outside of any loop

void displayMenu() {
printf("\nMenu:\n");
printf("1. Insert Element\n");
printf("2. Delete Element\n");
printf("3. Traverse (Display) Array\n");
printf("4. Exit\n");
}

// Function to insert an element in the array at a specified position


void insertElement(int arr[MAX_ROWS][MAX_COLS], int *rows, int *cols) {
int row, col, element;

if (*rows >= MAX_ROWS || *cols >= MAX_COLS) {


printf("Array is full, cannot insert more elements.\n");
return;
}

printf("Enter the row (0 to %d) to insert: ", *rows - 1);


scanf("%d", &row);
printf("Enter the column (0 to %d) to insert: ", *cols - 1);
scanf("%d", &col);

if (row < 0 || row >= *rows || col < 0 || col >= *cols) {
printf("Invalid position!\n");
} else {
printf("Enter the element to insert: ");
scanf("%d", &element);
arr[row][col] = element;
printf("Element %d inserted at position (%d, %d).\n", element, row, col);
}
}

// Function to delete an element from the specified position


void deleteElement(int arr[MAX_ROWS][MAX_COLS], int *rows, int *cols) {
int row, col;

if (*rows == 0 || *cols == 0) {
printf("Array is empty, nothing to delete!\n");
return;
}

printf("Enter the row (0 to %d) to delete: ", *rows - 1);


scanf("%d", &row);
printf("Enter the column (0 to %d) to delete: ", *cols - 1);
scanf("%d", &col);

if (row < 0 || row >= *rows || col < 0 || col >= *cols) {
printf("Invalid position!\n");
} else {
printf("Element %d at position (%d, %d) deleted.\n", arr[row][col], row, col);
arr[row][col] = 0; // Set the deleted element to 0 (or a sentinel value)
}
}

// Function to traverse and display the 2D array


void traverseArray(int arr[MAX_ROWS][MAX_COLS], int rows, int cols) {
int i,j;
if (rows == 0 || cols == 0) {
printf("Array is empty!\n");
} else {
printf("Current Array:\n");
for (i = 0; i < rows; i++) { // Use 'i' declared globally
for ( j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
}

int main() {
printf("Name: Gautam Garg \n Roll No. : 23049561\n");
int arr[MAX_ROWS][MAX_COLS] = {0}; // Initialize array elements to 0
int rows, cols;
int choice;

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


scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

if (rows > MAX_ROWS || cols > MAX_COLS) {


printf("Array dimensions exceed the limit!\n");
return 1;
}

while (1) {
displayMenu();
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
insertElement(arr, &rows, &cols);
break;
case 2:
deleteElement(arr, &rows, &cols);
break;
case 3:
traverseArray(arr, rows, cols);
break;
case 4:
printf("Exiting the program.\n");
return 0;
default:
printf("Invalid choice! Please choose a valid option.\n");
}
}

return 0;

}
Output:
Program 3 : Write a menu driven program for insertion, deletion and traversal in a names
(character) Array.
#include <stdio.h>
#include <string.h>

#define MAX 100 // Maximum number of names

// Function prototypes
void insert(char names[MAX][50], int *n);
void delete(char names[MAX][50], int *n);
void traverse(char names[MAX][50], int n);

int main() {
char names[MAX][50]; // Array to store names
int n = 0; // Current number of names
int choice;
printf("Name: Gautam Garg \nRoll No. : 23049561\n");
while (1) {
// Display the menu
printf("\nMenu:\n");
printf("1. Insert a name\n");
printf("2. Delete a name\n");
printf("3. Traverse names\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insert(names, &n);
break;
case 2:
delete(names, &n);
break;
case 3:
traverse(names, n);
break;
case 4:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice, please try again.\n");
}
}
return 0;
}
// Function to insert a name
void insert(char names[MAX][50], int *n) {
if (*n >= MAX) {
printf("Array is full, cannot insert more names.\n");
return;
}
printf("Enter the name to insert: ");
scanf("%s", names[*n]);
(*n)++;
printf("Name inserted successfully.\n");
}
// Function to delete a name
void delete(char names[MAX][50], int *n) {
if (*n == 0) {
printf("Array is empty, nothing to delete.\n");
return;
}
char delName[50];
printf("Enter the name to delete: ");
scanf("%s", delName);

int i, found = 0;
for (i = 0; i < *n; i++) {
if (strcmp(names[i], delName) == 0) {
found = 1;
break;
}
}
if (found) {
int j;
for ( j = i; j < *n - 1; j++) {
strcpy(names[j], names[j + 1]);
}
(*n)--;
printf("Name deleted successfully.\n");
} else {
printf("Name not found.\n");
}
}

// Function to traverse and display all names


void traverse(char names[MAX][50], int n) {
if (n == 0) {
printf("No names to display.\n");
return;
}
printf("Names in the array:\n");
int i;
for ( i = 0; i < n; i++) {
printf("%s\n", names[i]);
}
}
Output:
Program 4: Write a menu driven program for maximum and minimum element in 1D and 2D
Array.
#include <stdio.h>

// Function prototypes

void findMaxMin1D();

void findMaxMin2D();

int main() {

int choice;

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

while (1) {

// Display the menu

printf("\nMenu:\n");

printf("1. Find max and min in 1D array\n");

printf("2. Find max and min in 2D array\n");

printf("3. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

findMaxMin1D();

break;

case 2:

findMaxMin2D();

break;
case 3:

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

return 0;

default:

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

return 0;

// Function to find the maximum and minimum in a 1D array

void findMaxMin1D() {

int n;

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

scanf("%d", &n);

int arr[n];

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

int i;

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

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

int max = arr[0], min = arr[0];

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

if (arr[i] > max)

max = arr[i];
if (arr[i] < min)

min = arr[i];

printf("Maximum element in 1D array: %d\n", max);

printf("Minimum element in 1D array: %d\n", min);

// Function to find the maximum and minimum in a 2D array

void findMaxMin2D() {

int rows, cols;

printf("Enter the number of rows and columns in the 2D array: ");

scanf("%d %d", &rows, &cols);

int arr[rows][cols];

printf("Enter the elements of the 2D array (%d x %d):\n", rows, cols);

int i,j;

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

for ( j = 0; j < cols; j++) {

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

int max = arr[0][0], min = arr[0][0];

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

for ( j = 0; j < cols; j++) {

if (arr[i][j] > max)

max = arr[i][j];

if (arr[i][j] < min)


min = arr[i][j];

printf("Maximum element in 2D array: %d\n", max);

printf("Minimum element in 2D array: %d\n", min);

}
Output:
Program 5: Matrix Multiplication, addition and subtraction
#include <stdio.h>
// Function prototypes
void addMatrices(int rows, int cols, int matrix1[10][10], int matrix2[10][10], int result[10][10]);
void subtractMatrices(int rows, int cols, int matrix1[10][10], int matrix2[10][10], int result[10][10]);
void multiplyMatrices(int rows1, int cols1, int matrix1[10][10], int rows2, int cols2, int matrix2[10][10], int
result[10][10]);

int main() {
int choice, rows1, cols1, rows2, cols2;
int matrix1[10][10], matrix2[10][10], result[10][10];
int i,j;

// Custom print statement


printf("Name: Gautam Garg \nRoll No. : 23049561\n");

while (1) {
// Display the menu
printf("\nMenu:\n");
printf("1. Matrix Addition\n");
printf("2. Matrix Subtraction\n");
printf("3. Matrix Multiplication\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Matrix addition
printf("Enter the number of rows and columns for both matrices: ");
scanf("%d %d", &rows1, &cols1);

printf("Enter elements of the first matrix:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of the second matrix:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
scanf("%d", &matrix2[i][j]);
}
}

addMatrices(rows1, cols1, matrix1, matrix2, result);


printf("Result of Matrix Addition:\n");
for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
break;

case 2:
// Matrix subtraction
printf("Enter the number of rows and columns for both matrices: ");
scanf("%d %d", &rows1, &cols1);

printf("Enter elements of the first matrix:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of the second matrix:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
scanf("%d", &matrix2[i][j]);
}
}

subtractMatrices(rows1, cols1, matrix1, matrix2, result);

printf("Result of Matrix Subtraction:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
break;

case 3:
// Matrix multiplication
printf("Enter the number of rows and columns for the first matrix: ");
scanf("%d %d", &rows1, &cols1);

printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d %d", &rows2, &cols2);

if (cols1 != rows2) {
printf("Matrix multiplication is not possible with these dimensions.\n");
break;
}

printf("Enter elements of the first matrix:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of the second matrix:\n");


for ( i = 0; i < rows2; i++) {
for ( j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}

multiplyMatrices(rows1, cols1, matrix1, rows2, cols2, matrix2, result);

printf("Result of Matrix Multiplication:\n");


for ( i = 0; i < rows1; i++) {
for ( j = 0; j < cols2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
break;

case 4:
printf("Exiting...\n");
return 0;

default:
printf("Invalid choice, please try again.\n");
}
}

return 0;
}

// Function to add two matrices


void addMatrices(int rows, int cols, int matrix1[10][10], int matrix2[10][10], int result[10][10]) {
int i,j;
for ( i = 0; i < rows; i++) {
for ( j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
// Function to subtract two matrices
void subtractMatrices(int rows, int cols, int matrix1[10][10], int matrix2[10][10], int result[10][10]) {
int i,j;
for ( i = 0; i < rows; i++) {
for ( j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}

// Function to multiply two matrices


void multiplyMatrices(int rows1, int cols1, int matrix1[10][10], int rows2, int cols2, int matrix2[10][10], int
result[10][10]) {
int i,j,k;
for (i= 0; i < rows1; i++) {
for (j = 0; j < cols2; j++) {
result[i][j] = 0;
for ( k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
Output:
Program 6: Write a menu driven program to show working of a stack using Array
#include <stdio.h>
#include <stdlib.h>

#define MAX 10 // Maximum size of the stack

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

// Function prototypes
void push();
void pop();
void display();

int main() {
int choice;

// Custom print statement


printf("Name: Gautam Garg \nRoll No. : 23049561\n");

while (1) {
// Display the menu
printf("\nMenu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}
return 0;
}
// Function to push an element onto the stack
void push() {
int value;

if (top == MAX - 1) {
printf("Stack Overflow! Cannot push any more elements.\n");
} else {
printf("Enter the value to push: ");
scanf("%d", &value);
top++;
stack[top] = value;
printf("Value pushed onto the stack.\n");
}
}

// Function to pop an element from the stack


void pop() {
if (top == -1) {
printf("Stack Underflow! Cannot pop any element.\n");
} else {
printf("Popped value: %d\n", stack[top]);
top--;
}
}
// Function to display the stack
void display() {
int i;
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Stack elements:\n");
for ( i = top; i >= 0; i--) {
printf("%d\n", stack[i]);
}
}
}
Output:
Program 7: WAP to show working of stack using linked list
#include <stdio.h>

#include <stdlib.h>

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

struct Node {

int data;

struct Node* next;

};

// Function prototypes

void push(struct Node** top);

void pop(struct Node** top);

void display(struct Node* top);

int main() {

struct Node* top = NULL; // Initialize the stack as an empty linked list

int choice;

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

while (1) {

// Display the menu

printf("\nMenu:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Display\n");

printf("4. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {

case 1:

push(&top);

break;

case 2:

pop(&top);

break;

case 3:

display(top);

break;

case 4:

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

exit(0);

default:

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

return 0;

// Function to push an element onto the stack

void push(struct Node** top) {

int value;

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

if (newNode == NULL) {

printf("Memory allocation failed. Unable to push.\n");

return;

printf("Enter the value to push: ");


scanf("%d", &value);

newNode->data = value;

newNode->next = *top;

*top = newNode;

printf("Value pushed onto the stack.\n");

// Function to pop an element from the stack

void pop(struct Node** top) {

if (*top == NULL) {

printf("Stack Underflow! Cannot pop any element.\n");

} else {

struct Node* temp = *top;

printf("Popped value: %d\n", temp->data);

*top = (*top)->next;

free(temp);

// Function to display the stack

void display(struct Node* top) {

if (top == NULL) {

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

} else {

struct Node* temp = top;

printf("Stack elements:\n");

while (temp != NULL) {

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

temp = temp->next;

}
Output:
Program 8: WAP to implement infix to post fix conversion.
#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <string.h>

#define MAX 100 // Maximum size of the stack

// Stack structure

struct Stack {

int top;

char arr[MAX];

};

// Function prototypes

void push(struct Stack* stack, char op);

char pop(struct Stack* stack);

char peek(struct Stack* stack);

int isEmpty(struct Stack* stack);

int precedence(char op);

int isOperator(char symbol);

void infixToPostfix(char infix[], char postfix[]);

int main() {

char infix[MAX], postfix[MAX];

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get the infix expression from the user


printf("Enter infix expression: ");

gets(infix);

// Convert infix to postfix

infixToPostfix(infix, postfix);

// Display the postfix expression

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

return 0;

// Function to push an operator onto the stack

void push(struct Stack* stack, char op) {

if (stack->top == MAX - 1) {

printf("Stack Overflow!\n");

return;

stack->arr[++(stack->top)] = op;

// Function to pop an operator from the stack

char pop(struct Stack* stack) {

if (isEmpty(stack)) {

printf("Stack Underflow!\n");

return -1;

return stack->arr[(stack->top)--];

// Function to check the top of the stack

char peek(struct Stack* stack) {

return stack->arr[stack->top];

}
// Function to check if the stack is empty

int isEmpty(struct Stack* stack) {

return stack->top == -1;

// Function to get the precedence of an operator

int precedence(char op) {

switch (op) {

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

default:

return 0;

// Function to check if a character is an operator

int isOperator(char symbol) {

return symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' || symbol == '^';

// Function to convert an infix expression to postfix

void infixToPostfix(char infix[], char postfix[]) {

struct Stack stack;

[Link] = -1; // Initialize stack

int i = 0, j = 0;
while (infix[i] != '\0') {

char symbol = infix[i];

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

if (isalnum(symbol)) {

postfix[j++] = symbol;

// If the character is an opening parenthesis, push it onto the stack

else if (symbol == '(') {

push(&stack, symbol);

// If the character is a closing parenthesis, pop until '(' is found

else if (symbol == ')') {

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

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

pop(&stack); // Remove '(' from the stack

// If the character is an operator

else if (isOperator(symbol)) {

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

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

push(&stack, symbol);

i++;

}
// Pop the remaining operators from the stack

while (!isEmpty(&stack)) {

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

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

}
Output:
Program 9: WAP to implement post fix expression evaluation.
#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <math.h>

#define MAX 100

// Stack structure for evaluation

struct Stack {

int top;

int arr[MAX];

};

// Function prototypes

void push(struct Stack* stack, int value);

int pop(struct Stack* stack);

int evaluatePostfix(char* postfix);

int main() {

char postfix[MAX];

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get the postfix expression from the user

printf("Enter postfix expression: ");

gets(postfix);

// Evaluate the postfix expression


int result = evaluatePostfix(postfix);

// Display the result

printf("Result of postfix evaluation: %d\n", result);

return 0;

// Function to push a value onto the stack

void push(struct Stack* stack, int value) {

if (stack->top == MAX - 1) {

printf("Stack Overflow!\n");

return;

stack->arr[++(stack->top)] = value;

// Function to pop a value from the stack

int pop(struct Stack* stack) {

if (stack->top == -1) {

printf("Stack Underflow!\n");

exit(1);

return stack->arr[(stack->top)--];

// Function to evaluate a postfix expression

int evaluatePostfix(char* postfix) {

struct Stack stack;

[Link] = -1; // Initialize stack


int i = 0;

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

char symbol = postfix[i];

// If the character is an operand, push it onto the stack

if (isdigit(symbol)) {

push(&stack, symbol - '0'); // Convert char to int

// If the character is an operator, pop two operands and apply the operator

else {

int operand2 = pop(&stack);

int operand1 = pop(&stack);

switch (symbol) {

case '+':

push(&stack, operand1 + operand2);

break;

case '-':

push(&stack, operand1 - operand2);

break;

case '*':

push(&stack, operand1 * operand2);

break;

case '/':

if (operand2 == 0) {

printf("Division by zero error!\n");

exit(1);

push(&stack, operand1 / operand2);


break;

case '^':

push(&stack, pow(operand1, operand2));

break;

default:

printf("Invalid operator encountered: %c\n", symbol);

exit(1);

i++;

// The final result will be the only value left in the stack

return pop(&stack);

}
Output:
Program 10: WAP for recursive Tower of Hanoi.
#include <stdio.h>

// Recursive function to solve Tower of Hanoi

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {

if (n == 1) {

printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);

return;

towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);

towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

int main() {

int n; // Number of disks

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get the number of disks from the user

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

scanf("%d", &n);

// Call the Tower of Hanoi function

towerOfHanoi(n, 'A', 'C', 'B'); // A, B, and C are the names of the rods

return 0;

}
Output:
Program 11: WAP for recursive factorial.
#include <stdio.h>

// Recursive function to calculate factorial

int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

int main() {

int num;

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get the number from the user

printf("Enter a number: ");

scanf("%d", &num);

// Calculate factorial using recursion

int result = factorial(num);

// Display the result

printf("Factorial of %d is %d\n", num, result);

return 0;

}
Output:
Program 12: WAP for recursive Fibonacci series
#include <stdio.h>

// Recursive function to find the nth Fibonacci number

int fibonacci(int n) {

if (n == 0) {

return 0;

} else if (n == 1) {

return 1;

} else {

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int n;

// Custom print statement

printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get the number of terms for Fibonacci series

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

scanf("%d", &n);

// Display the Fibonacci series

printf("Fibonacci series: ");

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

printf("%d ", fibonacci(i));

printf("\n");

return 0;

}
Output:
Program 13: WAP to implement search in array: find 1st occurrence, only 2nd
occurrence, first two occurrence and last occurrence of the number.
#include <stdio.h>

#define MAX 100

// Function prototypes
int findFirstOccurrence(int arr[], int size, int num);
int findSecondOccurrence(int arr[], int size, int num);
void findFirstTwoOccurrences(int arr[], int size, int num);
int findLastOccurrence(int arr[], int size, int num);

int main() {
int arr[MAX], size, num, choice;

// Custom print statement


printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Get array size and elements from the user


printf("Enter the size of the array: ");
scanf("%d", &size);

printf("Enter the elements of the array:\n");


for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Get the number to search for


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

while (1) {
// Display the menu
printf("\nMenu:\n");
printf("1. Find first occurrence\n");
printf("2. Find second occurrence\n");
printf("3. Find first two occurrences\n");
printf("4. Find last occurrence\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
int index = findFirstOccurrence(arr, size, num);
if (index != -1) {
printf("First occurrence of %d is at index %d\n", num, index);
} else {
printf("Number %d not found in the array.\n", num);
}
break;
}
case 2: {
int index = findSecondOccurrence(arr, size, num);
if (index != -1) {
printf("Second occurrence of %d is at index %d\n", num, index);
} else {
printf("Second occurrence of %d not found in the array.\n", num);
}
break;
}
case 3: {
findFirstTwoOccurrences(arr, size, num);
break;
}
case 4: {
int index = findLastOccurrence(arr, size, num);
if (index != -1) {
printf("Last occurrence of %d is at index %d\n", num, index);
} else {
printf("Number %d not found in the array.\n", num);
}
break;
}
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}
// Function to find the first occurrence of a number in the array
int findFirstOccurrence(int arr[], int size, int num) {
for (int i = 0; i < size; i++) {
if (arr[i] == num) {
return i; // Return the index of the first occurrence
}
}
return -1; // Return -1 if the number is not found
}

// Function to find the second occurrence of a number in the array


int findSecondOccurrence(int arr[], int size, int num) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == num) {
count++;
if (count == 2) {
return i; // Return the index of the second occurrence
}
}
}
return -1; // Return -1 if the second occurrence is not found
}

// Function to find the first two occurrences of a number in the array


void findFirstTwoOccurrences(int arr[], int size, int num) {
int count = 0;
printf("First two occurrences of %d are at indices: ", num);
for (int i = 0; i < size; i++) {
if (arr[i] == num) {
printf("%d ", i);
count++;
if (count == 2) {
break; // Stop after finding the first two occurrences
}
}
}
if (count == 0) {
printf("Number not found.");
}
printf("\n");
}

// Function to find the last occurrence of a number in the array


int findLastOccurrence(int arr[], int size, int num) {
for (int i = size - 1; i >= 0; i--) {
if (arr[i] == num) {
return i; // Return the index of the last occurrence
}
}
return -1; // Return -1 if the number is not found
}
Output:
Program 14: WAP to implement search in linkedlist: find 1st occurrence, only 2nd
occurrence, first two occurrence of a number.
#include <stdio.h>
#include <stdlib.h>

// Node structure for the linked list


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

// Function prototypes
void insertAtEnd(struct Node** head, int data);
int findFirstOccurrence(struct Node* head, int num);
int findSecondOccurrence(struct Node* head, int num);
void findFirstTwoOccurrences(struct Node* head, int num);

int main() {
struct Node* head = NULL;
int choice, num, data;
// Custom print statement
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Menu-driven interface
while (1) {
printf("\nMenu:\n");
printf("1. Insert element in linked list\n");
printf("2. Find first occurrence\n");
printf("3. Find second occurrence\n");
printf("4. Find first two occurrences\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the number to insert: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 2:
printf("Enter the number to search for: ");
scanf("%d", &num);
{
int index = findFirstOccurrence(head, num);
if (index != -1) {
printf("First occurrence of %d is at position %d\n", num, index);
} else {
printf("Number %d not found in the linked list.\n", num);
}
}
break;
case 3:
printf("Enter the number to search for: ");
scanf("%d", &num);
{
int index = findSecondOccurrence(head, num);
if (index != -1) {
printf("Second occurrence of %d is at position %d\n", num, index);
} else {
printf("Second occurrence of %d not found in the linked list.\n", num);
}
}
break;
case 4:
printf("Enter the number to search for: ");
scanf("%d", &num);
findFirstTwoOccurrences(head, num);
break;
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
// Function to insert a node at the end of the linked list
void insertAtEnd(struct Node** head, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head;
new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
}
// Function to find the first occurrence of a number in the linked list
int findFirstOccurrence(struct Node* head, int num) {
int pos = 1;
struct Node* current = head;
while (current != NULL) {
if (current->data == num) {
return pos;
}
current = current->next;
pos++;
}
return -1; // Return -1 if the number is not found
}
// Function to find the second occurrence of a number in the linked list
int findSecondOccurrence(struct Node* head, int num) {
int pos = 1, count = 0;
struct Node* current = head;

while (current != NULL) {


if (current->data == num) {
count++;
if (count == 2) {
return pos;
}
}
current = current->next;
pos++;
}

return -1; // Return -1 if the second occurrence is not found


}
// Function to find and print the first two occurrences of a number in the linked list
void findFirstTwoOccurrences(struct Node* head, int num) {
int pos = 1, count = 0;
struct Node* current = head;

printf("First two occurrences of %d are at positions: ", num);


while (current != NULL) {
if (current->data == num) {
printf("%d ", pos);
count++;
if (count == 2) {
break; // Stop after finding the first two occurrences
}
}
current = current->next;
pos++;
}

if (count == 0) {
printf("Number not found.");
}
printf("\n");
}
Output:
Program 15: WAP to show insertion and deletion in a linked list:
a) at beginning b) at end c) in middle d) in sorted order

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

// Node structure for the linked list


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

// Function prototypes
void insertAtBeginning(struct Node** head, int data);
void insertAtEnd(struct Node** head, int data);
void insertInMiddle(struct Node** head, int data, int position);
void insertInSortedOrder(struct Node** head, int data);
void deleteNode(struct Node** head, int key);
void displayList(struct Node* node);

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

// Custom print statement


printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Menu-driven interface
while (1) {
printf("\nMenu:\n");
printf("1. Insert at beginning\n");
printf("2. Insert at end\n");
printf("3. Insert in middle\n");
printf("4. Insert in sorted order\n");
printf("5. Delete a node\n");
printf("6. Display the linked list\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the number to insert at beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter the number to insert at end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter the number to insert in middle: ");
scanf("%d", &data);
printf("Enter the position (1-based index): ");
scanf("%d", &position);
insertInMiddle(&head, data, position);
break;
case 4:
printf("Enter the number to insert in sorted order: ");
scanf("%d", &data);
insertInSortedOrder(&head, data);
break;
case 5:
printf("Enter the number to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;
case 6:
displayList(head);
break;
case 7:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

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


void insertAtBeginning(struct Node** head, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}

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


void insertAtEnd(struct Node** head, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head;

new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}

while (last->next != NULL) {


last = last->next;
}

last->next = new_node;
}

// Function to insert a node in the middle of the linked list


void insertInMiddle(struct Node** head, int data, int position) {
if (position < 1) {
printf("Invalid position. Position should be >= 1.\n");
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = data;

if (position == 1) {
new_node->next = *head;
*head = new_node;
return;
}

struct Node* current = *head;


int i;
for ( i = 1; i < position - 1 && current != NULL; i++) {
current = current->next;
}

if (current == NULL) {
printf("The previous node is null. Inserting at the end.\n");
free(new_node);
insertAtEnd(head, data);
return;
}
new_node->next = current->next;
current->next = new_node;
}
// Function to insert a node in sorted order in the linked list
void insertInSortedOrder(struct Node** head, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;

// Special case for the head end


if (*head == NULL || (*head)->data >= data) {
new_node->next = *head;
*head = new_node;
return;
}
struct Node* current = *head;
while (current->next != NULL && current->next->data < data) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
// Function to delete a node by value
void deleteNode(struct Node** head, int key) {
struct Node* temp = *head, *prev = NULL;
// If the head node itself holds the key to be deleted
if (temp != NULL && temp->data == key) {
*head = temp->next; // Change head
free(temp); // Free old head
return;
}
// Search for the key to be deleted, keep track of the previous node
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If key was not present in linked list
if (temp == NULL) {
printf("Node with value %d not found.\n", key);
return;
}
// Unlink the node from linked list
prev->next = temp->next;
free(temp); // Free memory
}
// Function to display the linked list
void displayList(struct Node* node) {
if (node == NULL) {
printf("The linked list is empty.\n");
return;
}
printf("Linked List: ");
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
Output:
Program 16: WAP to show insertion and deletion in a circular, header and doubly linked
list.
#include <stdio.h>
#include <stdlib.h>

// Node structure for circular linked list


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

// Node structure for header linked list


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

// Node structure for doubly linked list


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

// Function prototypes for Circular Linked List


void insertAtEndCircular(struct CircularNode** head, int data);
void deleteNodeCircular(struct CircularNode** head, int key);
void displayCircular(struct CircularNode* head);

// Function prototypes for Header Linked List


struct HeaderNode* createHeaderNode(int data);
void insertAtEndHeader(struct HeaderNode* head, int data);
void deleteNodeHeader(struct HeaderNode* head, int key);
void displayHeader(struct HeaderNode* head);

// Function prototypes for Doubly Linked List


void insertAtEndDoubly(struct DoublyNode** head, int data);
void deleteNodeDoubly(struct DoublyNode** head, int key);
void displayDoubly(struct DoublyNode* head);

int main() {
struct CircularNode* circularHead = NULL;
struct HeaderNode* headerHead = createHeaderNode(0); // Create header node
struct DoublyNode* doublyHead = NULL;

// Custom print statement


printf("Name: Gautam Garg \nRoll No. : 23049561\n");
// Circular Linked List Operations
insertAtEndCircular(&circularHead, 1);
insertAtEndCircular(&circularHead, 2);
insertAtEndCircular(&circularHead, 3);
printf("Circular Linked List: ");
displayCircular(circularHead);
deleteNodeCircular(&circularHead, 2);
printf("After deletion in Circular Linked List: ");
displayCircular(circularHead);

// Header Linked List Operations


insertAtEndHeader(headerHead, 5);
insertAtEndHeader(headerHead, 10);
printf("Header Linked List: ");
displayHeader(headerHead);
deleteNodeHeader(headerHead, 5);
printf("After deletion in Header Linked List: ");
displayHeader(headerHead);

// Doubly Linked List Operations


insertAtEndDoubly(&doublyHead, 20);
insertAtEndDoubly(&doublyHead, 30);
printf("Doubly Linked List: ");
displayDoubly(doublyHead);
deleteNodeDoubly(&doublyHead, 20);
printf("After deletion in Doubly Linked List: ");
displayDoubly(doublyHead);

return 0;
}

// Circular Linked List Functions


void insertAtEndCircular(struct CircularNode** head, int data) {
struct CircularNode* new_node = (struct CircularNode*)malloc(sizeof(struct CircularNode));
new_node->data = data;

if (*head == NULL) {
*head = new_node;
new_node->next = *head; // Point to itself
} else {
struct CircularNode* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = new_node;
new_node->next = *head;
}
}
void deleteNodeCircular(struct CircularNode** head, int key) {
if (*head == NULL) return;

struct CircularNode *temp = *head, *prev = NULL;

// If the head node itself holds the key


if (temp->data == key) {
// If there's only one node
if (temp->next == *head) {
free(temp);
*head = NULL;
return;
} else {
struct CircularNode* last = *head;
while (last->next != *head) {
last = last->next;
}
last->next = temp->next;
*head = temp->next; // Change head
free(temp);
return;
}
}

// Search for the key to be deleted


while (temp->next != *head && temp->next->data != key) {
temp = temp->next;
}

// If key was not present in the list


if (temp->next == *head) {
printf("Node with value %d not found.\n", key);
return;
}

// Unlink the node from the list


struct CircularNode* nodeToDelete = temp->next;
temp->next = nodeToDelete->next;
free(nodeToDelete);
}

void displayCircular(struct CircularNode* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}
struct CircularNode* temp = head;
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}

// Header Linked List Functions


struct HeaderNode* createHeaderNode(int data) {
struct HeaderNode* header = (struct HeaderNode*)malloc(sizeof(struct HeaderNode));
header->data = data;
header->next = NULL;
return header;
}

void insertAtEndHeader(struct HeaderNode* head, int data) {


struct HeaderNode* new_node = (struct HeaderNode*)malloc(sizeof(struct HeaderNode));
new_node->data = data;
new_node->next = NULL;

struct HeaderNode* temp = head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}

void deleteNodeHeader(struct HeaderNode* head, int key) {


struct HeaderNode* temp = head->next; // Start from the first real node
struct HeaderNode* prev = head;

while (temp != NULL) {


if (temp->data == key) {
prev->next = temp->next;
free(temp);
return;
}
prev = temp;
temp = temp->next;
}
printf("Node with value %d not found.\n", key);
}

void displayHeader(struct HeaderNode* head) {


struct HeaderNode* temp = head->next; // Skip the header
if (temp == NULL) {
printf("List is empty.\n");
return;
}
printf("Header Linked List: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Doubly Linked List Functions


void insertAtEndDoubly(struct DoublyNode** head, int data) {
struct DoublyNode* new_node = (struct DoublyNode*)malloc(sizeof(struct DoublyNode));
new_node->data = data;
new_node->next = NULL;

if (*head == NULL) {
new_node->prev = NULL;
*head = new_node;
return;
}

struct DoublyNode* temp = *head;


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

temp->next = new_node;
new_node->prev = temp;
}

void deleteNodeDoubly(struct DoublyNode** head, int key) {


struct DoublyNode* temp = *head;

// If the list is empty


if (temp == NULL) return;

// If the node to be deleted is the head


if (temp->data == key) {
*head = temp->next; // Change head
if (*head != NULL) {
(*head)->prev = NULL; // Update previous of new head
}
free(temp);
return;
}

// Search for the key to be deleted


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

// If the key was not found


if (temp == NULL) {
printf("Node with value %d not found.\n", key);
return;
}

// Unlink the node from the doubly linked list


if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}

free(temp);
}

void displayDoubly(struct DoublyNode* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}
printf("Doubly Linked List: ");
struct DoublyNode* temp = head;
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
Output:
Program 17: WAP to implement polynomial evaluation.
#include <stdio.h>
#include <math.h>

// Function to evaluate the polynomial using Horner's method


double evaluatePolynomial(int coefficients[], int degree, double x) {
double result = coefficients[0]; // Initialize result with the first coefficient
int i;
for ( i = 1; i <= degree; i++) {
result = result * x + coefficients[i];
}

return result;
}

int main() {
int degree;

// Print Name and Roll No.


printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Take the degree of the polynomial as input


printf("Enter the degree of the polynomial: ");
scanf("%d", &degree);

int coefficients[degree + 1]; // Array to store coefficients of the polynomial

// Input the coefficients of the polynomial


printf("Enter the coefficients (from highest to lowest degree):\n");
int i;
for ( i = 0; i <= degree; i++) {
printf("Coefficient of x^%d: ", degree - i);
scanf("%d", &coefficients[i]);
}

double x;
// Input the value of x for evaluation
printf("Enter the value of x: ");
scanf("%lf", &x);

// Call the function to evaluate the polynomial


double result = evaluatePolynomial(coefficients, degree, x);

// Print the result


printf("The result of the polynomial evaluation is: %.2lf\n", result);

return 0;
}
Output:
Program 18: WAP to show working of simple queue using array and Linked list.

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

// Node structure for linked list implementation


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

// Queue structure for array implementation


#define MAX 5
struct QueueArray {
int items[MAX];
int front, rear;
};

// Function prototypes for queue operations using array


void initializeQueueArray(struct QueueArray* q);
int isFullArray(struct QueueArray* q);
int isEmptyArray(struct QueueArray* q);
void enqueueArray(struct QueueArray* q, int value);
int dequeueArray(struct QueueArray* q);
void displayQueueArray(struct QueueArray* q);

// Function prototypes for queue operations using linked list


struct Node* createNode(int value);
void enqueueLinkedList(struct Node** front, struct Node** rear, int value);
int dequeueLinkedList(struct Node** front);
void displayQueueLinkedList(struct Node* front);

int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Array implementation
struct QueueArray qArray;
initializeQueueArray(&qArray);

printf("\nQueue using Array:\n");


enqueueArray(&qArray, 10);
enqueueArray(&qArray, 20);
enqueueArray(&qArray, 30);
displayQueueArray(&qArray);
printf("Dequeued: %d\n", dequeueArray(&qArray));
displayQueueArray(&qArray);

// Linked list implementation


struct Node* front = NULL;
struct Node* rear = NULL;

printf("\nQueue using Linked List:\n");


enqueueLinkedList(&front, &rear, 40);
enqueueLinkedList(&front, &rear, 50);
enqueueLinkedList(&front, &rear, 60);
displayQueueLinkedList(front);
printf("Dequeued: %d\n", dequeueLinkedList(&front));
displayQueueLinkedList(front);

return 0;
}

// Queue functions using array


void initializeQueueArray(struct QueueArray* q) {
q->front = -1;
q->rear = -1;
}

int isFullArray(struct QueueArray* q) {


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

int isEmptyArray(struct QueueArray* q) {


return q->front == -1;
}

void enqueueArray(struct QueueArray* q, int value) {


if (isFullArray(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (isEmptyArray(q)) {
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = value;
printf("Enqueued: %d\n", value);
}

int dequeueArray(struct QueueArray* q) {


if (isEmptyArray(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int value = q->items[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1; // Queue is now empty
} else {
q->front = (q->front + 1) % MAX;
}
return value;
}

void displayQueueArray(struct QueueArray* q) {


if (isEmptyArray(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
int i = q->front;
while (1) {
printf("%d ", q->items[i]);
if (i == q->rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}

// Queue functions using linked list


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
void enqueueLinkedList(struct Node** front, struct Node** rear, int value) {
struct Node* newNode = createNode(value);
if (*rear == NULL) {
*front = *rear = newNode; // Queue is empty
printf("Enqueued: %d\n", value);
return;
}
(*rear)->next = newNode;
*rear = newNode;
printf("Enqueued: %d\n", value);
}

int dequeueLinkedList(struct Node** front) {


if (*front == NULL) {
printf("Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int value = (*front)->data;
struct Node* temp = *front;
*front = (*front)->next;

if (*front == NULL) {
// If the queue becomes empty, reset rear
return value;
}
free(temp);
return value;
}

void displayQueueLinkedList(struct Node* front) {


if (front == NULL) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
while (front != NULL) {
printf("%d ", front->data);
front = front->next;
}
printf("\n");
}
Output:
Program 19: WAP to show working of Circular Queue using array and linked list.
#include <stdio.h>
#include <stdlib.h>

// Node structure for linked list implementation


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

// Circular Queue structure for array implementation


#define MAX 5
struct CircularQueueArray {
int items[MAX];
int front, rear;
};

// Function prototypes for circular queue operations using array


void initializeCircularQueueArray(struct CircularQueueArray* cq);
int isFullArray(struct CircularQueueArray* cq);
int isEmptyArray(struct CircularQueueArray* cq);
void enqueueArray(struct CircularQueueArray* cq, int value);
int dequeueArray(struct CircularQueueArray* cq);
void displayCircularQueueArray(struct CircularQueueArray* cq);

// Function prototypes for circular queue operations using linked list


struct Node* createNode(int value);
void enqueueLinkedList(struct Node** front, struct Node** rear, int value);
int dequeueLinkedList(struct Node** front);
void displayCircularQueueLinkedList(struct Node* front);

int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Array implementation
struct CircularQueueArray cqArray;
initializeCircularQueueArray(&cqArray);

printf("\nCircular Queue using Array:\n");


enqueueArray(&cqArray, 10);
enqueueArray(&cqArray, 20);
enqueueArray(&cqArray, 30);
displayCircularQueueArray(&cqArray);
printf("Dequeued: %d\n", dequeueArray(&cqArray));
displayCircularQueueArray(&cqArray);
enqueueArray(&cqArray, 40);
enqueueArray(&cqArray, 50);
displayCircularQueueArray(&cqArray);
enqueueArray(&cqArray, 60); // Attempt to enqueue when full
displayCircularQueueArray(&cqArray);

// Linked list implementation


struct Node* front = NULL;
struct Node* rear = NULL;

printf("\nCircular Queue using Linked List:\n");


enqueueLinkedList(&front, &rear, 70);
enqueueLinkedList(&front, &rear, 80);
enqueueLinkedList(&front, &rear, 90);
displayCircularQueueLinkedList(front);
printf("Dequeued: %d\n", dequeueLinkedList(&front));
displayCircularQueueLinkedList(front);
enqueueLinkedList(&front, &rear, 100);
enqueueLinkedList(&front, &rear, 110);
displayCircularQueueLinkedList(front);

return 0;
}

// Circular Queue functions using array


void initializeCircularQueueArray(struct CircularQueueArray* cq) {
cq->front = -1;
cq->rear = -1;
}

int isFullArray(struct CircularQueueArray* cq) {


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

int isEmptyArray(struct CircularQueueArray* cq) {


return cq->front == -1;
}

void enqueueArray(struct CircularQueueArray* cq, int value) {


if (isFullArray(cq)) {
printf("Circular Queue is full! Cannot enqueue %d\n", value);
return;
}
if (isEmptyArray(cq)) {
cq->front = 0; // Initialize front if queue is empty
}
cq->rear = (cq->rear + 1) % MAX;
cq->items[cq->rear] = value;
printf("Enqueued: %d\n", value);
}
int dequeueArray(struct CircularQueueArray* cq) {
if (isEmptyArray(cq)) {
printf("Circular Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int value = cq->items[cq->front];
if (cq->front == cq->rear) {
// Queue becomes empty after this operation
cq->front = -1;
cq->rear = -1;
} else {
cq->front = (cq->front + 1) % MAX;
}
return value;
}

void displayCircularQueueArray(struct CircularQueueArray* cq) {


if (isEmptyArray(cq)) {
printf("Circular Queue is empty!\n");
return;
}
printf("Circular Queue: ");
int i = cq->front;
while (1) {
printf("%d ", cq->items[i]);
if (i == cq->rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}

// Circular Queue functions using linked list


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

void enqueueLinkedList(struct Node** front, struct Node** rear, int value) {


struct Node* newNode = createNode(value);
if (*rear == NULL) {
// If queue is empty
*front = *rear = newNode;
newNode->next = newNode; // Point to itself
printf("Enqueued: %d\n", value);
return;
}
newNode->next = *front; // Point new node to front
(*rear)->next = newNode; // Old rear points to new node
*rear = newNode; // Update rear to new node
printf("Enqueued: %d\n", value);
}

int dequeueLinkedList(struct Node** front) {


if (*front == NULL) {
printf("Circular Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int value = (*front)->data;
struct Node* temp = *front;

if (*front == (*front)->next) {
// If there is only one node
*front = NULL;
} else {
struct Node* rear = *front;
while (rear->next != *front) {
rear = rear->next;
}
rear->next = (*front)->next; // Update rear to point to the next node
*front = (*front)->next; // Move front to the next node
}

free(temp);
return value;
}

void displayCircularQueueLinkedList(struct Node* front) {


if (front == NULL) {
printf("Circular Queue is empty!\n");
return;
}
printf("Circular Queue: ");
struct Node* temp = front;
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != front);
printf("\n");
}
Output:
Program 20: WAP to implement priority queue using array and linked list.
#include <stdio.h>
#include <stdlib.h>

// Node structure for linked list implementation


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

// Priority Queue structure for array implementation


#define MAX 5
struct PriorityQueueArray {
int items[MAX];
int priorities[MAX];
int count;
};

// Function prototypes for priority queue operations using array


void initializePriorityQueueArray(struct PriorityQueueArray* pq);
int isFullArray(struct PriorityQueueArray* pq);
int isEmptyArray(struct PriorityQueueArray* pq);
void enqueueArray(struct PriorityQueueArray* pq, int value, int priority);
int dequeueArray(struct PriorityQueueArray* pq);
void displayPriorityQueueArray(struct PriorityQueueArray* pq);

// Function prototypes for priority queue operations using linked list


struct Node* createNode(int value, int priority);
void enqueueLinkedList(struct Node** front, struct Node** rear, int value, int priority);
int dequeueLinkedList(struct Node** front);
void displayPriorityQueueLinkedList(struct Node* front);

int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Array implementation
struct PriorityQueueArray pqArray;
initializePriorityQueueArray(&pqArray);

printf("\nPriority Queue using Array:\n");


enqueueArray(&pqArray, 10, 2);
enqueueArray(&pqArray, 20, 1);
enqueueArray(&pqArray, 30, 3);
displayPriorityQueueArray(&pqArray);
printf("Dequeued: %d\n", dequeueArray(&pqArray));
displayPriorityQueueArray(&pqArray);
// Linked list implementation
struct Node* front = NULL;
struct Node* rear = NULL;

printf("\nPriority Queue using Linked List:\n");


enqueueLinkedList(&front, &rear, 40, 1);
enqueueLinkedList(&front, &rear, 50, 3);
enqueueLinkedList(&front, &rear, 60, 2);
displayPriorityQueueLinkedList(front);
printf("Dequeued: %d\n", dequeueLinkedList(&front));
displayPriorityQueueLinkedList(front);

return 0;
}

// Priority Queue functions using array


void initializePriorityQueueArray(struct PriorityQueueArray* pq) {
pq->count = 0;
}

int isFullArray(struct PriorityQueueArray* pq) {


return pq->count == MAX;
}

int isEmptyArray(struct PriorityQueueArray* pq) {


return pq->count == 0;
}

void enqueueArray(struct PriorityQueueArray* pq, int value, int priority) {


if (isFullArray(pq)) {
printf("Priority Queue is full! Cannot enqueue %d\n", value);
return;
}
int i;
// Find the correct position for the new item based on priority
for (i = pq->count - 1; (i >= 0 && priority < pq->priorities[i]); i--) {
pq->items[i + 1] = pq->items[i];
pq->priorities[i + 1] = pq->priorities[i];
}
pq->items[i + 1] = value;
pq->priorities[i + 1] = priority;
pq->count++;
printf("Enqueued: %d with priority %d\n", value, priority);
}

int dequeueArray(struct PriorityQueueArray* pq) {


if (isEmptyArray(pq)) {
printf("Priority Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int i;
int value = pq->items[0];
for ( i = 0; i < pq->count - 1; i++) {
pq->items[i] = pq->items[i + 1];
pq->priorities[i] = pq->priorities[i + 1];
}
pq->count--;
return value;
}

void displayPriorityQueueArray(struct PriorityQueueArray* pq) {


if (isEmptyArray(pq)) {
printf("Priority Queue is empty!\n");
return;
}
printf("Priority Queue: ");
int i;
for ( i = 0; i < pq->count; i++) {
printf("%d(priority: %d) ", pq->items[i], pq->priorities[i]);
}
printf("\n");
}

// Priority Queue functions using linked list


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

void enqueueLinkedList(struct Node** front, struct Node** rear, int value, int priority) {
struct Node* newNode = createNode(value, priority);
if (*front == NULL) {
*front = *rear = newNode; // If the queue is empty
printf("Enqueued: %d with priority %d\n", value, priority);
return;
}

// If new node has higher priority than the front node


if (priority < (*front)->priority) {
newNode->next = *front;
*front = newNode;
} else {
struct Node* current = *front;
while (current->next != NULL && current->next->priority <= priority) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;

if (newNode->next == NULL) {
*rear = newNode; // Update rear if it's the new last node
}
}
printf("Enqueued: %d with priority %d\n", value, priority);
}

int dequeueLinkedList(struct Node** front) {


if (*front == NULL) {
printf("Priority Queue is empty! Cannot dequeue\n");
return -1; // Return -1 for empty queue
}
int value = (*front)->data;
struct Node* temp = *front;
*front = (*front)->next;
free(temp);
return value;
}

void displayPriorityQueueLinkedList(struct Node* front) {


if (front == NULL) {
printf("Priority Queue is empty!\n");
return;
}
printf("Priority Queue: ");
struct Node* temp = front;
while (temp != NULL) {
printf("%d(priority: %d) ", temp->data, temp->priority);
temp = temp->next;
}
printf("\n");
}
Output:
Program 21: WAP to show traversal of a binary tree.
#include <stdio.h>
#include <stdlib.h>

// Definition of the tree node structure


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

// Function to create a new node


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

// Function for in-order traversal


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

// Function for pre-order traversal


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

// Function for post-order traversal


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

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

// Create a binary tree


struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);

// Perform traversals
printf("In-order traversal: ");
inorderTraversal(root);
printf("\n");

printf("Pre-order traversal: ");


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

printf("Post-order traversal: ");


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

return 0;
}
Output:
Program 22: WAP to show insertion, deletion and searching in a binary search tree.
#include <stdio.h>
#include <stdlib.h>

// Definition of the tree node structure


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

// Function to create a new node


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

// Function to insert a node in the BST


struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}

// Function to search for a node in the BST


struct Node* search(struct Node* root, int data) {
if (root == NULL || root->data == data) {
return root; // Data found or reached leaf node
}
if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}

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


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

// Function to delete a node from the BST


struct Node* deleteNode(struct Node* root, int data) {
if (root == NULL) {
return root; // Tree is empty or data not found
}
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
// Node with one child or no child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
// Node with two children
struct Node* temp = findMin(root->right); // Get the inorder successor
root->data = temp->data; // Copy the inorder successor's content to this node
root->right = deleteNode(root->right, temp->data); // Delete the inorder successor
}
return root;
}

// Function to perform in-order traversal of the BST


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

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

struct Node* root = NULL;


// Insert nodes into the BST
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 70);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 60);
root = insert(root, 80);

// Display in-order traversal


printf("In-order traversal of the BST: ");
inorderTraversal(root);
printf("\n");

// Search for a node


int searchValue = 40;
struct Node* foundNode = search(root, searchValue);
if (foundNode) {
printf("Node %d found in the BST.\n", searchValue);
} else {
printf("Node %d not found in the BST.\n", searchValue);
}

// Delete a node
printf("Deleting node 20 from the BST...\n");
root = deleteNode(root, 20);
printf("In-order traversal after deletion: ");
inorderTraversal(root);
printf("\n");

// Search for a deleted node


searchValue = 20;
foundNode = search(root, searchValue);
if (foundNode) {
printf("Node %d found in the BST.\n", searchValue);
} else {
printf("Node %d not found in the BST.\n", searchValue);
}

return 0;
}
Output:
Program 23: WAP to show working of depth first traversal of a graph.
#include <stdio.h>
#include <stdlib.h>

// Definition of the structure for a graph node


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

// Definition of the structure for the graph


struct Graph {
int numVertices;
struct Node** adjLists;
};

// Function to create a new node


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

// Function to create a graph


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = (struct Node**)malloc(vertices * sizeof(struct Node*));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Since the graph is undirected, add an edge from dest to src as well
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// DFS recursive function
void DFS(struct Graph* graph, int vertex, int* visited) {
visited[vertex] = 1; // Mark the current vertex as visited
printf("%d ", vertex); // Print the visited vertex

struct Node* temp = graph->adjLists[vertex];


while (temp) {
int adjVertex = temp->data;
if (!visited[adjVertex]) {
DFS(graph, adjVertex, visited); // Recur for the adjacent vertex
}
temp = temp->next;
}
}

// Function to perform DFS traversal


void depthFirstTraversal(struct Graph* graph) {
int i;
int* visited = (int*)malloc(graph->numVertices * sizeof(int));
for ( i = 0; i < graph->numVertices; i++) {
visited[i] = 0; // Initialize all vertices as not visited
}

printf("Depth First Traversal starting from vertex 0:\n");


DFS(graph, 0, visited);
printf("\n");
}

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

struct Graph* graph = createGraph(5); // Create a graph with 5 vertices

// Adding edges to the graph


addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);

// Perform depth-first traversal


depthFirstTraversal(graph);
int i;
// Free allocated memory (optional, for better practice)
for ( i = 0; i < graph->numVertices; i++) {
struct Node* temp = graph->adjLists[i];
while (temp) {
struct Node* toFree = temp;
temp = temp->next;
free(toFree);
}
}
free(graph->adjLists);
free(graph);

return 0;
}
Output:
Program 24: WAP to show working of breadth first traversal of a graph.
#include <stdio.h>
#include <stdlib.h>

#define MAX 100 // Maximum number of vertices

// Structure for the adjacency list node


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

// Structure for the graph


struct Graph {
int numVertices;
struct Node** adjLists;
};

// Function to create a new node


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

// Function to create a graph


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = (struct Node**)malloc(vertices * sizeof(struct Node*));
int i;
for ( i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Since the graph is undirected, add an edge from dest to src as well
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Function to perform breadth-first traversal


void breadthFirstTraversal(struct Graph* graph, int startVertex) {
int visited[MAX] = {0}; // Array to track visited vertices
int queue[MAX]; // Queue for BFS
int front = 0, rear = 0;

visited[startVertex] = 1; // Mark the starting vertex as visited


queue[rear++] = startVertex; // Enqueue the starting vertex

printf("Breadth First Traversal starting from vertex %d:\n", startVertex);

while (front < rear) {


int currentVertex = queue[front++]; // Dequeue a vertex
printf("%d ", currentVertex); // Print the visited vertex

struct Node* temp = graph->adjLists[currentVertex];


while (temp) {
int adjVertex = temp->data;
if (!visited[adjVertex]) { // If the adjacent vertex has not been visited
visited[adjVertex] = 1; // Mark it as visited
queue[rear++] = adjVertex; // Enqueue the adjacent vertex
}
temp = temp->next;
}
}
printf("\n");
}

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

struct Graph* graph = createGraph(5); // Create a graph with 5 vertices

// Adding edges to the graph


addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);

// Perform breadth-first traversal


breadthFirstTraversal(graph, 0); // Start BFS from vertex 0
int i;
// Free allocated memory (optional, for better practice)
for ( i = 0; i < graph->numVertices; i++) {
struct Node* temp = graph->adjLists[i];
while (temp) {
struct Node* toFree = temp;
temp = temp->next;
free(toFree);
}
}
free(graph->adjLists);
free(graph);

return 0;
}
Output:
Program 25: Write a Program to show the following sorting algorithms:
a) Bubble Sort b) Insertion Sort c) Quick Sort d) Merge Sort e) Selection Sort
#include <stdio.h>

// Function to perform Bubble Sort


void bubbleSort(int arr[], int n) {
int i,j;
for ( i = 0; i < n - 1; i++) {
for ( 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 perform Insertion Sort


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

// Function to perform Quick Sort


int partition(int arr[], int low, int high) {
int j;
int pivot = arr[high]; // Pivot
int i = (low - 1); // Index of smaller element
for ( 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;
}

void quickSort(int 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 perform Merge Sort


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

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

i = 0;
j = 0;
k = left;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

// Function to perform Selection Sort


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

// Function to print an array


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

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

int arr[] = {64, 34, 25, 12, 22, 11, 90};


int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");


printArray(arr, n);
// Bubble Sort
bubbleSort(arr, n);
printf("Sorted array using Bubble Sort: \n");
printArray(arr, n);

// Resetting array for next sort


int arr1[] = {64, 34, 25, 12, 22, 11, 90};
printf("Sorted array using Insertion Sort: \n");
insertionSort(arr1, n);
printArray(arr1, n);

// Resetting array for next sort


int arr2[] = {64, 34, 25, 12, 22, 11, 90};
printf("Sorted array using Quick Sort: \n");
quickSort(arr2, 0, n - 1);
printArray(arr2, n);

// Resetting array for next sort


int arr3[] = {64, 34, 25, 12, 22, 11, 90};
printf("Sorted array using Merge Sort: \n");
mergeSort(arr3, 0, n - 1);
printArray(arr3, n);

// Resetting array for next sort


int arr4[] = {64, 34, 25, 12, 22, 11, 90};
printf("Sorted array using Selection Sort: \n");
selectionSort(arr4, n);
printArray(arr4, n);

return 0;
}
Output:
Program: WAP for Linear Search
#include <stdio.h>

// Function for Linear Search


int linearSearch(int arr[], int size, int target) {
int i;
for ( i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index if the target is found
}
}
return -1; // Return -1 if the target is not found
}

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

int arr[] = {5, 3, 8, 6, 2, 7, 4, 1};


int size = sizeof(arr) / sizeof(arr[0]);
int target;
int i;
printf("Array: ");
for ( i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Asking user for the number to search


printf("Enter the number to search: ");
scanf("%d", &target);

// Performing Linear Search


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

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

return 0;
}
Output:
Program 27: WAP for Binary Search.
#include <stdio.h>

// Function for Binary Search


int binarySearch(int arr[], int size, int target) {
int left = 0;
int right = size - 1;

while (left <= right) {


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

// Check if target is present at mid


if (arr[mid] == target) {
return mid; // Return the index if the target is found
}

// If target is greater, ignore the left half


if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}

return -1; // Return -1 if the target is not found


}

// Main function
int main() {
// Display Name and Roll Number
printf("Name: Gautam Garg \nRoll No. : 23049561\n");

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Sorted array


int size = sizeof(arr) / sizeof(arr[0]);
int target;
int i;
printf("Sorted Array: ");
for ( i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Asking user for the number to search


printf("Enter the number to search: ");
scanf("%d", &target);
// Performing Binary Search
int result = binarySearch(arr, size, target);

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

return 0;
}
Output:

You might also like