0% found this document useful (0 votes)
8 views84 pages

DS Record 25 Final

The document outlines the course structure for the U23CSP03 Data Structures Laboratory for the academic year 2024-2025, including a bonafide certificate and a detailed index of experiments. It includes various programming tasks related to data structures in C, such as implementing arrays, linked lists, stacks, queues, and sorting algorithms. Each experiment is accompanied by algorithms, sample code, and expected outputs, demonstrating the practical application of data structure concepts.

Uploaded by

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

DS Record 25 Final

The document outlines the course structure for the U23CSP03 Data Structures Laboratory for the academic year 2024-2025, including a bonafide certificate and a detailed index of experiments. It includes various programming tasks related to data structures in C, such as implementing arrays, linked lists, stacks, queues, and sorting algorithms. Each experiment is accompanied by algorithms, sample code, and expected outputs, demonstrating the practical application of data structure concepts.

Uploaded by

kaviyarasu291
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/ 84

DEPARTMENT OFARTIFICIAL INTELLIGENCE

AND DATA SCIENCE

U23CSP03-DATA STRUCTURES LABORATORY

2024-2025
BONAFIDE CERTIFICATE

Certified that this is the bonafide record of work by


done by
Mr./Ms. .......................................................................................................... in the
U23CSP03-DATA STRUCTURES LABORATORY of this institution, for the Third
Semester Artificial Intelligence and Data Science, during the year 2024-2025.

Mr.S.Chandra Mohan,M.Tech., Dr. E. Gomathi M.E., Ph.D.,


ASSISTANT PROFESSOR HEAD OF THE DEPARTMENT
Department of Artificial Intelligence and Department of Artificial Intelligence and
Data Science, Data Science,
Coimbatore Institute of Engineering and Coimbatore Institute of Engineering
Technology, and Technology,

Coimbatore - 641109. Coimbatore – 641109.

Submitted for the University Practical Examination held on ............................. at Coimbatore


Institute of Engineering and Technology, Coimbatore – 641 109.

Register Number:

Internal Examiner External Examiner


INDEX

S.NO DATE LIST OF EXPERIMENTS MARKS PAGE SIGNATURE


NO
Write a program to read five
values into an array and print
them out in reverse order (Use
1) two independent for loops).
Insert, Update, Delete, sorting,
Traversing.

Create a C program to
implement a singly linked
list,Doubly, Circular linked list
2) Perform basic operations:
insertion, deletion,
traversal,and search.
Implementation of Stack,
Queue and its
3) Applications.Perform basic
operations: insertion, deletion,
traversal,and search.

Write a C program to
implement the binary search
tree and AVL tree using the
4) following operations- Insertion,
searching, deletion and
traversal.

Create a C program to
implement the DFS and BFS
algorithm and set of
operations.
1. Finding the shortest path in
5) an unweighted graph,
like finding the shortest path
between friends on a
social network.
2. Navigation through maze

Write a C program to
implementation of searching
and
6) sorting algorithms.
1. sorting students grade
2.E-commerce
3.Library systems.
S.NO DATE LIST OF EXPERIMENTS MARKS PAGE SIGNATURE
NO
Write a C program to sort a list of
7) employees by their salary in
ascending order using any sorting
algorithm.
Implementation of Hashing and
Collision Resolution
Techniques.
8) 1. Separate chaining program
using Hash technique

Write a program to display the


length of the longest and
shortest chains in the hash
9) table after multiple insertions.

Mini Project – Data structures


1. Creating a To-do list
2. Phone book
10) 3. Student’s grade checker
4. Banking management system
5. Travel plan
6. Games
7. Others-Recent trends
EX NO: 1
IMPLEMENTATION OF ARRAY
DATE :

Aim:
To write a c program to read the five values into an array and print them out in reverse
order(Usetwo independent for loops)

Algorithm:
1. Read Five Values:
• Step 1: Use a for loop to read five integer values from the user and store them in
the
array.
2. Insert a New Value:
・Step 1: Read the index where the new value should be inserted.
・Step 2: Shift elements from the end to the specified index to make room for the new
value.
・Step 3: Insert the new value at the specified index.
3. Update a Value:
・Step 1: Read the index of the value to be updated.
・Step 2: Update the value at the specified index.
4. Delete a Value:
・Step 1: Read the index of the value to be deleted.
・Step 2: Shift elements from the index of the deletion to the end to fill the gap.
・Step 3: Optionally, set the last value to zero.
5. Sort the Array:
・Step: Use Bubble Sort to sort the array in ascending order.
6. Traverse in Reverse Order:
・Step 1: Use a for loop to print the array elements in reverse order.
・Step 2: Determine the number of elements in the array.
・Step 3: Use another for loop to print the elements starting from the end.
Program:

