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

DS Lab Assignment PDF

Uploaded by

mohdtaha22509
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)
39 views

DS Lab Assignment PDF

Uploaded by

mohdtaha22509
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/ 37

1.

Write a program in C to read n number of values in an array and display it in reverse order

#include <stdio.h>
int main()
{

int n, num;
printf("Enter the n-numbers: ");
scanf("%d", &n);

int array1[n];

printf("Enter the numbers: \n");


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

printf("The reverse of given elements are:\n ");


for (int i = n - 1; i >= 0; i--)
{
printf("%2d", array1[i]);
}

return 0;
}

2.Write a C Program to insert an element into an array

#include<stdio.h>
int main(){
int n, newValue;

// Enter number of elements


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

int array1[n];

// Enter elements
printf("Enter the elements:\n");
for(int i = 0;i<=n-1;i++){
scanf("%d", &array1[i]);
}

// Print the elements before insertion


printf("The elements are: \n");
for(int i = 0; i<= n-1; i++){
printf("%2d", array1[i]);
}

// Enter new element


printf("\nEnter the new element: ");
scanf("%2d", &newValue);

array1[n] = newValue;
n++;

// Print the elements after insertion


printf("The elements are: \n");
for(int i = 0; i<= n-1; i++){
printf("%2d", array1[i]);
}

return 0;
}

3.Write a C Program to Delete an Element from an Array

#include <stdio.h>
int main()
{
int n, target;

printf("Enter the n-term: ");


scanf("%d", &n);

int array1[n];

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


for (int i = 0; i <= n - 1; i++)
{
scanf("%d", &array1[i]);
}

printf("The elements are:\n");


for (int i = 0; i <= n - 1; i++)
{
printf("%5d", array1[i]);
}

printf("\nEnter the element to delete: ");


scanf("%d", &target);

// Searching and deletion of element

int found = 0;
for (int i = 0; i < n; i++)
{
if(array1[i] == target){
found = 1;
for(int j = i; j < n-1; j++){
array1[j] = array1[j+1];
}
n--;
i--;
}
}

if(found){
printf("\nThe array after deletion:\n");
for(int i=0; i<n;i++){
printf("%3d", array1[i]);
}
}
else{
printf("\nElement not FOUND!");
}

return 0;
}

4.Write a C Program to Print Even and Odd Numbers in an Array

#include<stdio.h>
int main(){
int even,odd,n;
printf("Enter the n-terms number: ");
scanf("%d", &n);

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

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


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

// Checking for Even ..


printf("\nChecking and Printing Even Elements are: \n");
for(int i = 0; i < n; i++){
if(num[i] % 2 == 0){
printf("%d\n", num[i]);
}
}

// Checking for Odd ..

printf("\nChecking and Priinting Odd Elements are: \n");


for(int i = 0; i < n; i++){
if(num[i] % 2 == 1){
printf("%d\n", num[i]);
}
}

return 0;
}

5.Write a C Program to Find the Largest Element in an Array

#include<stdio.h>
int main(){
int n, num, large;
printf("Enter the n-terms Number: ");
scanf("%d",&n);

int arr[n];

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


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

printf("The elements of array are: \n");


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

large = arr[0];
for(int i = 0; i < n; i++){
if(arr[i] > large){
large = arr[i];
}
}

printf("\nThe %d is largest\n", large);

printf("Program Terminated");

return 0;
}
6.Write a C Program to Find the Transpose

#include <stdio.h>
int main()
{
int rows, cols;
printf("Enter the no. of rows: ");
scanf("%d", &rows);
printf("Enter the no. of columns: ");
scanf("%d", &cols);

int array[rows][cols], transpose[cols][rows];

// Insetion of elements
printf("Enter the elements: \n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &array[i][j]);
}
}

// Display the elements of array:


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%3d", array[i][j]);
}
printf("\n");
}

// Transposing of Array:
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
transpose[j][i] = array[i][j];
}
}

