0% found this document useful (0 votes)
30 views57 pages

Lab Record Assignment 2024

Uploaded by

amonakdan123
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)
30 views57 pages

Lab Record Assignment 2024

Uploaded by

amonakdan123
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/ 57

Martin Luther Christian University

The Light of Truth

Department of Information Technology


Batch 2022 -2024

LAB REPORT

Submitted by,
Name: Amona L Mawnai
Reg.No: B061220019
3rd Semester

Submitted to,
Ma’am Saphilarisa Marbaniang
Table of Contents

Topics Pg no
1.Arrays 2-7
(a)Array Deletion of an element
(b)Array Insertion at any position
(c)2D Array
2.Strings 7-8
(a)Lower case to uppercase
(b)Reverse String
3. Linked List 9-14
(a)Singly Linked List
(b)Doubly Linked List

4. Stacks 15-26
(a)Operation of Stacks
(b)Infix to Postfix
(c)Infix to Prefix

5.Queues 27-28
6.Trees 29-35
(a)Binary Search Tree
(b)Tree Traversal
7.Graphs 36-45
(a)BFS and DFS graph traversal
(b) Graph using Adjacency Matrix

9.Sorting 46-55
(a)Bubble Sort
(b)Insertion Sort
(c)Selection Sort
(d)Quick Sort

1 | Page
//C program array_deletion of an element//
#include <stdio.h>
int main()
{
int arr[10], n, p, i;
printf("\nEnter the size of the array: ");
scanf("%d", &n);
printf("\nEnter the %d numbers of the array: ", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("\nThe array before deletion:\n");
for (i = 0; i < n; i++)
{
printf("\t%d\t", arr[i]);
}
printf("\nEnter the index location to delete: ");
scanf("%d", &p);
int d = arr[p];
for (i = p; i < n - 1; i++)
{
arr[i] = arr[i + 1];
}
n--;
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}

2 | Page
OUTPUT

// C program to perform array insertion at any position //

#include <stdio.h>
int main()
{
int a[100], n, m, p;
printf("Enter the size of an array : ");
scanf("%d", &n);
printf("Enter the elements of an array : ");
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("The array before insertion :\n");
for (int i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
printf("\nEnter the position of an element: ");
scanf("%d", &p);
printf("Enter the element which one to enter : ");

3 | Page
scanf("%d", &m);
for (int i = n; i >= p; i--)
{
a[i] = a[i - 1];
}
n++;
a[p] = m;
printf("The elements are \n");
for (int i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
return 0;
}

OUTPUT

4 | Page
// C program to print the elements of a 2D array
#include <stdio.h>
#include <conio.h>
int main()
{
int arr[2][2] = {12, 34, 56, 32};
int i, j;
for (i = 0; i < 2; i++)
{
printf("\n");
for (j = 0; j < 2; j++)
printf("%d\t", arr[i][j]);
}
return 0;
}

OUTPUT

5 | Page
// C program to convert string to uppercase//

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
char str[MAX_SIZE];
int i;

/* Input string from user */


printf("Enter your text : ");
gets(str);

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


{
/*
* If current character is lowercase alphabet then
* convert it to uppercase.
*/
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32;
}
}

printf("Uppercase string : %s", str);


return 0;
}

OUTPUT

6 | Page
//Program to reverse a string//
#include <stdio.h>
#include <string.h>
int main()
{
char str[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);

// use strrev() function to reverse a string


printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}

//C program to perform Singly_linkd list //

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

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

void deleteStart (struct Node **head)


{
struct Node *temp = *head;

// if there are no nodes in Linked List can't delete

7 | Page
if (*head == NULL)
{
printf ("Linked List Empty, nothing to delete");
return;
}

// move head to next node


*head = (*head)->next;

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


free (temp);
}

void insertStart (struct Node **head, int data)


{

// dynamically create memory for this newNode


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

// assign data value


newNode->data = data;
// change the next node of this newNode
// to current head of Linked List
newNode->next = *head;

//re-assign head to this newNode


*head = newNode;
printf ("\n%d Inserted\n", newNode->data);
}

void display (struct Node *node)


{
printf ("\nLinked List: ");

// as linked list will end when Node is Null


while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
printf ("\n");
}

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

// Need '&' i.e. address as we need to change head


insertStart (&head, 100);
insertStart (&head, 80);
insertStart (&head, 60);
insertStart (&head, 40);
insertStart (&head, 20);

// No Need for '&' as not changing head in display operation


display (head);

deleteStart (&head);
deleteStart (&head);
display (head);

return 0;
}

