Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Structures Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

KARNATAKA STATE OPEN UNIVERSITY

MUKTHAGANGOTHRI, MYSURU-06

MCADSC 1.4: DATA STRUCTURES LAB


1. Write a C program to calculate the sum of array
#include <stdio.h>
int main()
{
// Declare an array
int arr[] = {1, 2, 3, 4, 5};

// Calculate the size of the array


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

// Initialize sum to 0
int sum = 0;

// Iterate through the array and calculate the sum


for (int i = 0; i < size; ++i) {
sum += arr[i];
}
// Display the sum
printf("Sum of elements in the array: %d\n", sum);
return 0;
}

OUTPUT
Sum of elements in the array: 15
2. Write a C Program to implement an array and perform basic operations (insertion, deletion,
traversal).

#include <stdio.h>

// Function to display the elements of the array


void displayArray(int arr[], int size)
{
printf("Array elements: ");
for (int i = 0; i < size; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to insert an element at a given position in the array
int insertElement(int arr[], int *size, int position, int element)
{
if (position < 0 || position > *size)
{
printf("Invalid position for insertion.\n");
return *size;
}
// Shift elements to make space for the new element
for (int i = *size - 1; i >= position; --i)
{
arr[i + 1] = arr[i];
}
// Insert the new element
arr[position] = element;
return ++*size;
}
// Function to delete an element at a given position from the array
int deleteElement(int arr[], int *size, int position)
{
if (position < 0 || position >= *size)
{
printf("Invalid position for deletion.\n");
return *size;
}
// Shift elements to fill the gap left by the deleted element
for (int i = position; i < *size - 1; ++i)
{
arr[i] = arr[i + 1];
}
return --*size;
}

int main()
{
// Declare an array
int myArray[10] = {1, 2, 3, 4, 5};
int arraySize = 5; // Initial size of the array
// Display the original array
displayArray(myArray, arraySize);

// Insert an element at position 2


arraySize = insertElement(myArray, &arraySize, 2, 10);
displayArray(myArray, arraySize);

// Delete the element at position 3


arraySize = deleteElement(myArray, &arraySize, 3);
displayArray(myArray, arraySize);

return 0;
}

OUTPUT
Array elements: 1 2 3 4 5
Array elements: 1 2 10 3 4 5
Array elements: 1 2 10 4 5
3. Write a C Program to implement Singly linked list
#include <stdio.h>
#include <stdlib.h>

// Structure representing 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));
if (newNode == NULL)
{
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

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


void insertAtBeginning(struct Node** head, int data)
{
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}

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


void insertAtEnd(struct Node** head, int data)
{
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}

temp->next = newNode;
}

// Function to delete a node with a given value from the singly linked list
void deleteNode(struct Node** head, int key)
{
if (*head == NULL)
{
printf("List is empty. Deletion failed.\n");
return;
}

struct Node* current = *head;


struct Node* prev = NULL;

// Search for the node to be deleted


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

// If the node is not found


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

// Update the pointers to bypass the node to be deleted


if (prev == NULL)
{
// If the node to be deleted is the first node
*head = current->next;
}
else {
prev->next = current->next;
}

// Free the memory of the deleted node


free(current);
}

// Function to display the singly linked list


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

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

do {
// Display menu
printf("\nSingly Linked List Operations:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Delete a node\n");
printf("4. Display the list\n");
printf("5. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
// Input: Get the data to insert at the beginning
printf("Enter the data to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
// Input: Get the data to insert at the end
printf("Enter the data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;

case 3:
// Input: Get the data to delete
printf("Enter the data to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;

case 4:
displayList(head);
break;

case 5:
printf("Quitting the program.\n");
break;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 5);

return 0;
}

OUTPUT
Singly Linked List Operations:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 1
Enter the data to insert at the beginning: 16

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice:
1
Enter the data to insert at the beginning: 18

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 1
Enter the data to insert at the beginning: 21

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 2
Enter the data to insert at the end: 25

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 4
Singly Linked List: 21 18 16 25

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 3
Enter the data to delete: 21

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice: 4
Singly Linked List: 18 16 25

Singly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Quit
Enter your choice:
4. Write a C Program to implement a doubly linked list and perform relevant operations
#include <stdio.h>
#include <stdlib.h>

// Structure representing 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));
if (newNode == NULL)
{
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

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


void insertAtBeginning(struct Node** head, int data)
{
struct Node* newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
}
else
{
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
}
}
// Function to insert a node at the end of the doubly linked list
void insertAtEnd(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;
newNode->prev = temp;
}
}

// Function to delete a node with a given value from the doubly linked list
void deleteNode(struct Node** head, int key)
{
if (*head == NULL)
{
printf("List is empty. Deletion failed.\n");
return;
}

struct Node* current = *head;


struct Node* prev = NULL;

// Search for the node to be deleted


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

// If the node is not found


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

// Update the pointers to bypass the node to be deleted


if (prev == NULL)
{
// If the node to be deleted is the first node
*head = current->next;
}
else {
prev->next = current->next;
if (current->next != NULL)
{
current->next->prev = prev;
}
}

// Free the memory of the deleted node


free(current);
}

// Function to display the doubly linked list


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

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

do {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Delete a node by value\n");
printf("4. Display the list\n");
printf("5. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter data to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;

case 2:
printf("Enter data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;

case 3:
printf("Enter the value of the node to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;

case 4:
displayList(head);
break;

case 5:
printf("Quitting the program.\n");
break;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 5);

return 0;
}
OUTPUT

Doubly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node by value
4. Display the list
5. Quit
Enter your choice: 4
Doubly Linked List:

Doubly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node by value
4. Display the list
5. Quit
Enter your choice: 1
Enter data to insert at the beginning: 12

Doubly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node by value
4. Display the list
5. Quit
Enter your choice: 1
Enter data to insert at the beginning: 13

Doubly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node by value
4. Display the list
5. Quit
Enter your choice: 1
Enter data to insert at the beginning: 14

Doubly Linked List Operations:


1. Insert at the beginning
2. Insert at the end
3. Delete a node by value
4. Display the list
5. Quit
Enter your choice: 4
Doubly Linked List: 14 13 12
5. Write a program to calculate factorial of a given number using recursive function
#include<stdio.h>
long int fact(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, fact(n));
return 0;
}
long int fact(int n)
{
if (n>=1)
return n*fact(n-1);
else
return 1;
}
OUTPUT
Enter a positive integer: 5
Factorial of 5 = 120
6. Write a C Program to implement the binary search algorithm
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
OUTPUT
Enter number of elements
5
Enter 5 integers
12
15
98
56
78
Enter value to find
15
15 found at location 2
7. Write a C program to implement linear search technique

#include <stdio.h>

// Function to perform linear search


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

int main()
{
int size, key;
int arr[size];
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; ++i)
{
scanf("%d", &arr[i]);
}
printf("Enter the number to search: ");
scanf("%d", &key);

// function call to perfrom linear search


int index = linearSearch(arr, size, key);

// function call to Display the result


if (index != -1)
{
printf("Number %d found at index %d.\n", key, index);
}
else
{
printf("Number %d not found in the list.\n", key);
}

return 0;
}

OUTPUT
Enter the size of the array: 5
Enter 5 elements:
23
45
67
89
34
Enter the number to search: 23
Number 23 found at index 0.

Enter the size of the array:


5
Enter 5 elements:
23
45
67
89
34
Enter the number to search: 88
Number 88 not found in the list.
8. Write a C Program to implement stack operations
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5

// Structure representing the stack


struct Stack
{
int items[MAX_SIZE];
int top;
};

// Function to initialize the stack


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

// Function to check if the stack is empty


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

// Function to check if the stack is full


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

// Function to push an element onto the stack


void push(struct Stack *s, int value)
{
if (isFull(s))
{
printf("Stack Overflow: Cannot push %d, stack is full.\n", value);
}
else
{
s->items[++s->top] = value;
printf("Pushed %d onto the stack.\n", value);
}
}

// Function to pop an element from the stack


int pop(struct Stack *s)
{
if (isEmpty(s))
{
printf("Stack Underflow: Cannot pop from an empty stack.\n");
return -1; // Return a special value to indicate underflow
}
else
{
printf("Popped %d from the stack.\n", s->items[s->top]);
return s->items[s->top--];
}
}

// Function to display the elements in the stack


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

int main()
{
// Create a stack
struct Stack myStack;
// Initialize the stack
initialize(&myStack);

int choice, element;

do {
// Display menu
printf("\nStack Operations:\n");
printf("1. Push an element\n");
printf("2. Pop an element\n");
printf("3. Display the stack\n");
printf("4. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
// Input: Get the element to push
printf("Enter the element to push: ");
scanf("%d", &element);
push(&myStack, element);
break;

case 2:
pop(&myStack);
break;

case 3:
display(&myStack);
break;

case 4:
printf("Quitting the program.\n");
break;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
}
while (choice != 4);
return 0;
}

OUTPUT
Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 3
Stack is empty.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 1
Enter the element to push: 12
Pushed 12 onto the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 1
Enter the element to push: 13
Pushed 13 onto the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 1
Enter the element to push: 14
Pushed 14 onto the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 1
Enter the element to push: 15
Pushed 15 onto the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 1
Enter the element to push: 16
Pushed 16 onto the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice:
1
Enter the element to push: 17
Stack Overflow: Cannot push 17, stack is full.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 3
Stack elements: 12 13 14 15 16

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice: 2
Popped 16 from the stack.

Stack Operations:
1. Push an element
2. Pop an element
3. Display the stack
4. Quit
Enter your choice:
9. Write a C Program to implement Queue operations
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5

// Structure representing the queue


struct Queue
{
int items[MAX_SIZE];
int front, rear;
};

// Function to initialize the queue


void initialize(struct Queue *q)
{
q->front = -1;
q->rear = -1;
}

// Function to check if the queue is empty


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

// Function to check if the queue is full


int isFull(struct Queue *q)
{
return (q->rear + 1) % MAX_SIZE == q->front;
}

// Function to enqueue an element


void enqueue(struct Queue *q, int value)
{
if (isFull(q))
{
printf("Queue Overflow: Cannot enqueue %d, queue is full.\n", value);
}
else
{
if (isEmpty(q))
{
q->front = 0; // Set front to 0 when enqueuing into an empty queue
}
q->rear = (q->rear + 1) % MAX_SIZE;
q->items[q->rear] = value;
printf("Enqueued %d into the queue.\n", value);
}
}

// Function to dequeue an element


int dequeue(struct Queue *q)
{
int dequeuedValue = -1; // Default value for underflow
if (isEmpty(q))
{
printf("Queue Underflow: Cannot dequeue from an empty queue.\n");
}
else
{
dequeuedValue = q->items[q->front];
if (q->front == q->rear)
{
initialize(q); // Reset the queue when dequeuing the last element
}
else
{
q->front = (q->front + 1) % MAX_SIZE;
}
printf("Dequeued %d from the queue.\n", dequeuedValue);
}

return dequeuedValue;
}

// Function to display the elements in the queue


void display(struct Queue *q)
{
if (isEmpty(q))
{
printf("Queue is empty.\n");
}
else
{
printf("Queue elements: ");
int i = q->front;
do
{
printf("%d ", q->items[i]);
i = (i + 1) % MAX_SIZE;
}
while (i != (q->rear + 1) % MAX_SIZE);
printf("\n");
}
}

int main()
{
// Create a queue using structure variable
struct Queue myQueue;

// Initialize the queue


initialize(&myQueue);

int choice, element;

do {
// Display menu
printf("\nQueue Operations:\n");
printf("1. Enqueue an element\n");
printf("2. Dequeue an element\n");
printf("3. Display the queue\n");
printf("4. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
// Input: Get the element to enqueue
printf("Enter the element to enqueue: ");
scanf("%d", &element);
enqueue(&myQueue, element);
break;
case 2:
dequeue(&myQueue);
break;

case 3:
display(&myQueue);
break;

case 4:
printf("Quit the program.\n");
break;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 4);

return 0;
}

OUTPUT
Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue: 12
Enqueued 12 into the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue: 13
Enqueued 13 into the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue: 14
Enqueued 14 into the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue: 15
Enqueued 15 into the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue: 16
Enqueued 16 into the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 3
Queue elements: 12 13 14 15 16

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 1
Enter the element to enqueue:
17
Queue Overflow: Cannot enqueue 17, queue is full.
Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 2
Dequeued 12 from the queue.

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice: 3
Queue elements: 13 14 15 16

Queue Operations:
1. Enqueue an element
2. Dequeue an element
3. Display the queue
4. Quit
Enter your choice:
10. Write a C Program to implement bubble sort algorithm
#include <stdio.h>

// Function to perform bubble sort


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

// Function to display an array


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

int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[]=n;
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}

// function call to Perform bubble sort


bubbleSort(arr, n);

// function call to Display the sorted array


displayArray(arr, n);

return 0;
}

OUTPUT

Enter the number of elements: 4


Enter 4 elements:
56
21
45
99
Sorted Array: 21 45 56 99
11. Write a C Program to implement quick sort algorithm
#include <stdio.h>

// Function to partition the array and return the pivot index


int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = low - 1;

for (int j = low; j <= high - 1; ++j)


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

// Swap arr[i + 1] and arr[high] (put the pivot in its correct position)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1; // Return the pivot index


}

// Function to perform quicksort


void quickSort(int arr[], int low, int high)
{
if (low < high)
{
// Find pivot such that elements smaller than pivot are on the left
// and elements greater than pivot are on the right
int pivotIndex = partition(arr, low, high);

// Recursively sort sub-arrays


quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
// Function to display an array
void displayArray(int arr[], int n)
{
printf("Sorted Array: ");
for (int i = 0; i < n; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
}

int main()
{
int n;
int arr[n];
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}

// function call to quicksort


quickSort(arr, 0, n - 1);

// function call to Display the sorted array


displayArray(arr, n);

return 0;
}
OUTPUT
Enter the number of elements: 5
Enter 5 elements:
12
67
10
28
121
Sorted Array: 10 12 28 67 121
12. Write a C Program to implement depth-first search (DFS) ) traversal on a graph

#include <stdio.h>
#define MAX_VERTICES 100

// Function to perform Depth-First Search (DFS) traversal


void DFS(int graph[MAX_VERTICES][MAX_VERTICES], int visited[MAX_VERTICES], int vertices,
int start)
{
printf("%d ", start); // Print the current vertex
visited[start] = 1; // Mark the current vertex as visited

// Visit all adjacent vertices


for (int i = 0; i < vertices; i++)
{
if (graph[start][i] == 1 && !visited[i])
{
DFS(graph, visited, vertices, i);
}
}
}

int main()
{
int vertices, edges;

// Input the number of vertices


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

if (vertices <= 0 || vertices > MAX_VERTICES)


{
printf("Invalid number of vertices. Exiting...\n");
return 1;
}

int graph[MAX_VERTICES][MAX_VERTICES] = {0}; // Initialize the adjacency matrix with zeros


int visited[MAX_VERTICES] = {0}; // Initialize the visited array with zeros

// Input the number of edges


printf("Enter the number of edges: ");
scanf("%d", &edges);
if (edges < 0 || edges > vertices * (vertices - 1))
{
printf("Invalid number of edges. Exiting...\n");
return 1;
}

// Input edges and construct the adjacency matrix


for (int i = 0; i < edges; i++)
{
int start, end;
printf("Enter edge %d (start end): ", i + 1);
scanf("%d %d", &start, &end);

// Validate input vertices


if (start < 0 || start >= vertices || end < 0 || end >= vertices)
{
printf("Invalid vertices. Try again.\n");
i--;
continue;
}

graph[start][end] = 1;
// For undirected graph, uncomment the following line:
// graph[end][start] = 1;
}

// Input the starting vertex for DFS traversal


int startVertex;
printf("Enter the starting vertex for DFS traversal: ");
scanf("%d", &startVertex);

if (startVertex < 0 || startVertex >= vertices) {


printf("Invalid starting vertex. Exiting...\n");
return 1;
}

printf("DFS Traversal Order: ");


DFS(graph, visited, vertices, startVertex);

return 0;
}
OUTPUT

Enter the number of vertices: 5


Enter the number of edges: 6
Enter edge 1 (start end): 0 1
Enter edge 2 (start end): 1 2
Enter edge 3 (start end): 2 3
Enter edge 4 (start end): 3 4
Enter edge 5 (start end): 4 0
Enter edge 6 (start end): 2 4

Enter the starting vertex for DFS traversal: 2


DFS Traversal Order: 2 3 4 0 1
13. Write a C Program to implement breadth-first search (BFS) ) traversal on a graph

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

#define MAX_VERTICES 100

// Function to add an edge to the graph


void addEdge(int graph[MAX_VERTICES][MAX_VERTICES], int start, int end)
{
graph[start][end] = 1;
graph[end][start] = 1; // For undirected graph
}

// Function to perform BFS traversal


void BFS(int graph[MAX_VERTICES][MAX_VERTICES], int vertices, int startVertex)
{
int visited[MAX_VERTICES] = {0}; // Initialize all vertices as not visited
int queue[MAX_VERTICES];
int front = -1, rear = -1;

// Mark the startVertex as visited and enqueue it


visited[startVertex] = 1;
queue[++rear] = startVertex;

printf("BFS Traversal Order: ");

while (front != rear)


{
int currentVertex = queue[++front];
printf("%d ", currentVertex);

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


{
if (graph[currentVertex][i] == 1 && !visited[i])
{
visited[i] = 1;
queue[++rear] = i;
}
}
}
printf("\n");
}

int main()
{
int vertices, edges;

// Input the number of vertices


printf("Input the number of vertices: ");
scanf("%d", &vertices);

if (vertices <= 0 || vertices > MAX_VERTICES)


{
printf("Invalid number of vertices. Exiting...\n");
return 1;
}

int graph[MAX_VERTICES][MAX_VERTICES] = {0}; // Initialize the adjacency matrix with zeros

// Input the number of edges


printf("Input the number of edges: ");
scanf("%d", &edges);

if (edges < 0 || edges > vertices * (vertices - 1) / 2)


{
printf("Invalid number of edges. Exiting...\n");
return 1;
}

// Input edges and construct the adjacency matrix


for (int i = 0; i < edges; i++)
{
int start, end;
printf("Input edge %d (start end): ", i + 1);
scanf("%d %d", &start, &end);

// Validate input vertices


if (start < 0 || start >= vertices || end < 0 || end >= vertices)
{
printf("Invalid vertices. Try again.\n");
i--;
continue;
}

addEdge(graph, start, end);


}

// Input the starting vertex for BFS traversal


int startVertex;
printf("Input the starting vertex for BFS traversal: ");
scanf("%d", &startVertex);

// Perform BFS traversal


BFS(graph, vertices, startVertex);

return 0;
}

Input the number of vertices: 5


Input the number of edges: 6
Input edge 1 (start end): 0 1
Input edge 2 (start end): 1 2
Input edge 3 (start end): 2 3
Input edge 4 (start end): 3 4
Input edge 5 (start end): 4 0
Input edge 6 (start end): 2 3

Input the starting vertex for BFS traversal: 0


BFS Traversal Order: 0 1 4 2 3
14. Write a C Program to perform an traversal of a binary tree.
#include <stdio.h>

// storing the maximum number of nodes


int max_node = 15;

// array to store the tree


char tree[] = {'\0', 'D', 'A', 'F', 'E', 'B', 'R', 'T', 'G', 'Q', '\0', '\0', 'V', '\0', 'J', 'L'};

int get_right_child(int index)


{
// node is not null
// and the result must lie within the number of nodes for a complete binary tree
if (tree[index] != '\0' && ((2 * index) + 1) <= max_node)
return (2 * index) + 1;
// right child doesn't exist
return -1;
}

int get_left_child(int index)


{
// node is not null
// and the result must lie within the number of nodes for a complete binary tree
if (tree[index] != '\0' && (2 * index) <= max_node)
return 2 * index;
// left child doesn't exist
return -1;
}

void preorder(int index)


{
// checking for valid index and null node
if (index > 0 && tree[index] != '\0')
{
printf(" %c ", tree[index]); // visiting root
preorder(get_left_child(index)); //visiting left subtree
preorder(get_right_child(index)); //visiting right subtree
}
}

void postorder(int index)


{
// checking for valid index and null node
if (index > 0 && tree[index] != '\0')
{
postorder(get_left_child(index)); //visiting left subtree
postorder(get_right_child(index)); //visiting right subtree
printf(" %c ", tree[index]); //visiting root
}
}

void inorder(int index)


{
// checking for valid index and null node
if (index > 0 && tree[index] != '\0')
{
inorder(get_left_child(index)); //visiting left subtree
printf(" %c ", tree[index]); //visiting root
inorder(get_right_child(index)); // visiting right subtree
}
}

int main()
{
printf("Preorder:\n");
preorder(1);
printf("\nPostorder:\n");
postorder(1);
printf("\nInorder:\n");
inorder(1);
printf("\n");
return 0;
}

OUTPUT

Preorder:
D A E G Q B F R V T J L
Postorder:
G Q E B A V R J L T F D
Inorder:
G E Q A B D V R F J T L
15. write a C Program to find the height of a binary tree
#include <stdio.h>
#include <stdlib.h>

// Structure for a binary tree node


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

// Function to create a new node


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

// Function to insert a node into the binary tree


struct TreeNode* insertNode(struct TreeNode* root, int value)
{
if (root == NULL)
{
return createNode(value);
}

if (value < root->data)


{
root->left = insertNode(root->left, value);
}
else if (value > root->data)
{
root->right = insertNode(root->right, value);
}

return root;
}

// Function to calculate the height of a binary tree


int treeHeight(struct TreeNode* root)
{
if (root == NULL)
{
return 0; // Height of an empty tree is 0
}

// Recursively calculate the height of the left and right subtrees


int leftHeight = treeHeight(root->left);
int rightHeight = treeHeight(root->right);

// Return the maximum height of the left and right subtrees, plus 1 for the current node
return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);
}

// Function to free the memory allocated for the binary tree


void freeTree(struct TreeNode* root)
{
if (root != NULL) {
freeTree(root->left);
freeTree(root->right);
free(root);
}
}

int main() {
struct TreeNode* root = NULL;
int nodeValue;
char choice;

// Insert nodes into the binary tree


do {
printf("Input a value to insert into the binary tree (enter 0 to stop): ");
scanf("%d", &nodeValue);

if (nodeValue != 0) {
root = insertNode(root, nodeValue);
}
} while (nodeValue != 0);

// Calculate and display the height of the binary tree


int height = treeHeight(root);
printf("\nHeight of the Binary Tree: %d\n", height);

// Free allocated memory


freeTree(root);

return 0;
}

OUTPUT
Input a value to insert into the binary tree (enter 0 to stop): 21
Input a value to insert into the binary tree (enter 0 to stop): 23
Input a value to insert into the binary tree (enter 0 to stop): 45
Input a value to insert into the binary tree (enter 0 to stop): 66
Input a value to insert into the binary tree (enter 0 to stop): 0

Height of the Binary Tree: 4


16. Program to implement a binary search tree (BST) and perform insertion and deletion
#include <stdio.h>
#include <stdlib.h>

// Structure for a binary tree node


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

// Function to create a new node


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

// Function to insert a node into the binary search tree


struct TreeNode* insertNode(struct TreeNode* root, int value)
{
if (root == NULL)
{
return createNode(value);
}

if (value < root->data)


{
root->left = insertNode(root->left, value);
}
else if (value > root->data)
{
root->right = insertNode(root->right, value);
}
return root;
}

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


struct TreeNode* findMinValueNode(struct TreeNode* node)
{
while (node->left != NULL)
{
node = node->left;
}
return node;
}

// Function to delete a node with a given value from the binary search tree
struct TreeNode* deleteNode(struct TreeNode* root, int value)
{
if (root == NULL)
{
return root; // Value not found, return as is
}

if (value < root->data)


{
root->left = deleteNode(root->left, value);
}
else if (value > root->data)
{
root->right = deleteNode(root->right, value);
}
else
{
// Node with only one child or no child
if (root->left == NULL)
{
struct TreeNode* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct TreeNode* temp = root->left;
free(root);
return temp;
}

// Node with two children: Get the inorder successor (smallest in the right subtree)
struct TreeNode* temp = findMinValueNode(root->right);

// Copy the inorder successor's content to this node


root->data = temp->data;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->data);
}

return root;
}

// Function to perform in-order traversal and print elements in sorted order


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

// Function to free the memory allocated for the binary tree


void freeTree(struct TreeNode* root)
{
if (root != NULL) {
freeTree(root->left);
freeTree(root->right);
free(root);
}
}

int main()
{
struct TreeNode* root = NULL;
int nodeValue;
char choice;
// Insert nodes into the binary search tree
do {
printf("Input a value to insert into the binary search tree (enter 0 to stop): ");
scanf("%d", &nodeValue);

if (nodeValue != 0)
{
root = insertNode(root, nodeValue);
}

} while (nodeValue != 0);

// Perform in-order traversal and print elements in sorted order


printf("\nIn-order Traversal (Sorted Order) of the Binary Search Tree: ");
inOrderTraversal(root);
printf("\n");

// Delete nodes from the binary search tree


do {
printf("Input a value to delete from the binary search tree (enter 0 to stop): ");
scanf("%d", &nodeValue);

if (nodeValue != 0)
{
root = deleteNode(root, nodeValue);
printf("In-order Traversal after deleting %d: ", nodeValue);
inOrderTraversal(root);
printf("\n");
}

} while (nodeValue != 0);

// Free allocated memory


freeTree(root);

return 0;
}
OUTPUT
Input a value to insert into the binary search tree (enter 0 to stop): 75
Input a value to insert into the binary search tree (enter 0 to stop): 42
Input a value to insert into the binary search tree (enter 0 to stop): 35
Input a value to insert into the binary search tree (enter 0 to stop): 12
Input a value to insert into the binary search tree (enter 0 to stop): 10
Input a value to insert into the binary search tree (enter 0 to stop): 0

In-order Traversal (Sorted Order) of the Binary Search Tree: 10 12 35 42 75


Input a value to delete from the binary search tree (enter 0 to stop): 35
In-order Traversal after deleting 35: 10 12 42 75
Input a value to delete from the binary search tree (enter 0 to stop): 0

You might also like