// Transpose of the array:


printf("\nTranspose of the array is: \n");
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
printf("%3d", transpose[i][j]);
}
printf("\n");
}

return 0;
}

7.Write a C Program to Add Two Matrices

#include<stdio.h>
int main(){
int n;
printf("Enter the element to make 2D Array: ");
scanf("%d", &n);

int arr1[n][n], arr2[n][n];

// Inserting the elements of array1


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

// Inserting the elements of array2


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

// Addition of two arrays


printf("The sum of elements of two arrays is: \n");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%8d", arr1[i][j] + arr2[i][j]);
}
printf("\n");
}

return 0;
}

8.Write a C Program to Multiply Two Matrices


#include <stdio.h>

int main() {
int rows1, cols1, rows2, cols2;

// Input dimensions of the first matrix


printf("Enter the number of rows for the first matrix: ");
scanf("%d", &rows1);
printf("Enter the number of columns for the first matrix: ");
scanf("%d", &cols1);

// Input dimensions of the second matrix


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

if (cols1 != rows2) {
printf("Matrix multiplication is not possible. Columns of the first matrix must be equal to rows of
the second matrix.\n");
return 1; // Exit with an error code
}

int matrix1[rows1][cols1], matrix2[rows2][cols2], result[rows1][cols2];

// Input elements of the first matrix


printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Input elements of the second matrix


printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Multiply the matrices


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the result matrix


printf("Result of matrix multiplication:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

9.Write a C Program to Compute the Sum of Diagonals of a Matrix

#include <stdio.h>

int main() {
int n;

// Input the size of the square matrix


printf("Enter the size of the square matrix: ");
scanf("%d", &n);

int matrix[n][n];

// Input the elements of the matrix


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

int primaryDiagonalSum = 0;
int secondaryDiagonalSum = 0;

// Compute the sum of the elements along the primary diagonal


for (int i = 0; i < n; i++) {
primaryDiagonalSum += matrix[i][i];
}

// Compute the sum of the elements along the secondary diagonal


for (int i = 0; i < n; i++) {
secondaryDiagonalSum += matrix[i][n - 1 - i];
}

// Display the sums


printf("Sum of the elements along the primary diagonal: %d\n", primaryDiagonalSum);
printf("Sum of the elements along the secondary diagonal: %d\n", secondaryDiagonalSum);

return 0;
}

10. Write a C Program to find the number of Occurrences of an Element in an Array

#include <stdio.h>

int main() {
int n, target;

// Input the size of the array


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

int array[n];

// Input the elements of the array


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

// Input the element to count


printf("Enter the element to count: ");
scanf("%d", &target);

int count = 0;

// Count the number of occurrences of the element


for (int i = 0; i < n; i++) {
if (array[i] == target) {
count++;
}
}

printf("The element %d occurs %d times in the array.\n", target, count);

return 0;
}

11. Write a C program to create initialize and access a pointer variable

#include <stdio.h>

int main() {
int number = 42; // Declare an integer variable
int *ptr; // Declare an integer pointer variable

ptr = &number; // Initialize the pointer with the address of 'number'

// Access and print the value using the pointer


printf("Value of 'number': %d\n", *ptr);

return 0;
}

12. Write a C Program to Swap Two Numbers using pointers.

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int num1, num2;

printf("Enter the first number: ");


scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

// Call the swap function to swap the two numbers


swap(&num1, &num2);

printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

return 0;
}

13. Write a C Program to Store Information of Students Using Structure

#include <stdio.h>

// Define a structure to store student information


struct Student {
char name[50];
int rollNo;
float marks;
};
int main() {
int n; // Number of students
printf("Enter the number of students: ");
scanf("%d", &n);

// Declare an array of structures to store student information


struct Student students[n];

// Input student information


for (int i = 0; i < n; i++) {
printf("Enter details for Student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name); // Assuming the name doesn't have spaces
printf("Roll Number: ");
scanf("%d", &students[i].rollNo);
printf("Marks: ");
scanf("%f", &students[i].marks);
}

// Display student information


printf("\nStudent Information:\n");
for (int i = 0; i < n; i++) {
printf("Student %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNo);
printf("Marks: %.2f\n", students[i].marks);
}

return 0;
}

14. Write a program that uses functions to perform the following operations on singly linked list:
i) Creation ii) Insertion iii) Deletion iv) Display. */

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