Output:

9 | Page
// C program to create a doubly linked list
#include <stdio.h>
#include <stdlib.h>

// node creation
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};

// insert node at the front


void insertFront(struct Node **head, int data)
{
// allocate memory for newNode
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));

// assign data to newNode


newNode->data = data;

// make newNode as a head


newNode->next = (*head);

// assign null to prev


newNode->prev = NULL;

// previous of head (now head is the second node) is newNode


if ((*head) != NULL)
(*head)->prev = newNode;

// head points to newNode


(*head) = newNode;
}

// insert a node after a specific node


void insertAfter(struct Node *prev_node, int data)
{
// check if previous node is null
if (prev_node == NULL)
{
printf("previous node cannot be null");
return;
}

10 | P a g e
// allocate memory for newNode
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));

// assign data to newNode


newNode->data = data;

// set next of newNode to next of prev node


newNode->next = prev_node->next;

// set next of prev node to newNode


prev_node->next = newNode;

// set prev of newNode to the previous node


newNode->prev = prev_node;

// set prev of newNode's next to newNode


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

// insert a newNode at the end of the list


void insertEnd(struct Node **head, int data)
{
// allocate memory for node
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));

// assign data to newNode


newNode->data = data;

// assign null to next of newNode


newNode->next = NULL;

// store the head node temporarily (for later use)


struct Node *temp = *head;

// if the linked list is empty, make the newNode as head node


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

// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
11 | P a g e
temp = temp->next;

// now, the last node of the linked list is temp

// assign next of the last node (temp) to newNode


temp->next = newNode;

// assign prev of newNode to temp


newNode->prev = temp;
}

// delete a node from the doubly linked list


void deleteNode(struct Node **head, struct Node *del_node)
{
// if head or del is null, deletion is not possible
if (*head == NULL || del_node == NULL)
return;

// if del_node is the head node, point the head pointer to the next of del_node
if (*head == del_node)
*head = del_node->next;

// if del_node is not at the last node, point the prev of node next to del_node to the
previous of del_node
if (del_node->next != NULL)
del_node->next->prev = del_node->prev;

// if del_node is not the first node, point the next of the previous node to the next node of
del_node
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;

// free the memory of del_node


free(del_node);
}

// print the doubly linked list


void displayList(struct Node *node)
{
struct Node *last;

while (node != NULL)


{
printf("%d->", node->data);
last = node;
12 | P a g e
node = node->next;
}
if (node == NULL)
printf("NULL\n");
}

int main()
{
// initialize an empty node
struct Node *head = NULL;

insertEnd(&head, 5);
insertFront(&head, 1);
insertFront(&head, 6);
insertEnd(&head, 9);

// insert 11 after head


insertAfter(head, 11);

// insert 15 after the seond node


insertAfter(head->next, 15);

displayList(head);

// delete the last node


deleteNode(&head, head->next->next->next->next->next);

displayList(head);
}

OUTPUT

13 | P a g e
// Program to show the different stack operations (Push, Pop, Peek)
#include <stdio.h>
#include <stdlib.h>
#define MAX 10

int st[MAX], top = -1;