#include <stdio.h>
#define SIZE 5
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to sort an array using Bubble Sort
void sortArray(int arr[], int size) {
int temp;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[SIZE];
int newValue, index, i;// Step 1: Read five values into the array
printf("Enter 5 values:\n");
for (i = 0; i < SIZE; i++) {
scanf("%d", &arr[i]);
}
printf("Original array:\n");
printArray(arr, SIZE);
// Step 2: Insert a new value
printf("Enter the index (0-4) to insert a new value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
}
else {
// Shift elements to the right
for (i = SIZE - 1; i > index; i--) {
arr[i] = arr[i - 1];
}
// Insert new value
printf("Enter the new value: ");
scanf("%d", &newValue);
arr[index] = newValue;
}
printf("Array after insertion:\n");
printArray(arr, SIZE);
// Step 3: Update a value
printf("Enter the index (0-4) to update a value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
} else {
printf("Enter the new value: ");
scanf("%d", &newValue);
arr[index] = newValue;
}
printf("Array after update:\n");
printArray(arr, SIZE);
// Step 4: Delete a value
printf("Enter the index (0-4) to delete a value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
} else {
// Shift elements to the left
for (i = index; i < SIZE - 1; i++) {
arr[i] = arr[i + 1];
printf("Array after deletion:\n");
printArray(arr, SIZE);
// Step 5: Sort the array
sortArray(arr, SIZE);
}
// Step 5: Sort the array
sortArray(arr, SIZE);printf("Sorted array:\n");
printArray(arr, SIZE);
// Step 6: Traverse the array in reverse order using two
independent for loops
printf("Array in reverse order:\n");
// First for loop to determine the number of elements
int numElements = SIZE;
// Second for loop to print elements in reverse order
for (i = numElements - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter 5 values:
22
33
44
55
66
Original array:
22 33 44 55 66
Enter the index (0-4) to insert a new value: 2
Enter the new value: 70
Array after insertion:
22 33 70 44 55
Enter the index (0-4) to update a value: 1
Enter the new value: 56
Array after update:
22 56 70 44 55
Enter the index (0-4) to delete a value: 5
Invalid index.
Array after deletion:
22 56 70 44 55
Sorted array:
22 44 55 56 70
Array in reverse order:
70 56 55 44 22

Result:
Thus the C program was implemented an array in reverse order and executed
successfully.
EX NO: 2(A) IMPLEMENTATION OF SINGLY LINKED
LIST,DOUBLY AND CIRCULAR LINLED LIST
DATE :

Aim:
To write a c program to implement singly linked list to perform the operations.

Algorithm:
1. Create a Node:
・Define a structure for the node with data and a pointer to the next node.
2. Insert a Node:
・Allocate memory for a new node.
・Set its data and adjust pointers to maintain the linked list.
3. Delete a Node:
・Traverse the list to find the node to delete.
・Adjust pointers to remove the node.
4. Traverse and Display:
・Traverse through the list from the head node and print data.
Program:

#include <stdio.h>
#include <stdlib.h>
// Define a node in the singly linked list
struct Node {
int data;
struct Node* next;
};
// 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 insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node *temp = *head, *prev = NULL;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// Function to display the list
void displayList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
printf("Singly Linked List: ");
displayList(head);
deleteNode(&head, 2);
printf("After deleting 2: ");
displayList(head);
return 0;
}
Output:
Singly Linked List: 1 -> 2 -> 3 -> NULL
After deleting 2: 1 -> 3 -> NULL

Result:
Thus the C program was implemented an array in reverse order and executed
successfully.
EX NO: 2(B)
IMPLEMENTATION OF DOUBLY LINKE LIST
DATE :

Aim:
To write a c program to implement doubly linked list to perform the operations.

Algorithm:
1. Create a Node:
・Define a structure for the node with data, and pointers to the previous and next
nodes.
2. Insert a Node:
・Allocate memory for a new node.
・Adjust pointers to insert the node at the end.
3. Delete a Node:
• Traverse the list to find the node to delete.
・Adjust pointers to remove the node.
4. Traverse and Display:
・Traverse forward and backward to display the list.
Program:

#include <stdio.h>
#include <stdlib.h>
// Define a node in the doubly linked list
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
struct Node* temp = *head;
if (*head == NULL) {
*head = newNode;
} else {
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node* temp = *head;
while (temp != NULL && temp->data != data) {
temp = temp->next;
}
if (temp == NULL) return;
if (temp->prev != NULL) {
temp->prev->next = temp->next;
} else {
*head = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
}
// Function to display the list in forward direction
void displayForward(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");}
// Function to display the list in backward direction
void displayBackward(struct Node* head) {
struct Node* temp = head;
if (temp == NULL) return;
while (temp->next != NULL) {
temp = temp->next;
}
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->prev;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
deleteNode(&head, 2);
printf("After deleting 2, Forward: ");
displayForward(head);
printf("After deleting 2, Backward: “);
displayBackward(head);
return 0;

Output:
Doubly Linked List Forward: 1 <-> 2 <-> 3 <-> NULL
After deleting 2, Forward: 1 <-> 3 <-> NULL
After deleting 2, Backward: 3 <-> 1 <-> NULL

Result:
Thus the C program was implemented doubly linked list and executed successfully.
EX NO: 2(c)
IMPLEMENTATION OF CIRCULAR LINKE LIST
DATE :

Aim:
To write a c program to implement circular linked list to perform the operations.

Algorithm:
1. Create a Node:
・Define a structure for the node with data and a pointer to the next node.
2. Insert a Node:
・Allocate memory for a new node.
・Adjust pointers to maintain circularity.
3. Delete a Node:
・Traverse the list to find the node to delete.
・Adjust pointers to remove the node and maintain circularity.
4. Traverse and Display:
・Traverse the list starting from the head node until you return to the head.
Program:

#include <stdio.h>
#include <stdlib.h>
// Define a node in the circular linked list
struct Node {
int data;
struct Node* next;
};
// 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 insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node *temp = *head, *prev = NULL;
if (temp != NULL && temp->data == data) {
prev = *head;
while (prev->next != *head) {
prev = prev->next;
}
if (*head == (*head)->next) {
free(*head);
*head = NULL;
} else {
prev->next = temp->next;
free(temp);
*head = prev->next;
}
return;
}
while (temp->next != *head && temp->next->data != data) {
temp = temp->next;
}
if (temp->next == *head) return;
struct Node* toDelete = temp->next;
temp->next = toDelete->next;
free(toDelete);
}
// Function to display the list
void displayList(struct Node* head) {
if (head == NULL) return;
struct Node* temp = head;
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
printf("Circular Linked List: ");
displayList(head);
deleteNode(&head, 2);
printf("After deleting 2: ");
displayList(head);
return 0; }
Output:
Circular Linked List: 1 -> 2 -> 3 -> (head)
After deleting 2: 1 -> 3 -> (head)

Result:
Thus the c program was implemented circular linked list and output is verified.
EX NO: 3(A)
IMPLEMENTATION OF STACK
DATE :

Aim:
To write a c program to implement circular linked list to perform the operations.

Algorithm:
1. Create a Stack:
・Define a stack structure with an array and an integer to keep track of the top index.
2. Push Operation:
・Check if the stack is full.
・Increment the top index and add the new element.
3. Pop Operation:
・Check if the stack is empty.
・Return the element at the top index and decrement the top index.
4. Peek Operation:
・Return the element at the top index without modifying the stack.
5. Traversal:
・Print elements from the bottom to the top of the stack.
6. Search Operation:
・Search for an element in the stack.
Program:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Define a stack structure
typedef struct {
int arr[MAX];
int top;
} Stack;
// Initialize the stack
void initStack(Stack* stack) {
stack->top = -1;
}
// Check if the stack is full
int isFull(Stack* stack) {
return stack->top == MAX - 1;
}
// Check if the stack is empty
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// Push operation
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full.\n");return;
}
stack->arr[++stack->top] = value;
}
// Pop operation
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->arr[stack->top--];
}
// Peek operation
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->arr[stack->top];
}
// Traverse the stack
void traverseStack(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->arr[i]);
}
printf("\n");
}
// Search operation
int searchStack(Stack* stack, int value) {
for (int i = 0; i <= stack->top; i++) {
if (stack->arr[i] == value) {
return i;
}}
return -1;
}
int main() {
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Stack elements: ");
traverseStack(&stack);
printf("Popped element: %d\n", pop(&stack));
printf("Stack elements after pop: ");
traverseStack(&stack);
int valueToSearch = 20;
int index = searchStack(&stack,
valueToSearch);
if (index != -1) {
printf("Element %d found at index %d.\n",
valueToSearch, index);
} else {
printf("Element %d not found.\n",
valueToSearch);
}
return 0;

Output:
Stack elements: 10 20 30
Popped element: 30
Stack elements after pop: 10 20
Element 20 found at index 1.

Result:
Thus the C program was implemented stack and executed successfully.
EX NO: 3(B)
IMPLEMENTATION OF QUEUE
DATE :

Aim:
To write a c program to implement the queue to perform the operations.

Algorithm:
1. Create a Queue:
・Define a queue structure with an array, front and rear indices, and the size of the
queue.
2. Enqueue Operation:
・Check if the queue is full.
・Add the new element at the rear index and adjust the rear index.
3. Dequeue Operation:
・Check if the queue is empty.
・Remove the element from the front index and adjust the front index.
4. Peek Operation:
・Return the element at the front index without modifying the queue.
5. Traversal:
・Print elements from the front to the rear of the queue.
6. Search Operation:
・Search for an element in the queue.
Program:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Define a queue structure
typedef struct {
int arr[MAX];
int front, rear, size;
} Queue;
// Initialize the queue
void initQueue(Queue* queue) {
queue->front = 0;
queue->rear = -1;
queue->size = 0;}
// Check if the queue is full
int isFull(Queue* queue) {
return queue->size == MAX;}
// Check if the queue is empty
int isEmpty(Queue* queue) {
return queue->size == 0;
}
// Enqueue operation
void enqueue(Queue* queue, int value) {if (isFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->rear = (queue->rear + 1) % MAX;
queue->arr[queue->rear] = value;
queue->size++;
}
// Dequeue operation
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int value = queue->arr[queue->front];
queue->front = (queue->front + 1) % MAX;
queue->size--;
return value;
}
// Peek operation
int peekQueue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
return queue->arr[queue->front];
}
// Traverse the queue
void traverseQueue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
int i = queue->front;
int count = queue->size;
while (count--) {
printf("%d ", queue->arr[i]);
i = (i + 1) % MAX;
}
printf("\n");
}
// Search operation
int searchQueue(Queue* queue, int value) {
int i = queue->front;
int count = queue->size;
while (count--) {
if (queue->arr[i] == value) {
return i;
}
i = (i + 1) % MAX;
}
return -1;
}
int main() {
Queue queue;
initQueue(&queue);enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
printf("Queue elements: ");
traverseQueue(&queue);
printf("Dequeued element: %d\n", dequeue(&queue));
printf("Queue elements after dequeue: ");
traverseQueue(&queue);
int valueToSearch = 20;
int index = searchQueue(&queue, valueToSearch);
if (index != -1) {
printf("Element %d found at index %d.\n", valueToSearch, index);
} else {
printf("Element %d not found.\n", valueToSearch);
}
return 0;
}
Output:
Queue elements: 10 20 30
Dequeued element: 10
Queue elements after dequeue: 20 30
Element 20 found at index 1.