// Define the structure for a node in the 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 of the linked list


void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

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

struct Node* current = *head;


struct Node* prev = NULL;

if (current != NULL && current->data == key) {


*head = current->next;
free(current);
printf("Deleted node with data %d\n", key);
return;
}

while (current != NULL && current->data != key) {


prev = current;
current = current->next;
}

if (current == NULL) {
printf("Node with data %d not found.\n", key);
} else {
prev->next = current->next;
free(current);
printf("Deleted node with data %d\n", key);
}
}

// Function to display the linked list


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

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

// Create the linked list


insertNode(&head, 10);
insertNode(&head, 20);
insertNode(&head, 30);

// Display the linked list


printf("Linked List: ");
displayList(head);

// Delete a node
deleteNode(&head, 20);

// Display the updated linked list


printf("Updated Linked List: ");
displayList(head);

return 0;
}

15. Write a program that uses functions to perform the following operations on doubly linked list
i) Creation ii) Insertion iii) Deletion iv) Display. */

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

// Define the structure for 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 of the doubly linked list


void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
}

// 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.\n");
return;
}

struct Node* current = *head;


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

if (current == NULL) {
printf("Node with data %d not found.\n", key);
} else {
if (current->prev != NULL) {
current->prev->next = current->next;
} else {
*head = current->next;
}
if (current->next != NULL) {
current->next->prev = current->prev;
}
free(current);
printf("Deleted node with data %d\n", key);
}
}

// Function to display the doubly linked list from the head


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

current = head;
while (current != NULL && current->next != NULL) {
current = current->next;
}

printf("Backward: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->prev;
}
printf("NULL\n");
}

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

// Create the doubly linked list


insertNode(&head, 10);
insertNode(&head, 20);
insertNode(&head, 30);

// Display the doubly linked list


printf("Doubly Linked List:\n");
displayList(head);

// Delete a node
deleteNode(&head, 20);

// Display the updated doubly linked list


printf("Updated Doubly Linked List:\n");
displayList(head);

return 0;
}

16. Write a program that uses functions to perform the following operations on circular linked List
i) Creation ii) Insertion iii) Deletion iv) Display. */

#include <stdio.h>
#include <stdlib.h>
// Define the structure for 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 of the circular linked list


void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* current = *head;
while (current->next != *head) {
current = current->next;
}
current->next = newNode;
newNode->next = *head;
}
}

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

struct Node* current = *head;


struct Node* prev = NULL;

while (current->next != *head && current->data != key) {


prev = current;
current = current->next;
}

if (current->data != key) {
printf("Node with data %d not found.\n", key);
} else {
if (current == *head && current->next == *head) {
*head = NULL;
} else if (current == *head) {
struct Node* last = *head;
while (last->next != *head) {
last = last->next;
}
*head = (*head)->next;
last->next = *head;
} else {
prev->next = current->next;
}
free(current);
printf("Deleted node with data %d\n", key);
}
}

// Function to display the circular linked list


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

struct Node* current = head;


do {
printf("%d -> ", current->data);
current = current->next;
} while (current != head);

printf("%d\n", current->data); // Display the last node


}

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

// Create the circular linked list


insertNode(&head, 10);
insertNode(&head, 20);
insertNode(&head, 30);

// Display the circular linked list


printf("Circular Linked List:\n");
displayList(head);

// Delete a node
deleteNode(&head, 20);

// Display the updated circular linked list