void push(int st[], int val);
int pop(int st[]);
int peek(int st[]);
void display(int st[]);
int main(int argc, char *argv[])
{
int val, option;
do
{
printf("\n\n *****MAIN MENU*****");
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. PEEK");
printf("\n 4. DISPLAY");
printf("\n 5. EXIT");
printf("\n\n Enter your option: ");
scanf("%d", &option);
switch (option)
{
case 1:
printf("\n Enter the number to be pushed on stack: ");
scanf("%d", &val);
push(st, val);
break;
case 2:
val = pop(st);
if (val != -1)
printf("\n The value deleted from stack is: %d", val);
break;
case 3:
val = peek(st);
if (val != -1)
printf("\n The value stored at top of stack is: %d", val);
break;
case 4:
display(st);
break;
}
} while (option != 5);
14 | P a g e
return 0;
}
void push(int st[], int val)
{
if (top == MAX - 1)
{
printf("\n STACK OVERFLOW");
}
else
{
top++;
st[top] = val;
}
}
int pop(int st[])
{
int val;
if (top == -1)
{
printf("\n STACK UNDERFLOW");
return -1;
}
else
{
val = st[top];
top--;
return val;
}
}
void display(int st[]) {
int i;
if (top == -1)
printf("\n STACK IS EMPTY");
else
{
for (i = top; i >= 0; i--)
printf("\n %d", st[i]);
printf("\n"); // Added for formatting purposes
}
}
int peek(int st[]) {
if (top == -1) {
printf("\n STACK IS EMPTY");
return -1;
} else
15 | P a g e
return (st[top]);
}

OUTPUT

16 | P a g e
17 | P a g e
18 | P a g e
//C program Infix to Prefix Expression//
/* #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STACK_SIZE 100

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

int getPrecedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
return 0;
}

void infixToPrefix(char infix[], char prefix[]) {


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

int len = strlen(infix);


int j = 0;

for (int i = len - 1; i >= 0; i--) {


char c = infix[i];

if (c == ')') {
stack[++top] = c;
} else if (c == '(') {
while (top >= 0 && stack[top] != ')') {
prefix[j++] = stack[top--];
}
top--;
} else if (isOperator(c)) {
while (top >= 0 && getPrecedence(c) < getPrecedence(stack[top])) {
prefix[j++] = stack[top--];
}
stack[++top] = c;
} else {
prefix[j++] = c;
}
19 | P a g e
}

while (top >= 0) {


prefix[j++] = stack[top--];
}

prefix[j] = '\0';
strrev(prefix);
}

int main() {
char infix[100], prefix[100];

printf("Enter an infix expression: ");


scanf("%s", infix);
printf("\n");

infixToPrefix(infix, prefix);

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


return 0;
} */

// using stack
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX_SIZE 100

// Define a stack structure for operators


struct Stack
{
int top;
char array[MAX_SIZE];
};

// Function to initialize an empty stack


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

// Function to check if the stack is empty


20 | P a g e
int isEmpty(struct Stack *stack)
{
return (stack->top == -1);
}

// Function to push an element onto the stack


void push(struct Stack *stack, char value)
{
if (stack->top == MAX_SIZE - 1)
{
printf("Stack overflow\n");
exit(1);
}
stack->array[++stack->top] = value;
}

// Function to pop an element from the stack


char pop(struct Stack *stack)
{
if (isEmpty(stack))
{
printf("Stack underflow\n");
exit(1);
}
return stack->array[stack->top--];
}

// Function to get the precedence of an operator


int getPrecedence(char op)
{
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
return 0;
}

// Function to check if a character is an operator


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

// Function to reverse a string


void reverseString(char str[])
21 | P a g e
{
int length = strlen(str);
int start = 0;
int end = length - 1;

while (start < end)


{
char temp = str[start];
str[start] = str[end];
str[end] = temp;

start++;
end--;
}
}

// Function to convert infix to postfix


void infixToPostfix(char infix[], char postfix[])
{
struct Stack operatorStack;
initialize(&operatorStack);

int i, j = 0;

// Reverse the infix expression


reverseString(infix);

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


{
if (infix[i] == '(')
{
infix[i] = ')';
i++;
}
else if (infix[i] == ')')
{
infix[i] = '(';
i++;
}
}

// Convert infix to postfix


for (i = 0; infix[i] != '\0'; ++i)
{
if (isalnum(infix[i]))
22 | P a g e
{
postfix[j++] = infix[i];
}
else if (infix[i] == '(')
{
push(&operatorStack, infix[i]);
}
else if (infix[i] == ')')
{
while (!isEmpty(&operatorStack) && operatorStack.array[operatorStack.top]
!= '(')
{
postfix[j++] = pop(&operatorStack);
}
pop(&operatorStack); // Pop '('
}
else if (isOperator(infix[i]))
{
while (!isEmpty(&operatorStack) && getPrecedence(infix[i]) <=
getPrecedence(operatorStack.array[operatorStack.top]))
{
postfix[j++] = pop(&operatorStack);
}
push(&operatorStack, infix[i]);
}
}

// Pop any remaining operators from the stack


while (!isEmpty(&operatorStack))
{
postfix[j++] = pop(&operatorStack);
}

postfix[j] = '\0';

// Reverse the postfix expression to get the final result


reverseString(postfix);
}