Result:
Thus the C program was implemented queue operations and executed successfully.
EX NO: 4(A) IMPLEMENTATION OF BINARY SEARCH TREE

DATE :

Aim:
Write a C program to implement the binary search tree and AVL tree using the
following operations- Insertion, searching, deletion and traversal.

Algorithm:
1. Step 1: Define Node Structure
◦ Create a struct Node with an integer data and two pointers left and right to represent child
nodes.
2. Step 2: Create a New Node

◦ Implement a function createNode(int data) that allocates memory, initializes the node with
data, and sets its child pointers to NULL.
3. Step 3: Insert a Node

◦ Define insert(struct Node* root, int data):


▪ If the root is NULL, create a new node.
▪ Recursively insert the node in the left subtree if data is smaller, or in the right subtree
if data is larger.
4. Step 4: Search for a Node

◦ Implement search(struct Node* root, int data):


▪ If the root is NULL or contains data, return the node.
▪ Recursively search in the left subtree if data is smaller, or in the right subtree if data
is larger.
5. Step 5: Find the Minimum Node

◦ Implement findMin(struct Node* root) to return the leftmost node of the tree, which holds
the minimum value.
6. Step 6: Delete a Node

◦ Define deleteNode(struct Node* root, int data):


▪ Recursively delete in the left or right subtree based on the value.
▪ Handle node deletion by either replacing it with its child (for one or no child) or the
minimum node from the right subtree (for two children).
7. Step 7: In-order Traversal

◦ Implement inOrder(struct Node* root) to recursively visit the left subtree, print the current
node, and then visit the right subtree.
8. Step 8: Perform Operations

◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
search for a specific value.
Program:

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 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;
}
// Insertion in 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 if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
// Searching in BST
struct Node* search(struct Node* root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return search(root->left, data);
}
return search(root->right, data);
}
// Find the minimum node
struct Node* findMin(struct Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}
// Deletion in BST
struct Node* deleteNode(struct Node* root, int data) {
if (root == NULL) return root;
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);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
// In-order traversal of BST
void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
int main() {
struct Node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the BST: ");
inOrder(root);
printf("\n");
root = deleteNode(root, 20);
printf("Inorder traversal after deletion of 20: ");
inOrder(root);
printf("\n");
struct Node* found = search(root, 70);
if (found) {
printf("Node 70 found in the BST.\n");
} else {
printf("Node 70 not found in the BST.\n");
}
return 0;
}

Output:
Inorder traversal of the BST: 20 30 40 50 60 70 80
Inorder traversal after deletion of 20: 30 40 50 60 70 80
Node 70 found in the BST.

Result:
The above program has been executed successfully and the output is verified.
EX NO: 4(B) IMPLEMENTATION OF AVL TREE

DATE :

Aim:
To write a C program to implement the binary search tree and AVL tree using the following
operations- Insertion, searching, deletion and traversal.

Algorithm:
1. Step 1: Define AVL Node Structure
◦ Create a struct AVLNode with an integer data, two pointers left and right, and an integer
height to store the height of the node.
2. Step 2: Create a New AVL Node

◦ Implement a function createAVLNode(int data) that initializes a new node with data, sets
its left and right pointers to NULL, and assigns the height as 1 (leaf node).
3. Step 3: Insert a Node

◦ Define insertAVL(struct AVLNode* node, int data):


▪ Insert the node in the left subtree if data is smaller, or in the right subtree if data is
larger.
▪ Update the node's height and check the balance factor to ensure the tree remains
balanced.
▪ Perform rotations (left, right, or double rotations) if needed to balance the tree.
4. Step 4: Perform Rotations

◦ Implement rightRotate and leftRotate functions to handle unbalanced cases:


▪ Rotate nodes appropriately to maintain the AVL property during insertion or deletion.
5. Step 5: Get Balance Factor

◦ Define getBalance(struct AVLNode* node) to return the difference in height between the
left and right subtrees.
6. Step 6: Delete a Node

◦ Define deleteAVL(struct AVLNode* root, int data):


▪ Delete the node based on whether it has zero, one, or two children.
▪ Update the height of the remaining nodes and check for balance.
▪ Apply rotations if necessary to maintain AVL balance after deletion.
7. Step 7: In-order Traversal

◦ Implement inOrderAVL(struct AVLNode* root) to recursively traverse and print the tree
in sorted order by visiting the left subtree, current node, and then the right subtree.
8. Step 8: Perform Operations

◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
optionally search for a specific value (e.g., node 70).
Program:

#include <stdio.h>
#include <stdlib.h>
struct AVLNode {
int data;
struct AVLNode* left;
struct AVLNode* right;
int height;
};
int height(struct AVLNode* node) {
if (node == NULL)
return 0;
return node->height;
}
struct AVLNode* createAVLNode(int data) {
struct AVLNode* node = (struct AVLNode*)malloc(sizeof(struct AVLNode));
node->data = data;
node->left = NULL;
node->right = NULL;
node->height = 1; // New node is added at leaf
return node;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
struct AVLNode* rightRotate(struct AVLNode* y) {
struct AVLNode* x = y->left;
struct AVLNode* T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
// Left rotate
struct AVLNode* leftRotate(struct AVLNode* x) {
struct AVLNode* y = x->right;
struct AVLNode* T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
// Get balance factor of node
int getBalance(struct AVLNode* node) {
if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}
// Insert node in AVL tree
struct AVLNode* insertAVL(struct AVLNode* node, int data) {
if (node == NULL)
return createAVLNode(data);
if (data < node->data)
node->left = insertAVL(node->left, data);
else if (data > node->data)
node->right = insertAVL(node->right, data);
else
return node;
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
// Left Left Case
if (balance > 1 && data < node->left->data)
return rightRotate(node);
// Right Right Case
if (balance < -1 && data > node->right->data)
return leftRotate(node);
// Left Right Case
if (balance > 1 && data > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && data < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
// Find the node with the minimum value
struct AVLNode* findMinAVL(struct AVLNode* node) {
while (node->left != NULL)
node = node->left;
return node;
}
// Delete node in AVL tree
struct AVLNode* deleteAVL(struct AVLNode* root, int data) {
if (root == NULL)
return root;
if (data < root->data)
root->left = deleteAVL(root->left, data);
else if (data > root->data)
root->right = deleteAVL(root->right, data);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct AVLNode* temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else {
*root = *temp;
}
free(temp);
} else {
struct AVLNode* temp = findMinAVL(root->right);
root->data = temp->data;
root->right = deleteAVL(root->right, temp->data);
}
}
if (root == NULL)
return root;
root->height = max(height(root->left), height(root->right)) + 1;
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// In-order traversal of AVL tree
void inOrderAVL(struct AVLNode* root) {
if (root != NULL) {
inOrderAVL(root->left);
printf("%d ", root->data);
inOrderAVL(root->right);
}
}
int main() {
struct AVLNode* root = NULL;
root = insertAVL(root, 50);
root = insertAVL(root, 30);
root = insertAVL(root, 20);
root = insertAVL(root, 40);
root = insertAVL(root, 70);
root = insertAVL(root, 60);
root = insertAVL(root, 80);
printf("Inorder traversal of the AVL Tree: ");
inOrderAVL(root);
printf("\n");
root = deleteAVL(root, 20);
printf("Inorder traversal after deletion of 20: ");
inOrderAVL(root);
printf("\n");
struct AVLNode* found = search(root, 70);
if (found) {
printf("Node 70 found in the AVL Tree.\n");
} else {
printf("Node 70 not found in the AVL Tree.\n");
}
return 0;
}
Output:
Inorder traversal of the AVL Tree: 20 30 40 50 60 70 80
Inorder traversal after deletion of 20: 30 40 50 60 70 80
Node 70 found in the AVL Tree.

Result:
The above program has been executed successfully and the output is verified.
EX NO: 5
IMPLEMENTATION OF DFS & BFS ALGORITHM
DATE :

Aim:
To create a C program to implement the DFS and BFS algorithm and set of operations.
1. Finding the shortest path in an unweighted graph, like finding the shortest path
between friends on a social network.2. Navigation through maze.

Algorithm:
1. Step 1: Define AVL Node Structure

◦ Create a struct AVLNode with an integer data, two pointers left and right, and an integer
height to store the height of the node.
2. Step 2: Create a New AVL Node

◦ Implement a function createAVLNode(int data) that initializes a new node with data, sets
its left and right pointers to NULL, and assigns the height as 1 (leaf node).
3. Step 3: Insert a Node

◦ Define insertAVL(struct AVLNode* node, int data):


▪ Insert the node in the left subtree if data is smaller, or in the right subtree if data is
larger.
▪ Update the node's height and check the balance factor to ensure the tree remains
balanced.
▪ Perform rotations (left, right, or double rotations) if needed to balance the tree.
4. Step 4: Perform Rotations

◦ Implement rightRotate and leftRotate functions to handle unbalanced cases:


▪ Rotate nodes appropriately to maintain the AVL property during insertion or deletion.
5. Step 5: Get Balance Factor

◦ Define getBalance(struct AVLNode* node) to return the difference in height between the
left and right subtrees.
6. Step 6: Delete a Node

◦ Define deleteAVL(struct AVLNode* root, int data):


▪ Delete the node based on whether it has zero, one, or two children.
▪ Update the height of the remaining nodes and check for balance.
▪ Apply rotations if necessary to maintain AVL balance after deletion.
7. Step 7: In-order Traversal

◦ Implement inOrderAVL(struct AVLNode* root) to recursively traverse and print the tree
in sorted order by visiting the left subtree, current node, and then the right subtree.
8. Step 8: Perform Operations

◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
optionally search for a specific value (e.g., node 70).
Program:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define INF 9999999
// Structure for graph
struct Graph {
int vertices;
int adj[MAX][MAX]; // Adjacency matrix
};
// Queue structure for BFS
struct Queue {
int items[MAX];
int front, rear;
};
// Stack structure for DFS
struct Stack {
int items[MAX];
int top;
};
// Initialize a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
graph->adj[i][j] = 0;
}
}
return graph;
// Add edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
graph->adj[src][dest] = 1;
graph->adj[dest][src] = 1; // Since the graph is undirected
}
// Initialize the queue for BFS
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
// Check if the queue is empty
int isEmptyQueue(struct Queue* queue) {
return queue->rear == -1;
}
// Enqueue for BFS
void enqueue(struct Queue* queue, int value) {
if (queue->rear == MAX - 1)
return;
else {
if (queue->front == -1)
queue->front = 0;
queue->rear++;
queue->items[queue->rear] = value;
}
}
// Dequeue for BFS
int dequeue(struct Queue* queue) {
int item;
if (isEmptyQueue(queue)) {
return -1;
} else {
item = queue->items[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return item;
}
}
// Initialize stack for DFS
struct Stack* createStack() {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->top = -1;
return stack;
}
// Check if the stack is empty
int isEmptyStack(struct Stack* stack) {
return stack->top == -1;
}
// Push to stack for DFS
void push(struct Stack* stack, int value) {
if (stack->top == MAX - 1)
return;
else {
stack->top++;
stack->items[stack->top] = value;
}
}
// Pop from stack for DFS
int pop(struct Stack* stack) {
if (isEmptyStack(stack))
return -1;
else {
int item = stack->items[stack->top];
stack->top--;
return item;
}
}
// Breadth-First Search (BFS)
void BFS(struct Graph* graph, int startVertex) {
struct Queue* queue = createQueue();
int visited[MAX] = {0}; // Track visited vertices
enqueue(queue, startVertex);
visited[startVertex] = 1;
printf("BFS Traversal: ");
while (!isEmptyQueue(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = 1;
}
}
}
printf("\n");
}
// Depth-First Search (DFS)
void DFS(struct Graph* graph, int startVertex) {
struct Stack* stack = createStack();
int visited[MAX] = {0}; // Track visited vertices
push(stack, startVertex);
visited[startVertex] = 1;
printf("DFS Traversal: ");
while (!isEmptyStack(stack)) {
int currentVertex = pop(stack);
printf("%d ", currentVertex);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
push(stack, i);
visited[i] = 1;
}
}
}
printf("\n");
}
// Find the shortest path in an unweighted graph (using BFS)
void findShortestPath(struct Graph* graph, int startVertex, int targetVertex) {
struct Queue* queue = createQueue();
int visited[MAX] = {0};
int distance[MAX];
int predecessor[MAX];
// Initialize distances and predecessors
for (int i = 0; i < graph->vertices; i++) {
distance[i] = INF;
predecessor[i] = -1;
}
enqueue(queue, startVertex);
visited[startVertex] = 1;
distance[startVertex] = 0;
while (!isEmptyQueue(queue)) {
int currentVertex = dequeue(queue);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = 1;
distance[i] = distance[currentVertex] + 1;
predecessor[i] = currentVertex;
// Stop if we found the target
if (i == targetVertex)
break;
}
}
}
// Print the shortest path
printf("Shortest path from %d to %d is: ", startVertex, targetVertex);
int crawl = targetVertex;
if (predecessor[targetVertex] == -1) {
printf("No path found.\n");
return;
}
printf("%d ", targetVertex);
while (predecessor[crawl] != -1) {
printf("<- %d ", predecessor[crawl]);
crawl = predecessor[crawl];
}
printf("\nPath length: %d\n", distance[targetVertex]); }
// Maze navigation using DFS
void navigateMaze(int maze[MAX][MAX], int size, int startX, int startY, int
endX, int endY) {
struct Stack* stack = createStack();
int visited[MAX][MAX] = {0}; // Track visited cells
int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // Up, Down, Left,
Right
push(stack, startX * size + startY); // Push starting point
visited[startX][startY] = 1;
printf("Navigating the maze using DFS:\n");
while (!isEmptyStack(stack)) {
int pos = pop(stack);
int x = pos / size;
int y = pos % size;
printf("At position (%d, %d)\n", x, y);
if (x == endX && y == endY) {
printf("Reached the goal (%d, %d)\n", endX, endY);
return;
}

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


int newX = x + directions[i][0];
int newY = y + directions[i][1];
if (newX >= 0 && newX < size && newY >= 0 && newY < size &&
maze[newX][newY] == 0 && !visited[newX][newY]) {
push(stack, newX * size + newY);
visited[newX][newY] = 1;
}
}
printf("No path found in the maze.\n”); }
int main() {
// Example graph for BFS and DFS
int vertices = 6;
struct Graph* graph = createGraph(vertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 5);
addEdge(graph, 4, 5);
printf("Example BFS and DFS on Graph:\n");
BFS(graph, 0); // Start BFS from vertex 0
DFS(graph, 0); // Start DFS from vertex 0
// Find the shortest path in the graph
printf("\nFinding shortest path in graph:\n");
findShortestPath(graph, 0, 5); // Find shortest path from vertex 0 to 5
// Maze example (0 represents free path, 1 represents wall)
int maze[MAX][MAX] = {
{0, 1, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 1, 0}
};
int mazeSize = 5;
printf("\nMaze Navigation (using DFS):\n");
navigateMaze(maze, mazeSize, 0, 0, 4, 4); // Start at (0,0), goal at (4,4)
return 0;
}
Output:
Example BFS and DFS on Graph:
BFS Traversal: 0 1 2 3 4 5
DFS Traversal: 0 2 4 5 1 3

Finding shortest path in graph:


Shortest path from 0 to 5 is: 5 <- 3 <- 1 <- 0
Path length: 3

Maze Navigation (using DFS):


Navigating the maze using DFS:
At position (0, 0)
At position (1, 0)
At position (2, 0)
At position (2, 1)
At position (2, 2)
At position (3, 2)
At position (4, 2)
At position (4, 4)
Reached the goal (4, 4)

Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(A)
IMPLEMENTATION OF SORTING STUDENTS GRADE
DATE :

Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.

Algorithm:
1. Step 1: Define Student Structure
◦ Create a struct Student to store student information, which includes a name and
an int for grade.
2. Step 2: Input Student Data
◦ Prompt the user to enter the number of students and their respective names and
grades, storing the information in an array of struct Student.
3. Step 3: Implement Bubble Sort
◦ Define the function bubbleSort(struct Student students[], int n):
▪ Compare adjacent students' grades and swap them if they are out of
order.
▪ Repeat this process to sort the students in ascending order of their grades.
4. Step 4: Display Sorted Students
◦ Implement the function displayStudents(struct Student students[], int n) to print
the sorted list of students along with their grades.
5. Step 5: Implement Binary Search
◦ Define the function binarySearch(struct Student students[], int n, int
targetGrade):
▪ Perform a binary search on the sorted array to find the student with the
target grade.
▪ Return the index of the student if the grade is found, or -1 if not found.
6. Step 6: Search for a Grade
◦ Prompt the user to enter the grade they want to search for and use the
binarySearch function to find the student with that grade.
7. Step 7: Display Search Result
◦ If the grade is found, print the student's name and grade; otherwise, display a
message indicating that the grade was not found.
8. Step 8: Main Function Execution
◦ In the main function, take input for students, sort their grades using bubbleSort,
display the sorted list, and allow the user to search for a specific grade using
Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct Student {
char name[50];
int grade;
};
void bubbleSort(struct Student students[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (students[j].grade > students[j + 1].grade) {
// Swap the students
temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
void displayStudents(struct Student students[], int n) {
printf("\nSorted Students' Grades:\n");
printf("Name\t\tGrade\n");
printf(" --------------------- \n");
for (int i = 0; i < n; i++) {
printf("%-15s %d\n", students[i].name, students[i].grade);
}}
// Binary Search to search for a student's grade
int binarySearch(struct Student students[], int n, int targetGrade) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (students[mid].grade == targetGrade) {
return mid;
} else if (students[mid].grade < targetGrade) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Grade not found
}
int main() {
int n, i, targetGrade, foundIndex;
// Input number of students
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[MAX];
// Input student names and grades
for (i = 0; i < n; i++) {
printf("Enter the name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter the grade of student %d: ", i + 1);
scanf("%d", &students[i].grade);
}
// Sort the students' grades using Bubble Sort
bubbleSort(students, n);
// Display the sorted list of students
displayStudents(students, n);
// Searching for a student's grade using Binary Search
printf("\nEnter the grade to search for: ");
scanf("%d", &targetGrade);
foundIndex = binarySearch(students, n, targetGrade);
if (foundIndex != -1) {
printf("\nGrade %d found for student: %s\n",
students[foundIndex].grade, students[foundIndex].name);
} else {
printf("\nGrade %d not found.\n", targetGrade);
}
return 0;
}
Output:
Input :
Enter the number of students: 5
Enter the name of student 1: Alice
Enter the grade of student 1: 85
Enter the name of student 2: Bob
Enter the grade of student 2: 92
Enter the name of student 3: Charlie
Enter the grade of student 3: 78
Enter the name of student 4: David
Enter the grade of student 4: 95
Enter the name of student 5: Eve
Enter the grade of student 5: 88

Output:
Sorted Students' Grades:
Name Grade

Charlie 78
Alice 85
Eve 88
Bob 92
David 95

Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(B)
IMPLEMENTATION OF E-COMMERCE
DATE :

Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.

Algorithm:
1. Step 1: Define Product Structure
◦ Create a struct Product to store product information, which includes a name (string) and
price (float).
2. Step 2: Input Product Data

◦ Prompt the user to enter the number of products and their respective names and prices.
Store this information in an array of struct Product.
3. Step 3: Implement Bubble Sort

◦ Define the function bubbleSort(struct Product products[], int n):


▪ Compare adjacent products' prices and swap them if they are out of order.
▪ Repeat this process to sort the products in ascending order of their prices.
4. Step 4: Display Sorted Products

◦ Implement the function displayProducts(struct Product products[], int n) to print the


sorted list of products with their respective names and prices.
5. Step 5: Implement Linear Search

◦ Define the function linearSearch(struct Product products[], int n, char* targetName):


▪ Traverse the array of products and compare the target name with each product's
name.
▪ Return the index of the product if the name is found or -1 if not found.
6. Step 6: Search for a Product

◦ Prompt the user to enter the name of the product they want to search for, and use the
linearSearch function to find the product.
7. Step 7: Display Search Result

◦ If the product is found, print its name and price; otherwise, display a message indicating
that the product was not found.
8. Step 8: Main Function Execution

◦ In the main function, take input for the products, sort their prices using bubbleSort,
display the sorted list, and allow the user to search for a specific product by name using
linear search.
◦ binary search.
Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PRODUCTS 100
// Structure to represent a product
struct Product {
char name[50];
float price;
};
// Function to perform Bubble Sort on products by price
void bubbleSort(struct Product products[], int n) {
int i, j;
struct Product temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (products[j].price > products[j + 1].price) {
// Swap products
temp = products[j];
products[j] = products[j + 1];
products[j + 1] = temp;
}
}
}
}
// Function to display all products
void displayProducts(struct Product products[], int n) {
printf("\nProducts List:\n");
printf("Name\t\tPrice\n");
printf(" --------------------- \n");
for (int i = 0; i < n; i++) {
printf("%-15s %.2f\n", products[i].name, products[i].price);
}
}
// Function to search for a product by name using Linear Search
int linearSearch(struct Product products[], int n, char* targetName) {
for (int i = 0; i < n; i++) {
if (strcmp(products[i].name, targetName) == 0) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int n, foundIndex;
char targetName[50];

// Input the number of products


printf("Enter the number of products: ");
scanf("%d", &n);
struct Product products[MAX_PRODUCTS];
// Input product names and prices
for (int i = 0; i < n; i++) {
printf("Enter the name of product %d: ", i + 1);
scanf("%s", products[i].name);
printf("Enter the price of product %d: ", i + 1);
scanf("%f", &products[i].price);
}
// Sort the products by price
bubbleSort(products, n);
// Display the sorted list of products
displayProducts(products, n);
// Searching for a product by name
printf("\nEnter the name of the product to search for: ");
scanf("%s", targetName);
foundIndex = linearSearch(products, n, targetName);
if (foundIndex != -1) {
printf("\nProduct found: %s with price %.2f\n",
products[foundIndex].name, products[foundIndex].price);
} else {
printf("\nProduct '%s' not found.\n", targetName);
}
return 0;
}
Output:
Input:
Enter the number of products: 5
Enter the name of product 1: Laptop
Enter the price of product 1: 999.99
Enter the name of product 2: Mouse
Enter the price of product 2: 25.50
Enter the name of product 3: Keyboard
Enter the price of product 3: 45.99
Enter the name of product 4: Monitor
Enter the price of product 4: 199.99
Enter the name of product 5: Headphones
Enter the price of product 5: 79.99

Output:
Products List:
Name Price

Mouse 25.50
Keyboard 45.99
Headphones 79.99
Monitor 199.99
Laptop 999.99

Enter the name of the product to search for: Headphones

Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(C) IMPLEMENTATION OF LIBRARY SYSTEMS

DATE :

Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.

Algorithm:
1. Step 1: Define Book Structure
◦ Create a struct Book to store book information, including title, author, and year.
2. Step 2: Input Book Details

◦ Prompt the user to enter the number of books and their respective titles, authors, and
publication years. Store this data in an array of struct Book.
3. Step 3: Implement Bubble Sort

◦ Define the function bubbleSort(struct Book books[], int n):


▪ Compare the titles of adjacent books.
▪ If a book title is lexicographically greater than the next one, swap them.
▪ Repeat this process to sort the books in ascending order by title.
4. Step 4: Display Sorted Books

◦ Implement the function displayBooks(struct Book books[], int n) to print the sorted list
of books, including their titles, authors, and publication years.
5. Step 5: Implement Linear Search

◦ Define the function linearSearch(struct Book books[], int n, char* targetTitle):


▪ Traverse the array and compare each book's title with the target title.
▪ Return the index of the book if found or -1 if not found.
6. Step 6: Search for a Book

◦ Prompt the user to enter the title of the book they want to search for, and use the
linearSearch function to find the book.
7. Step 7: Display Search Result

◦ If the book is found, print its title, author, and publication year; otherwise, display a
message indicating that the book was not found.
8. Step 8: Main Function Execution

◦ In the main function, take input for the books, sort their titles using bubbleSort, display
the sorted list, and allow the user to search for a specific book by title using linear
search.
Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
// Structure to represent a book
struct Book {
char title[100];
char author[100];
int year;
};
// Function to perform Bubble Sort on books by title
void bubbleSort(struct Book books[], int n) {
int i, j;
struct Book temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (strcmp(books[j].title, books[j + 1].title) > 0) {
// Swap books
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
// Function to display all books
void displayBooks(struct Book books[], int n) {
printf("\nLibrary Books:\n");
printf("Title\t\t\tAuthor\t\tYear\n");
printf(" ------------------------------------------ \n");
for (int i = 0; i < n; i++) {
printf("%-20s %-20s %d\n", books[i].title, books[i].author,
books[i].year);
}
}
// Function to search for a book by title using Linear Search
int linearSearch(struct Book books[], int n, char* targetTitle) {
for (int i = 0; i < n; i++) {
if (strcmp(books[i].title, targetTitle) == 0) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int n, foundIndex;
char targetTitle[100];
// Input the number of books
printf("Enter the number of books: ");
scanf("%d", &n);
getchar(); // To consume the newline character after the number input
struct Book books[MAX_BOOKS];
// Input book details
for (int i = 0; i < n; i++) {
printf("Enter the title of book %d: ", i + 1);
fgets(books[i].title, sizeof(books[i].title), stdin);
books[i].title[strcspn(books[i].title, "\n")] = 0; // Remove newline
character
printf("Enter the author of book %d: ", i + 1);
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = 0; // Remove newline
character
printf("Enter the year of publication of book %d: ", i + 1);
scanf("%d", &books[i].year);
getchar(); // To consume the newline character after the year input
}
// Sort the books by title
bubbleSort(books, n);
// Display the sorted list of books
displayBooks(books, n);
// Searching for a book by title
printf("\nEnter the title of the book to search for: ");
fgets(targetTitle, sizeof(targetTitle), stdin);
targetTitle[strcspn(targetTitle, "\n")] = 0; // Remove newline character
foundIndex = linearSearch(books, n, targetTitle);
if (foundIndex != -1) {
printf("\nBook found: %s by %s (%d)\n", books[foundIndex].title,
books[foundIndex].author, books[foundIndex].year);
} else {
printf("\nBook '%s' not found in the library.\n", targetTitle);
}
return 0;
}
Output:
Input:
Enter the number of books: 3
Enter the title of book 1: The Great Gatsby
Enter the author of book 1: F. Scott Fitzgerald
Enter the year of publication of book 1: 1925
Enter the title of book 2: To Kill a Mockingbird
Enter the author of book 2: Harper Lee
Enter the year of publication of book 2: 1960
Enter the title of book 3: 1984
Enter the author of book 3: George Orwell
Enter the year of publication of book 3: 1949

Output:
Library Books:
Title Author Year

1984 George Orwell 1949


The Great Gatsby F. Scott Fitzgerald 1925
To Kill a Mockingbird Harper Lee 1960

Enter the title of the book to search for: 1984

Book found: 1984 by George Orwell (1949)


Product found: Headphones with price 79.99

Result:
The above program has been executed successfully and the output is verified.
EX NO: 7
IMPLEMENTATION OF EMPLOYEE SALARY
DATE :

Aim:

To write a C program to sort a list of employees by their salary in ascending order


using Bubble Sort.

Algorithm:
1. Step 1 : Define Employee Structure
o Create a struct Employee with fields: name, id, and salary.
2. Step 2 : Input Employee Data
o Prompt the user to enter the number of employees, and accept each employee's ID,
name, and salary.
3. Step 3 : Implement Bubble Sort
o Define the function bubbleSort(struct Employee emp[], int n) that:
 Compares adjacent employees' salaries.
 Swaps them if they are out of order.
 Repeats the process to sort in ascending order.
4. Step 4 : Display Sorted Employee List
o Define the function displayEmployees(struct Employee emp[], int n) to print the
sorted employee records.
5. Step 5 : Main Function Execution
o In main(), call input, sorting, and display functions in sequence.
Program :

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

#define MAX 100

// Employee structure
struct Employee {
char name[50];
int id;
float salary;
};

// Bubble Sort function


void bubbleSort(struct Employee emp[], int n) {
struct Employee temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (emp[j].salary > emp[j + 1].salary) {
// Swap
temp = emp[j];
emp[j] = emp[j + 1];
emp[j + 1] = temp;
}
}
}
}

// Display function
void displayEmployees(struct Employee emp[], int n) {
printf("\nSorted Employee List by Salary (Ascending):\n");
printf("ID\tName\t\tSalary\n");
printf("--------------------------------------\n");
for (int i = 0; i < n; i++) {
printf("%d\t%-15s %.2f\n", emp[i].id, emp[i].name, emp[i].salary);
}
}
// Main function
int main() {
int n;
struct Employee emp[MAX];

// Input number of employees


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

// Input employee details


for (int i = 0; i < n; i++) {
printf("\nEnter details of employee %d:\n", i + 1);
printf("ID: ");
scanf("%d", &emp[i].id);
printf("Name: ");
scanf("%s", emp[i].name);
printf("Salary: ");
scanf("%f", &emp[i].salary);
}
// Sort using Bubble Sort
bubbleSort(emp, n);

// Display sorted employees


displayEmployees(emp, n);

return 0;
}
Output :
Input :
Enter the number of employees: 3
Enter details of employee 1:
ID: 101
Name: Alice
Salary: 50000
Enter details of employee 2:
ID: 102
Name: Bob
Salary: 45000
Enter details of employee 3:
ID: 103
Name: Charlie
Salary: 60000

Output :
Sorted Employee List by Salary (Ascending):
ID Name Salary
--------------------------------------
102 Bob 45000.00
101 Alice 50000.00
103 Charlie 60000.00

Result:
The above C program for sorting employee records based on salary using
Bubble Sort has been successfully executed and verified with correct output.
EX NO: 8
Implementation of Hashing and Collision Resolution
DATE :

Aim:
To implementation of Hashing and Collision Resolution Techniques.Separate chaining
program using Hash technique .

Algorithm:
1. Step 1: Define Node Structure

◦ Create a struct Node to represent each entry in the hash table.


◦ Each node contains a key and a pointer next to the next node in case of collisions.
2. Step 2: Define Hash Table Structure

◦ Create a struct HashTable that contains an array of linked lists (struct Node** table),
which will hold keys based on the hash index.
3. Step 3: Create Hash Table

◦ Define the createHashTable() function to initialize the hash table:


▪ Allocate memory for the hash table and for the array of pointers to nodes.
▪ Initialize each bucket to NULL to indicate empty slots.
4. Step 4: Hash Function

◦ Create a simple hash function hash(int key) that returns the modulus of the key by the table
size. This will determine the index where the key is placed.
5. Step 5: Insert Keys into the Hash Table

◦ Define the insert(struct HashTable* ht, int key) function:


▪ Compute the hash index using the key.
▪ If the corresponding bucket is empty, create a new node and insert it.
▪ If there is a collision (i.e., the bucket already contains a node), use separate chaining
by traversing the linked list and adding the new node at the end.
6. Step 6: Search for a Key

◦ Implement the search(struct HashTable* ht, int key) function:


▪ Compute the hash index of the key and search the linked list at that index.
▪ Return 1 if the key is found, otherwise return 0.
7. Step 7: Delete a Key

◦ Define the delete(struct HashTable* ht, int key) function:


▪ Search for the key in the corresponding linked list.
▪ If found, unlink the node and free its memory.
▪ Print a message indicating whether the key was found and deleted.
8. Step 8: Display the Hash Table

◦ Implement the display(struct HashTable* ht) function to show all buckets of the hash
table.
◦ For each bucket, display the keys and their connections (using -> to indicate the linked list
structure).
Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
// Structure to represent a node in the linked list
struct Node {
int key;
struct Node* next;
};

// Structure to represent the hash table


struct HashTable {
struct Node** table;
};
// Function to create a hash table
struct HashTable* createHashTable() {
struct HashTable* ht = malloc(sizeof(struct HashTable));
ht->table = malloc(TABLE_SIZE * sizeof(struct Node*));

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


ht->table[i] = NULL; // Initialize all buckets to NULL
}
return ht;
}
// Hash function
int hash(int key) {
return key % TABLE_SIZE; // Simple modulus-based hash function
}
// Function to insert a key into the hash table
void insert(struct HashTable* ht, int key) {
int index = hash(key);
struct Node* newNode = malloc(sizeof(struct Node));
newNode->key = key;
newNode->next = NULL;
// If the bucket is empty, add the new node
if (ht->table[index] == NULL) {
ht->table[index] = newNode;
} else {
// Collision resolution: separate chaining
struct Node* current = ht->table[index];
while (current->next != NULL) {
current = current->next; // Move to the end of the list
}
current->next = newNode; // Add the new node at the end
}
}
// Function to search for a key in the hash table
int search(struct HashTable* ht, int key) {
int index = hash(key);
struct Node* current = ht->table[index];
while (current != NULL) {
if (current->key == key) {
return 1; // Key found
}
current = current->next; // Move to the next node
}
return 0; // Key not found
}
// Function to delete a key from the hash table
void delete(struct HashTable* ht, int key) {
int index = hash(key);
struct Node* current = ht->table[index];
struct Node* previous = NULL;
while (current != NULL) {
if (current->key == key) {
if (previous == NULL) {
// Node to delete is the first node in the list
ht->table[index] = current->next;
} else {
// Bypass the current node
previous->next = current->next;
}
free(current); // Free the memory
printf("Deleted key %d from hash table.\n", key);
return;
}
previous = current;
current = current->next; // Move to the next node
}
printf("Key %d not found in hash table.\n", key);
}
// Function to display the hash table
void display(struct HashTable* ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
printf("Bucket %d: ", i);
struct Node* current = ht->table[i];
while (current != NULL) {
printf("%d -> ", current->key);
current = current->next;
}
printf("NULL\n");
}
}
// Function to free the hash table
void freeHashTable(struct HashTable* ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
struct Node* current = ht->table[i];
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
}
free(ht->table);
free(ht);
}
int main() {
struct HashTable* ht = createHashTable();
// Inserting keys
insert(ht, 5);
insert(ht, 15);
insert(ht, 25);
insert(ht, 35);
insert(ht, 12);
insert(ht, 22);
// Displaying the hash table
display(ht);
// Searching for keys
printf("Searching for key 15: %s\n", search(ht, 15) ? "Found" : "Not Found");
printf("Searching for key 99: %s\n", search(ht, 99) ? "Found" : "Not Found");
// Deleting a key
delete(ht, 15);
display(ht);
// Free the allocated memory
freeHashTable(ht);
return 0;
}
Output:
Bucket 0: NULL
Bucket 1: NULL
Bucket 2: NULL
Bucket 3: NULL
Bucket 4: NULL
Bucket 5: 5 -> 15 -> 25 -> NULL
Bucket 6: NULL
Bucket 7: NULL
Bucket 8: 12 -> NULL
Bucket 9: 22 -> 35 -> NULL
Searching for key 15: Found
Searching for key 99: Not Found
Deleted key 15 from hash table.
Bucket 0: NULL
Bucket 1: NULL
Bucket 2: NULL
Bucket 3: NULL
Bucket 4: NULL
Bucket 5: 5 -> 25 -> NULL
Bucket 6: NULL
Bucket 7: NULL
Bucket 8: 12 -> NULL
Bucket 9: 22 -> 35 -> NULL

Result:
The above program has been executed successfully and the output is verified.
EX NO : 9
Display the Length of the Longest and Shortest
DATE : Chains in a Hash Table

Aim:

To write a C program that implements a hash table using separate chaining, and
displays the lengths of the longest and shortest chains after multiple insertions.

Algorithm:

1. Define Node Structure


o Create struct Node to hold a key and a next pointer (for chaining).
2. Create Hash Table Structure
o Define struct HashTable with an array of node pointers (linked lists).
3. Hash Function
o Use a simple hash function: index = key % TABLE_SIZE.
4. Insert Function
o Implement insert(struct HashTable* ht, int key):
 Compute the index using hash.
 Add the key at the end of the corresponding chain.
5. Display Function
o Show all keys in each bucket for visual understanding.
6. Chain Length Functions

Implement getChainLengths(struct HashTable* ht, int* min, int* max):

 Traverse all chains.


 Count number of nodes in each.
 Track maximum and minimum chain lengths.
7. Main Function
o Insert multiple values.
o Display the hash table.
o Call function to display longest and shortest chain lengths.
Program :

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

#define TABLE_SIZE 10

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

// HashTable structure
struct HashTable {
struct Node** table;
};

// Create hash table


struct HashTable* createHashTable() {
struct HashTable* ht = malloc(sizeof(struct HashTable));
ht->table = malloc(TABLE_SIZE * sizeof(struct Node*));
for (int i = 0; i < TABLE_SIZE; i++) {
ht->table[i] = NULL;
}
return ht;
}

// Hash function
int hash(int key) {
return key % TABLE_SIZE;
}

// Insert key into hash table


void insert(struct HashTable* ht, int key) {
int index = hash(key);
struct Node* newNode = malloc(sizeof(struct Node));
newNode->key = key;
newNode->next = NULL;
if (ht->table[index] == NULL) {
ht->table[index] = newNode;
} else {
struct Node* current = ht->table[index];
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
}

// Display hash table


void display(struct HashTable* ht) {
printf("\nHash Table:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
printf("Bucket %d: ", i);
struct Node* current = ht->table[i];
while (current != NULL) {
printf("%d -> ", current->key);
current = current->next;
}
printf("NULL\n");
}
}

// Function to get min and max chain lengths


void getChainLengths(struct HashTable* ht, int* min, int* max) {
*min = -1;
*max = 0;
for (int i = 0; i < TABLE_SIZE; i++) {
int length = 0;
struct Node* current = ht->table[i];
while (current != NULL) {
length++;
current = current->next;
}
if (length > *max)
*max = length;
if ((length < *min || *min == -1) && length > 0)
*min = length;
}
}
// Free memory
void freeHashTable(struct HashTable* ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
struct Node* current = ht->table[i];
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
}
free(ht->table);
free(ht);
}

// Main function
int main() {
struct HashTable* ht = createHashTable();

// Insert multiple values


int keys[] = {5, 15, 25, 35, 45, 8, 18, 28, 38, 48, 3, 13, 23};
int size = sizeof(keys) / sizeof(keys[0]);

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


insert(ht, keys[i]);
}

// Display hash table


display(ht);

// Calculate chain lengths


int min, max;
getChainLengths(ht, &min, &max);
printf("\nLength of Shortest Chain: %d\n", min);
printf("Length of Longest Chain: %d\n", max);

// Clean up
freeHashTable(ht);
return 0;
}
Output :
Hash Table:
Bucket 0: NULL
Bucket 1: NULL
Bucket 2: NULL
Bucket 3: 3 -> 13 -> 23 -> NULL
Bucket 4: NULL
Bucket 5: 5 -> 15 -> 25 -> 35 -> 45 -> NULL
Bucket 6: NULL
Bucket 7: NULL
Bucket 8: 8 -> 18 -> 28 -> 38 -> 48 -> NULL
Bucket 9: NULL

Length of Shortest Chain: 3


Length of Longest Chain: 5

Result :
The above C program was successfully executed. It correctly calculated and
displayed the length of the shortest and longest chains in the hash table using
separate chaining after multiple insertions.

You might also like