printf("Updated Circular Linked List:\n");
displayList(head);

return 0;
}

17. Write a program that implement stack and its operations using
i) Arrays OR ii) Linked list (Pointers). */

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

#define MAX_SIZE 100

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

// Function to initialize the stack


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

// Function to check if the stack is empty


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

// Function to check if the stack is full


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

// Function to push an element onto the stack


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

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Cannot pop.\n");
return -1;
} else {
int item = stack->items[stack->top--];
return item;
}
}

// Function to display the elements of the stack


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

int main() {
struct Stack stack;
initialize(&stack);

push(&stack, 10);
push(&stack, 20);
push(&stack, 30);

display(&stack);

int popped = pop(&stack);


if (popped != -1) {
printf("Popped %d from the stack.\n", popped);
}

display(&stack);

return 0;
}

18. Write a program that implement Queue and its operations using
i) ArraysOR ii) Linked list (Pointers). */

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

#define MAX_SIZE 100

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

// Function to initialize the queue


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

// Function to check if the queue is empty


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

// Function to check if the queue is full


int isFull(struct Queue* queue) {
return (queue->rear == MAX_SIZE - 1);
}

// Function to enqueue an element into the queue


void enqueue(struct Queue* queue, int item) {
if (isFull(queue)) {
printf("Queue is full. Cannot enqueue %d.\n", item);
} else {
if (isEmpty(queue)) {
queue->front = 0;
}
queue->items[++queue->rear] = item;
printf("Enqueued %d into the queue.\n", item);
}
}

// Function to dequeue an element from the queue


int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1;
} else {
int item = queue->items[queue->front];
if (queue->front == queue->rear) {
queue->front = queue->rear = -1;
} else {
queue->front++;
}
return item;
}
}

// Function to display the elements in the queue


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

int main() {
struct Queue queue;
initialize(&queue);

enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);

display(&queue);

int dequeued = dequeue(&queue);


if (dequeued != -1) {
printf("Dequeued %d from the queue.\n", dequeued);
}

display(&queue);

return 0;
}

19. Write a program that performs the searching operations for a Key value in a given list of integers
using Linear search Technique.*/

#include <stdio.h>

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


for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Key found at index i
}
}
return -1; // Key not found
}

int main() {
int n, key;

printf("Enter the number of elements in the list: ");


scanf("%d", &n);

int arr[n];

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


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

printf("Enter the key value to search for: ");


scanf("%d", &key);

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

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

return 0;
}

20. Write a program that performs the searching operations for a Key value in a given list of integers
using Binary search Technique. */

#include <stdio.h>

int binarySearch(int arr[], int left, int right, int key) {


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

if (arr[mid] == key) {
return mid; // Key found at index mid
}

if (arr[mid] < key) {


left = mid + 1;
} else {
right = mid - 1;
}
}

return -1; // Key not found


}

int main() {
int n, key;
printf("Enter the number of elements in the sorted list: ");
scanf("%d", &n);

int arr[n];

printf("Enter the sorted elements:\n");


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

printf("Enter the key value to search for: ");


scanf("%d", &key);

int result = binarySearch(arr, 0, n - 1, key);

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

return 0;
}

21. Write a program that implements the Bubble sort.

#include <stdio.h>

int main() {
int n, temp;

// Input the size of the array


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

int array[n];

// Input the elements of the array


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

// Bubble sort algorithm


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
// Compare adjacent elements
if (array[j] > array[j + 1]) {
// Swap the elements if they are in the wrong order
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}

// Display the sorted array


printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}

return 0;
}

22. Write a program that implements the Selection sort.

#include <stdio.h>

int main() {
int n, temp;

// Input the size of the array


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

int array[n];

// Input the elements of the array


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

// Selection sort algorithm


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

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


// Find the index of the minimum element in the unsorted part of the array
if (array[j] < array[minIndex]) {
minIndex = j;
}
}

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