int main()
{
char infix[MAX_SIZE], prefix[MAX_SIZE];

printf("Enter infix expression: ");


scanf("%s", infix);
23 | P a g e
infixToPostfix(infix, prefix);

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

return 0;
}

// Convert infix to postfix


for (i = 0; infix[i] != '\0'; ++i)
{
if (isalnum(infix[i]))
{
postfix[j++] = infix[i];
}
else if (infix[i] == '(')
{
push(&operatorStack, infix[i]);
}
else if (infix[i] == ')')
{
while (!isEmpty(&operatorStack) && operatorStack.array[operatorStack.top]
!= '(')
{
postfix[j++] = pop(&operatorStack);
}
pop(&operatorStack); // Pop '('
}
else if (isOperator(infix[i]))
{
while (!isEmpty(&operatorStack) && getPrecedence(infix[i]) <=
getPrecedence(operatorStack.array[operatorStack.top]))
{
postfix[j++] = pop(&operatorStack);
}
push(&operatorStack, infix[i]);
}
}

// Pop any remaining operators from the stack


while (!isEmpty(&operatorStack))
24 | P a g e
{
postfix[j++] = pop(&operatorStack);
}

postfix[j] = '\0';

// Reverse the postfix expression to get the final result


reverseString(postfix);
}

int main()
{
char infix[MAX_SIZE], prefix[MAX_SIZE];

printf("Enter infix expression: ");


scanf("%s", infix);

infixToPostfix(infix, prefix);

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

return 0;
}

OUTPUT

25 | P a g e
//C program Infix To Postfix//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STACK_SIZE 100

int precedence(char operator)


{
if (operator== '+' || operator== '-')
return 1;
else if (operator== '*' || operator== '/')
return 2;
else
return 0;
}

int isOperand(char ch)


{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

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


{
int i, j;
char stack[MAX_STACK_SIZE];
int top = -1;

for (i = 0, j = 0; i < strlen(infix); i++)


{
char currentChar = infix[i];

if (isOperand(currentChar))
{
postfix[j++] = currentChar;
}
else if (currentChar == '(')
{
stack[++top] = currentChar;
}
else if (currentChar == ')')
{
26 | P a g e
while (top != -1 && stack[top] != '(')
{
postfix[j++] = stack[top--];
}
top--;
}
else
{
while (top != -1 && precedence(stack[top]) >= precedence(currentChar))
{
postfix[j++] = stack[top--];
}
stack[++top] = currentChar;
}
}

while (top != -1)


{
postfix[j++] = stack[top--];
}

postfix[j] = '\0';
}

int main()
{
char infix[100];
char postfix[100];

printf("Enter infix expression: ");


fgets(infix, sizeof(infix), stdin);
infix[strlen(infix) - 1] = '\0'; // Remove the newline character

infixToPostfix(infix, postfix);

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

return 0;
}

27 | P a g e
OUPUT

// Queue implementation in C

#include <stdio.h>
#define SIZE 5

void enQueue(int);
void deQueue();
void display();

int items[SIZE], front = -1, rear = -1;

int main()
{
// deQueue is not possible on empty queue
deQueue();

// enQueue 5 elements
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);

// 6th element can't be added to because the queue is full

28 | P a g e
enQueue(6);

display();

// deQueue removes element entered first i.e. 1


deQueue();

// Now we have just 4 elements


display();

return 0;
}

void enQueue(int value)


{
if (rear == SIZE - 1)
printf("\nQueue is Full!!");
else
{
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted -> %d", value);
}
}

void deQueue()
{
if (front == -1)
printf("\nQueue is Empty!!");
else
{
printf("\nDeleted : %d", items[front]);
front++;
if (front > rear)
front = rear = -1;
}
}

// Function to print the queue