// Display the sorted array


printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}

return 0;
}

23. Write a program that implements the Insertion sort.

#include <stdio.h>

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


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

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


arr[j + 1] = arr[j];
j--;
}

arr[j + 1] = key;
}
}

int main() {
int n;

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


scanf("%d", &n);

int arr[n];

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


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

insertionSort(arr, n);

printf("Sorted array in ascending order: ");


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

return 0;
}

24. Write a program to perform the following operations:


a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree. */

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

// Structure for a node in the binary search tree


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

// Function to create a new node


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

// Function to insert a key into a binary search tree


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

if (key < root->data) {


root->left = insert(root->left, key);
} else if (key > root->data) {
root->right = insert(root->right, key);
}

return root;
}

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


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

// Function to delete a key from a binary search tree


struct TreeNode* delete(struct TreeNode* root, int key) {
if (root == NULL) {
return root;
}

if (key < root->data) {


root->left = delete(root->left, key);
} else if (key > root->data) {
root->right = delete(root->right, key);
} else {
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;
}

struct TreeNode* temp = findMin(root->right);


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

// Function to search for a key in a binary search tree


struct TreeNode* search(struct TreeNode* root, int key) {
if (root == NULL || root->data == key) {
return root;
}

if (root->data < key) {


return search(root->right, key);
}

return search(root->left, key);


}

// Function to perform in-order traversal of a binary search tree


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

int main() {
struct TreeNode* root = NULL;
int choice, key;

do {
printf("Binary Search Tree Operations:\n");
printf("1. Insert an element\n");
printf("2. Delete an element\n");
printf("3. Search for a key\n");
printf("4. In-order Traversal\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the key to insert: ");
scanf("%d", &key);
root = insert(root, key);
break;
case 2:
printf("Enter the key to delete: ");
scanf("%d", &key);
root = delete(root, key);
break;
case 3:
printf("Enter the key to search for: ");
scanf("%d", &key);
if (search(root, key) != NULL) {
printf("%d is present in the tree.\n");
} else {
printf("%d is not found in the tree.\n");
}
break;
case 4:
printf("In-order Traversal of the Binary Search Tree: ");
inOrderTraversal(root);
printf("\n");
break;
case 5:
// Exit the program
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);

return 0;
}

25. Write a program to implement the tree traversal methods.

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

// Structure for a tree node


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

// Function to create a new node


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

// Function to perform In-order traversal of the tree


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

// Function to perform Pre-order traversal of the tree


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

// Function to perform Post-order traversal of the tree


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

int main() {
struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

printf("In-order Traversal: ");


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

printf("Pre-order Traversal: ");


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

printf("Post-order Traversal: ");


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

return 0;
}

26. Write C programs for implementing the Depth first Search (DFS) graph traversal algorithm.

// Iterative DFS:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Structure for an adjacency list node


struct AdjListNode {
int dest;
struct AdjListNode* next;
};

// Structure for an adjacency list


struct AdjList {
struct AdjListNode* head;
};

// Structure for a graph


struct Graph {
int V;
struct AdjList* array;
};
// Function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with V vertices


struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));

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


graph->array[i].head = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}

// Function to perform Depth-First Search


void DFS(struct Graph* graph, int vertex, bool* visited) {
visited[vertex] = true;
printf("%d ", vertex);

struct AdjListNode* adjNode = graph->array[vertex].head;


while (adjNode) {
int dest = adjNode->dest;
if (!visited[dest]) {
DFS(graph, dest, visited);
}
adjNode = adjNode->next;
}
}

// Function to perform DFS traversal of the graph