void display()
{
if (rear == -1)
printf("\nQueue is Empty!!!");
29 | P a g e
else
{
int i;
printf("\nQueue elements are:\n");
for (i = front; i <= rear; i++)
printf("%d ", items[i]);
}
printf("\n");
}

OUTPUT

30 | P a g e
// Binary Search Tree operations in C

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

struct node
{
int key;
struct node *left, *right;
};

// Create a node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// Inorder Traversal
void inorder(struct node *root)
{
if (root != NULL)
{
// Traverse left
inorder(root->left);

// Traverse root
printf("%d -> ", root->key);

// Traverse right
inorder(root->right);
}
}

// Insert a node
struct node *insert(struct node *node, int key)
{
// Return a new node if the tree is empty
if (node == NULL)
return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
31 | P a g e
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node)
{
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;
}

// Deleting a node
struct node *deleteNode(struct node *root, int key)
{
// Return if the tree is empty
if (root == NULL)
return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else
{
// If the node is with only 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);
32 | P a g e
return temp;
}

// If the node has two children


struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


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

// Driver code
int main()
{
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);

printf("Inorder traversal: ");


inorder(root);

printf("\nAfter deleting 10\n");


root = deleteNode(root, 10);
printf("Inorder traversal: ");
inorder(root);
}

33 | P a g e
OUTPUT

34 | P a g e
// Tree traversal in C

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

struct node {
int item;
struct node* left;
struct node* right;
};

// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}

// preorderTraversal traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// postorderTraversal traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}

// Create a new Node


struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

35 | P a g e
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}

int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);

insertLeft(root->left, 5);
insertRight(root->left, 6);

printf("Inorder traversal \n");


inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);

printf("\nPostorder traversal \n");


postorderTraversal(root);
}

OUTPUT

36 | P a g e
37 | P a g e
//Graph_Adjacency Matrix//
#include <stdio.h>
int MIN(int, int); /* Function prototype for computing the minimum among two
integers */

void main()
{
int P[5][5], SP[5][5];
int i, j, k;

/* Initialize the Path Matrix */


for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
P[i][j] = 0;

P[0][0] = 8;
P[0][1] = 3;
P[0][3] = 4;
P[1][2] = 7;
P[2][0] = 4;
P[2][4] = 5;
P[3][2] = 2;
P[4][3] = 1;

printf("Path Matrix: \n");


for (i = 0; i < 5; i++)
{
printf("\n");
for (j = 0; j < 5; j++)
printf("%d\t", P[i][j]);
}

/* Initialize the Shortest Path Matrix */


for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
if (P[i][j] == 0)
SP[i][j] = 999;
else
SP[i][j] = P[i][j];

/* Apply the Floyd-Warshall algorithm to find the shortest paths */


for (k = 0; k < 5; k++)
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
SP[i][j] = MIN(SP[i][j], SP[i][k] + SP[k][j]);
38 | P a g e
printf("\n\nShortest Path Matrix: \n");
for (i = 0; i < 5; i++)
{
printf("\n");
for (j = 0; j < 5; j++)
printf("%d\t", SP[i][j]);
}
}

int MIN(int x, int y)


{
if (x <= y)
return (x);
else
return (y);
}

OUTPUT

39 | P a g e
// BFS algorithm in C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40

struct queue {
int items[SIZE];
int front;
int rear;
};

struct queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int);

struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};

// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();

graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);

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


40 | P a g e
while (temp) {
int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}

// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));


graph->visited = malloc(vertices * sizeof(int));

int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

41 | P a g e
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

// Check if the queue is empty


int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}

// Adding elements into queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}

// Removing elements from queue


int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
42 | P a g e
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


void printQueue(struct queue* q) {
int i = q->front;

if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);

bfs(graph, 0);

return 0;
}

43 | P a g e
OUTPUT

// DFS algorithm in C

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

struct node
{
int vertex;
struct node *next;
};

struct node *createNode(int v);

struct Graph
{
int numVertices;
int *visited;

// We need int** to store a two dimensional array.


// Similary, we need struct node** to store an array of Linked lists

44 | P a g e
struct node **adjLists;
};

// DFS algo
void DFS(struct Graph *graph, int vertex)
{
struct node *adjList = graph->adjLists[vertex];
struct node *temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while (temp != NULL)


{
int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0)
{
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

// Create a node
struct node *createNode(int v)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Create graph
struct Graph *createGraph(int vertices)
{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node *));

graph->visited = malloc(vertices * sizeof(int));

int i;
for (i = 0; i < vertices; i++)
45 | P a g e
{
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}

// Add edge
void addEdge(struct Graph *graph, int src, int dest)
{
// Add edge from src to dest
struct node *newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Print the graph


void printGraph(struct Graph *graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node *temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

int main()
{
struct Graph *graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
46 | P a g e
printGraph(graph);

DFS(graph, 2);

return 0;
}

OUTPUT

47 | P a g e
//C program to perform Bubble Sort//
#include <stdio.h>
// functions to performed Bubble sort
void bubble_Sort(int arr[], int n)
{
inti, j;
for (i = 0; i<= n - 1; i++)
{
for (j = 0; j < n - i; j++)
{
// Swapping
if (arr[j] >arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// main functions
intmain()
{
intarr[10], i, n;
printf("enter the size of and array\t");
scanf("%d", &n);
printf("enter the numbers of and array :", n);
for (int i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
bubble_Sort(arr, n);
printf("The new sorted array is :");
for (int i = 0; i< n; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}

48 | P a g e
OUTPUT

//C program to perform selection Sort//


#include<stdio.h>
intmain(){
inta[10],n;
printf("Enter the size of the array : ");
scanf("%d",&n);

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


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

for(inti =0;i<n;i++){
for(int j =i+1;j<n;j++) {
if(a[i]>a[j]){
int temp =a[i];
a[i]= a[j];
a[j]=temp;
}

}
}
printf("The new sorted array is :\n ");
49 | P a g e
for(int i=0;i<n;i++){
printf("%d\t",a[i]);
}
return 0;
}
OUTPUT

//C program to perform Insertion Sort//


#include <stdio.h>
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int current = arr[i];
int j = i - 1;
while (arr[j] >= current && j >= 0)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
printf("The new sorted array is : \n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
50 | P a g e
}
}

int main()
{
int arr[10], n;
printf("Enter the size of the array : ");
scanf("%d", &n);
printf("Enter the %d numbers of the array : ", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
insertionSort(arr, n);
return 0;
}
Output:

51 | P a g e
//C program to perform Quick sort//

#include <stdio.h>
intpartition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (arr[j] < pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
i++;
int temp = arr[i];
arr[i] = arr[high];
arr[high] = temp;

return i;
}

void quickSort(intarr[], int low, int high)


{
if (low < high)
{
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}

Int main()
{
Int arr[10], n;
printf("Enter the size of the array : ");
scanf("%d", &n);
printf("Enter the %d numbers of the array : ", n);
for (int i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
52 | P a g e
quickSort(arr, 0, n - 1);
for (inti = 0; i< n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

OUTPUT

53 | P a g e
// C program to perform merge sort//

#include <stdio.h>

void conqure(int arr[], int si, int mid, int ei)


{
int merged[ei - si + 1];
int idx1 = si;
int idx2 = mid + 1;
int x = 0;
while (idx1 <= mid && idx2 <= ei)
{
if (arr[idx1] <= arr[idx2])
{
merged[x++] = arr[idx1++];
}
else
{
merged[x++] = arr[idx2++];
}
}
while (idx1 <= mid)
{
merged[x++] = arr[idx1++];
}
while (idx2 <= ei)
{
merged[x++] = arr[idx2++];
}
for (int i = 0, j = si; i < x; i++, j++)
{
arr[j] = merged[i];
}
}
void devide(int arr[], int si, int ei)
{
if (si >= ei)
{
return;
}
int mid = si + (ei - si) / 2;
devide(arr, si, mid);
devide(arr, mid + 1, ei);
conqure(arr, si, mid, ei);
}
54 | P a g e
int main()
{
int arr[10], n;
printf("Enter the size of the array : ");
scanf("%d", &n);
printf("Enter the %d numbers of the array : ", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
devide(arr, 0, n - 1);
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

OUTPUT

55 | P a g e
56 | P a g e

You might also like