void DFSTraversal(struct Graph* graph, int startVertex) {
bool* visited = (bool*)malloc(graph->V * sizeof(bool));

for (int i = 0; i < graph->V; i++) {


visited[i] = false;
}

printf("Depth-First Search starting from vertex %d:\n", startVertex);


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

int main() {
int V = 6; // Number of vertices
struct Graph* graph = createGraph(V);

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

int startVertex = 0; // Starting vertex for DFS

DFSTraversal(graph, startVertex);

return 0;
}

// Recursive DFS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Structure for an adjacency list node


struct AdjListNode {
int dest;
struct AdjListNode* next;
};

// Structure for an adjacency list


struct AdjList {
struct AdjListNode* head;
};

// Structure for a graph


struct Graph {
int V;
struct AdjList* array;
};

// Function to create a new adjacency list node


struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with V vertices


struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));

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


graph->array[i].head = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}

// Function to perform Recursive Depth-First Search


void DFS(struct Graph* graph, int vertex, bool* visited) {
visited[vertex] = true;
printf("%d ", vertex);

struct AdjListNode* adjNode = graph->array[vertex].head;


while (adjNode) {
int dest = adjNode->dest;
if (!visited[dest]) {
DFS(graph, dest, visited);
}
adjNode = adjNode->next;
}
}

// Function to perform DFS traversal of the graph


void DFSTraversal(struct Graph* graph, int startVertex) {
bool* visited = (bool*)malloc(graph->V * sizeof(bool));

for (int i = 0; i < graph->V; i++) {


visited[i] = false;
}
printf("Depth-First Search starting from vertex %d:\n", startVertex);
DFS(graph, startVertex, visited);
printf("\n");
free(visited);
}

int main() {
int V = 6; // Number of vertices
struct Graph* graph = createGraph(V);

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

int startVertex = 0; // Starting vertex for DFS

DFSTraversal(graph, startVertex);

return 0;
}

27. Write C programs for implementing the Breadth first Search (BFS) graph traversal algorithm.

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

// Structure for an adjacency list node


struct AdjListNode {
int dest;
struct AdjListNode* next;
};

// Structure for an adjacency list


struct AdjList {
struct AdjListNode* head;
};

// Structure for a graph


struct Graph {
int V;
struct AdjList* array;
};

// Structure for a queue node


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

// Structure for a queue


struct Queue {
struct QueueNode* front;
struct QueueNode* rear;
};

// Function to create a new adjacency list node


struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with V vertices


struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));

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


graph->array[i].head = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}

// Function to create a new node for the queue


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

// Function to create an empty queue


struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
return queue;
}

// Function to check if the queue is empty


bool isEmpty(struct Queue* queue) {
return queue->front == NULL;
}

// Function to enqueue an element into the queue


void enqueue(struct Queue* queue, int data) {
struct QueueNode* newNode = newQueueNode(data);
if (queue->rear == NULL) {
queue->front = queue->rear = newNode;
return;
}
queue->rear->next = newNode;
queue->rear = newNode;
}

// Function to dequeue an element from the queue


int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
return -1;
}
struct QueueNode* temp = queue->front;
int data = temp->data;
queue->front = temp->next;
free(temp);
return data;
}

// Function to perform Breadth-First Search


void BFS(struct Graph* graph, int startVertex) {
bool* visited = (bool*)malloc(graph->V * sizeof(bool));
struct Queue* queue = createQueue();

for (int i = 0; i < graph->V; i++) {


visited[i] = false;
}

visited[startVertex] = true;
enqueue(queue, startVertex);

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


while (!isEmpty(queue)) {
int vertex = dequeue(queue);
printf("%d ", vertex);
struct AdjListNode* adjNode = graph->array[vertex].head;
while (adjNode) {
int dest = adjNode->dest;
if (!visited[dest]) {
visited[dest] = true;
enqueue(queue, dest);
}
adjNode = adjNode->next;
}
}
printf("\n");

free(visited);
free(queue);
}

int main() {
int V = 6; // Number of vertices
struct Graph* graph = createGraph(V);

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

int startVertex = 0; // Starting vertex for BFS

BFS(graph, startVertex);

return 0;
}

You might also like