0% found this document useful (0 votes)
0 views53 pages

Term Work

The document contains multiple C programming tasks completed by Anishk Singh, a BTECH CSE student. The tasks include implementing a priority queue using a doubly linked list, finding the union of two linked lists, splitting a linked list into two based on position, creating a binary search tree with various operations, and implementing Kruskal's algorithm for finding a minimal spanning tree. Each task is accompanied by code snippets and sample outputs demonstrating the functionality.

Uploaded by

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

Term Work

The document contains multiple C programming tasks completed by Anishk Singh, a BTECH CSE student. The tasks include implementing a priority queue using a doubly linked list, finding the union of two linked lists, splitting a linked list into two based on position, creating a binary search tree with various operations, and implementing Kruskal's algorithm for finding a minimal spanning tree. Each task is accompanied by code snippets and sample outputs demonstrating the functionality.

Uploaded by

omniscienthound9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q1. Write a C program to implement priority queue using doubly linked list
(Priority

depends on identity number. Small identity number has greater priority. If


identity numbers

are equal. Then FIFO rules are used with following functions,

1) insert 2) delete 3) display

CODE :

#include <stdio.h>

#include <stdlib.h>

typedef struct Node {

int id;

struct Node *prev, *next;

} Node;

Node *head = NULL;

Node* createNode(int id) {

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

newNode->id = id;

newNode->prev = newNode->next = NULL;

return newNode;
}

void insert(int id) {

Node *newNode = createNode(id);

if (head == NULL) {

head = newNode;

return;

Node *current = head;

while (current && current->id <= id) {

current = current->next;

if (current == NULL) {

Node *tail = head;

while (tail->next) {

tail = tail->next;

tail->next = newNode;

newNode->prev = tail;

} else if (current == head) {

newNode->next = head;

head->prev = newNode;

head = newNode;

} else {

newNode->next = current;
newNode->prev = current->prev;

current->prev->next = newNode;

current->prev = newNode;

void delete() {

if (head == NULL) {

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

return;

Node *temp = head;

head = head->next;

if (head) {

head->prev = NULL;

free(temp);

void display() {

if (head == NULL) {

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

return;

Node *current = head;

while (current) {
printf("%d ", current->id);

current = current->next;

printf("\n");

int main() {

int choice, id;

while (1) {

printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter identity number: ");

scanf("%d", &id);

insert(id);

break;

case 2:

delete();

break;

case 3:

display();

break;

case 4:
exit(0);

default:

printf("Invalid choice.\n");

return 0;

}
Output:

1. Insert

2. Delete

3. Display

4. Exit

Enter your choice: 1

Enter identity number: 15

Enter your choice: 1

Enter identity number: 10

Enter your choice: 1

Enter identity number: 20

Enter your choice: 3

10 15 20

Enter your choice: 2

Enter your choice: 3

15 20

Enter your choice: 2

Enter your choice: 3

20

Enter your choice: 2

Queue is empty.

Enter your choice: 5

Invalid choice.

Enter your choice: 4


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q2. Write a C program to find union (of two linked lists) based on their
information field

that implements singly linked list (with information field Emp_Id and Name of
employee

for each node).

Code :

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct Node {

int Emp_Id;

char Name[50];

struct Node *next;

} Node;

Node* createNode(int id, char* name) {

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

newNode->Emp_Id = id;

strcpy(newNode->Name, name);

newNode->next = NULL;
return newNode;

void insert(Node **head, int id, char *name) {

Node *newNode = createNode(id, name);

if (*head == NULL) {

*head = newNode;

return;

Node *temp = *head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

int exists(Node *head, int id) {

while (head) {

if (head->Emp_Id == id) {

return 1;

head = head->next;

return 0;

Node* unionLists(Node *list1, Node *list2) {


Node *unionHead = NULL, *temp;

temp = list1;

while (temp) {

insert(&unionHead, temp->Emp_Id, temp->Name);

temp = temp->next;

temp = list2;

while (temp) {

if (!exists(unionHead, temp->Emp_Id)) {

insert(&unionHead, temp->Emp_Id, temp->Name);

temp = temp->next;

return unionHead;

void display(Node *head) {

while (head) {

printf("Emp_Id: %d, Name: %s\n", head->Emp_Id, head->Name);

head = head->next;

int main() {

Node *list1 = NULL, *list2 = NULL, *unionList = NULL;

int n1, n2, id;


char name[50];

printf("Enter number of employees in list 1: ");

scanf("%d", &n1);

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

printf("Enter Emp_Id and Name: ");

scanf("%d %s", &id, name);

insert(&list1, id, name);

printf("Enter number of employees in list 2: ");

scanf("%d", &n2);

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

printf("Enter Emp_Id and Name: ");

scanf("%d %s", &id, name);

insert(&list2, id, name);

unionList = unionLists(list1, list2);

printf("Union of the two lists:\n");

display(unionList);

return 0;

}
Output :

Enter number of employees in list 1: 3

Enter Emp_Id and Name: 101 John

Enter Emp_Id and Name: 102 Alice

Enter Emp_Id and Name: 103 Bob

Enter number of employees in list 2: 2

Enter Emp_Id and Name: 102 Alice

Enter Emp_Id and Name: 104 David

Union of the two lists:

Emp_Id: 101, Name: John

Emp_Id: 102, Name: Alice

Emp_Id: 103, Name: Bob

Emp_Id: 104, Name: David


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q3. Write a C program to create a linked list P, then write a ‘C’ function named
split to

create two linked lists Q & R from P So that Q contains all elements in odd
positions of P

and R contains the remaining elements. Finally print both linked lists i.e. Q and
R.

code :

#include <stdio.h>

#include <stdlib.h>

typedef struct Node {

int data;

struct Node *next;

} Node;

Node* createNode(int data) {

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

newNode->data = data;
newNode->next = NULL;

return newNode;

void insert(Node **head, int data) {

Node *newNode = createNode(data);

if (*head == NULL) {

*head = newNode;

return;

Node *temp = *head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

void split(Node *P, Node **Q, Node **R) {

int position = 1;

while (P) {

if (position % 2 == 1) {

insert(Q, P->data);

} else {

insert(R, P->data);

P = P->next;
position++;

void display(Node *head) {

while (head) {

printf("%d ", head->data);

head = head->next;

printf("\n");}

int main() {

Node *P = NULL, *Q = NULL, *R = NULL;

int n, data;

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

scanf("%d", &n);

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

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

scanf("%d", &data);

insert(&P, data); }

split(P, &Q, &R);

printf("Elements in list Q (odd positions): ");

display(Q);

printf("Elements in list R (even positions): ");

display(R);

return 0;}
Output

Enter the number of elements in the list P: 6

Enter the elements of list P:

123456

Elements in list Q (odd positions): 1 3 5

Elements in list R (even positions): 2 4 6


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q4. Write a C program to create a binary search tree and perform following
operations:

1) Find node having smallest data in the BST.

2) Delete a node from the tree.

3) Find total number nodes having common parent.

4) Find height of a binary search tree

5) Count total numbers of nodes from right hand side of root node

#include <stdio.h>

#include <stdlib.h>

typedef struct Node {

int data;

struct Node *left, *right;

} Node;

Node* createNode(int data) {

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

newNode->data = data;

newNode->left = newNode->right = NULL;

return newNode;

}
Node* insert(Node *root, int data) {

if (root == NULL) {

return createNode(data);

if (data < root->data) {

root->left = insert(root->left, data);

} else if (data > root->data) {

root->right = insert(root->right, data);

return root;

Node* findMin(Node *root) {

while (root && root->left) {

root = root->left;

return root;

Node* deleteNode(Node *root, int data) {

if (root == NULL) return root;

if (data < root->data) {

root->left = deleteNode(root->left, data);

} else if (data > root->data) {

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

} else {
if (root->left == NULL) {

Node *temp = root->right;

free(root);

return temp;

} else if (root->right == NULL) {

Node *temp = root->left;

free(root);

return temp;

Node *temp = findMin(root->right);

root->data = temp->data;

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

return root;

int countSiblings(Node *root) {

if (!root) return 0;

int count = 0;

if (root->left && root->right) {

count = 2;

} else if (root->left || root->right) {

count = 1;
}

return count + countSiblings(root->left) + countSiblings(root->right);

int findHeight(Node *root) {

if (root == NULL) return 0;

int leftHeight = findHeight(root->left);

int rightHeight = findHeight(root->right);

return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;

int countRightNodes(Node *root) {

if (root == NULL || root->right == NULL) return 0;

return 1 + countRightNodes(root->right) + countRightNodes(root->right-


>left);

void inorder(Node *root) {

if (root == NULL) return;

inorder(root->left);

printf("%d ", root->data);

inorder(root->right);

int main() {
Node *root = NULL;

int choice, data;

while (1) {

printf("\n1. Insert\n2. Find smallest node\n3. Delete node\n4. Count nodes


with common parent\n5. Find height\n6. Count nodes on right of root\n7.
Display tree (inorder)\n8. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter data to insert: ");

scanf("%d", &data);

root = insert(root, data);

break;

case 2:

if (root) {

Node *minNode = findMin(root);

printf("Smallest node: %d\n", minNode->data);

} else {

printf("Tree is empty.\n"); }

break;

case 3:

printf("Enter data to delete: ");


scanf("%d", &data);

root = deleteNode(root, data);

break;

case 4:

printf("Total nodes with common parent: %d\n", countSiblings(root));

break;

case 5:

printf("Height of BST: %d\n", findHeight(root));

break;

case 6:

printf("Total nodes on right side of root: %d\n",


countRightNodes(root));

break;

case 7:

printf("Tree (inorder traversal): ");

inorder(root);

printf("\n");

break;

case 8:

exit(0);

default:

printf("Invalid choice.\n");

}}

return 0;}
Output :

Enter your choice: 1

Enter data to insert: 50

Enter your choice: 1

Enter data to insert: 30

Enter your choice: 1

Enter data to insert: 70

Enter your choice: 7

Tree (inorder traversal): 30 50 70

Enter your choice: 2

Smallest node: 30

Enter your choice: 3

Enter data to delete: 30

Enter your choice: 7

Tree (inorder traversal): 50 70

Enter your choice: 5

Height of BST: 2

Enter your choice: 8


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q5. Write a C program to implement Kurskal’s algorithm to find minimal


spanning tree

from a given graph.

Code:

#include <stdio.h>

#include <stdlib.h>

typedef struct Edge {

int src, dest, weight;

} Edge;

typedef struct Graph {

int V, E;

Edge* edges;

} Graph;

Graph* createGraph(int V, int E) {

Graph* graph = (Graph*)malloc(sizeof(Graph));

graph->V = V;

graph->E = E;
graph->edges = (Edge*)malloc(E * sizeof(Edge));

return graph;

typedef struct Subset {

int parent;

int rank;

} Subset;

int find(Subset subsets[], int i) {

if (subsets[i].parent != i) {

subsets[i].parent = find(subsets, subsets[i].parent);

return subsets[i].parent;

void Union(Subset subsets[], int x, int y) {

int rootX = find(subsets, x);

int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank) {

subsets[rootX].parent = rootY;

} else if (subsets[rootX].rank > subsets[rootY].rank) {

subsets[rootY].parent = rootX;
} else {

subsets[rootY].parent = rootX;

subsets[rootX].rank++;

int compareEdges(const void* a, const void* b) {

Edge* edgeA = (Edge*)a;

Edge* edgeB = (Edge*)b;

return edgeA->weight - edgeB->weight;

void KruskalMST(Graph* graph) {

int V = graph->V;

Edge result[V];

int e = 0;

int i = 0;

qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compareEdges);

Subset* subsets = (Subset*)malloc(V * sizeof(Subset));

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

subsets[v].parent = v;

subsets[v].rank = 0;
}

while (e < V - 1 && i < graph->E) {

Edge nextEdge = graph->edges[i++];

int x = find(subsets, nextEdge.src);

int y = find(subsets, nextEdge.dest);

if (x != y) {

result[e++] = nextEdge;

Union(subsets, x, y);

printf("Edges in the Minimum Spanning Tree:\n");

int minCost = 0;

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

printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);

minCost += result[i].weight;

printf("Total cost of MST: %d\n", minCost);

free(subsets);

}
int main() {

int V, E;

printf("Enter the number of vertices and edges: ");

scanf("%d %d", &V, &E);

Graph* graph = createGraph(V, E);

printf("Enter the edges (source, destination, weight):\n");

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

scanf("%d %d %d", &graph->edges[i].src, &graph->edges[i].dest,


&graph->edges[i].weight);

KruskalMST(graph);

free(graph->edges);

free(graph);

return 0;

}
OUTPUT:

Enter the number of vertices and edges: 4 5

Enter the edges (source, destination, weight):

0 1 10

026

035

1 3 15

234

Edges in the Minimum Spanning Tree:

2 -- 3 == 4

0 -- 3 == 5

0 -- 1 == 10

Total cost of MST: 19


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q6. Write a C program to sort N names (as a string) given by user in an array,
using Quick

sort technique.

Code:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void swap(char* str1, char* str2) {

char temp[100];

strcpy(temp, str1);

strcpy(str1, str2);

strcpy(str2, temp);

int partition(char arr[][100], int low, int high) {

char pivot[100];

strcpy(pivot, arr[high]);

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

if (strcmp(arr[j], pivot) < 0) {

i++;

swap(arr[i], arr[j]);

swap(arr[i + 1], arr[high]);

return i + 1;

void quickSort(char arr[][100], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

int main() {

int n;

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

scanf("%d", &n);

char names[n][100];
printf("Enter %d names:\n", n);

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

scanf("%s", names[i]);

quickSort(names, 0, n - 1);

printf("Sorted names:\n");

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

printf("%s\n", names[i]);

return 0;

}
OUTPUT :

Enter the number of names: 5

Enter 5 names:

Ravi

Priya

Ananya

Arjun

Rahul

Sorted names:

Ananya

Arjun

Priya

Rahul

Ravi
Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q7. Write a C program using circular linked list allocate time slots of 10 ms for
given

processes in time sharing environment and then print which process will be
completed in

how much time.

Code:

#include <stdio.h>

#include <stdlib.h>

typedef struct Process {

int id;

int burstTime;

struct Process* next;

} Process;

Process* createNode(int id, int burstTime) {

Process* newNode = (Process*)malloc(sizeof(Process));

newNode->id = id;

newNode->burstTime = burstTime;

newNode->next = newNode; // Circular property

return newNode;

}
void insert(Process** head, int id, int burstTime) {

Process* newNode = createNode(id, burstTime);

if (*head == NULL) {

*head = newNode;

return;

Process* temp = *head;

while (temp->next != *head) {

temp = temp->next;

temp->next = newNode;

newNode->next = *head;

void simulateTimeSharing(Process* head) {

if (!head) return;

int timeElapsed = 0;

Process* current = head;

do {

if (current->burstTime > 0) {

int timeSlice = (current->burstTime >= 10) ? 10 : current->burstTime;

current->burstTime -= timeSlice;

timeElapsed += timeSlice;

if (current->burstTime == 0) {

printf("Process P%d completed in %d ms\n", current->id,


timeElapsed);
}

current = current->next;

} while (current != head);

int main() {

Process* head = NULL;

int n, id, burstTime;

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

scanf("%d", &n);

printf("Enter process IDs and their burst times:\n");

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

printf("Process ID: ");

scanf("%d", &id);

printf("Burst Time: ");

scanf("%d", &burstTime);

insert(&head, id, burstTime);

simulateTimeSharing(head);

return 0;

}
OUTPUT:

Enter the number of processes: 3

Enter process IDs and their burst times:

Process ID: 1

Burst Time: 25

Process ID: 2

Burst Time: 15

Process ID: 3

Burst Time: 30

Process P1 completed in 25 ms

Process P2 completed in 40 ms

Process P3 completed in 70 ms
Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q8. Write a C program to store the details of a weighted graph (Using linked
list).

Code:

#include <stdio.h>

#include <stdlib.h>

typedef struct EdgeNode {

int dest;

int weight;

struct EdgeNode* next;

} EdgeNode;

typedef struct GraphNode {

int vertex;

EdgeNode* edges;

struct GraphNode* next;

} GraphNode;

typedef struct Graph {

GraphNode* head;
} Graph;

Graph* createGraph() {

Graph* graph = (Graph*)malloc(sizeof(Graph));

graph->head = NULL;

return graph;

GraphNode* createGraphNode(int vertex) {

GraphNode* newNode = (GraphNode*)malloc(sizeof(GraphNode));

newNode->vertex = vertex;

newNode->edges = NULL;

newNode->next = NULL;

return newNode;

EdgeNode* createEdgeNode(int dest, int weight) {

EdgeNode* newNode = (EdgeNode*)malloc(sizeof(EdgeNode));

newNode->dest = dest;

newNode->weight = weight;

newNode->next = NULL;

return newNode;

}
void addEdge(Graph* graph, int src, int dest, int weight) {

GraphNode* srcNode = graph->head;

while (srcNode && srcNode->vertex != src) {

srcNode = srcNode->next;

if (!srcNode) {

srcNode = createGraphNode(src);

srcNode->next = graph->head;

graph->head = srcNode;

EdgeNode* newEdge = createEdgeNode(dest, weight);

newEdge->next = srcNode->edges;

srcNode->edges = newEdge;

void displayGraph(Graph* graph) {

GraphNode* current = graph->head;

while (current) {

printf("Vertex %d:\n", current->vertex);

EdgeNode* edge = current->edges;

while (edge) {

printf(" -> (Dest: %d, Weight: %d)\n", edge->dest, edge->weight);

edge = edge->next;
}

current = current->next;

int main() {

Graph* graph = createGraph();

int n, src, dest, weight;

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

scanf("%d", &n);

printf("Enter edges (source, destination, weight):\n");

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

scanf("%d %d %d", &src, &dest, &weight);

addEdge(graph, src, dest, weight);

printf("Graph representation:\n");

displayGraph(graph);

return 0;

}
OUTPUT:

Enter the number of edges: 4

Enter edges (source, destination, weight):

0 1 10

0 2 20

1 2 30

2 3 40
Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q9. Write a menu driven program to implement DFS.

Code:

#include <stdio.h>

#include <stdlib.h>

typedef struct Graph {

int** adjMatrix;

int vertices;

} Graph;

void initializeGraph(Graph* g, int vertices) {

g->vertices = vertices;

g->adjMatrix = (int*)malloc(vertices * sizeof(int));

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

g->adjMatrix[i] = (int*)malloc(vertices * sizeof(int));

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

for (int j = 0; j < vertices; j++) {

g->adjMatrix[i][j] = 0;

}
}

void addEdge(Graph* g, int src, int dest) {

if (src >= 0 && src < g->vertices && dest >= 0 && dest < g->vertices) {

g->adjMatrix[src][dest] = 1;

g->adjMatrix[dest][src] = 1;

} else {

printf("Invalid vertex number.\n");

void DFS(Graph* g, int startVertex, int visited[]) {

int stack[g->vertices];

int top = -1;

stack[++top] = startVertex;

visited[startVertex] = 1;

printf("DFS Traversal: ");

while (top != -1) {

int currentVertex = stack[top--];

printf("%d ", currentVertex);

for (int i = 0; i < g->vertices; i++) {

if (g->adjMatrix[currentVertex][i] == 1 && !visited[i]) {

stack[++top] = i;

visited[i] = 1;

}
}

printf("\n");

void displayGraph(Graph* g) {

printf("Adjacency Matrix:\n");

for (int i = 0; i < g->vertices; i++) {

for (int j = 0; j < g->vertices; j++) {

printf("%d ", g->adjMatrix[i][j]);

printf("\n");

int main() {

Graph g;

int choice, src, dest, startVertex;

printf("Enter number of vertices: ");

scanf("%d", &g.vertices);

initializeGraph(&g, g.vertices);

int visited[g.vertices];

for (int i = 0; i < g.vertices; i++) {

visited[i] = 0;

do {

printf("\nMenu:\n");
printf("1. Add edge\n");

printf("2. Display graph\n");

printf("3. DFS traversal\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter source and destination vertices (0 to %d): ", g.vertices1);

scanf("%d %d", &src, &dest);

addEdge(&g, src, dest);

break;

case 2:

displayGraph(&g);

break;

case 3:

printf("Enter the starting vertex for DFS: ");

scanf("%d", &startVertex);

for (int i = 0; i < g.vertices; i++) {

visited[i] = 0;

DFS(&g, startVertex, visited);

break;

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

break;

default:

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

break;

} while (choice != 4);

for (int i = 0; i < g.vertices; i++) {

free(g.adjMatrix[i]);

free(g.adjMatrix);

return 0;

}
OUTPUT :

Enter number of vertices: 5

1. Add edge

2. Display graph

3. DFS traversal

4. Exit

Enter your choice: 1

Enter source and destination vertices (0 to 4): 0 1

1. Add edge

2. Display graph

3. DFS traversal

4. Exit

Enter your choice: 2

Adjacency Matrix:

01000

10000

00000

00000

00000

1. Add edge

2. Display graph

3. DFS traversal

4. Exit

Enter your choice: 3

Enter starting vertex for DFS: 0


Name : Anishk Singh

Section: J1

Roll no : 29

Sem: 3 (BTECH CSE)

Q10. Write a menu driven program to implement BFS.

Code:

#include <stdio.h>

#include <stdlib.h>

typedef struct Graph {

int** adjMatrix;

int vertices;

} Graph;

void initializeGraph(Graph* g, int vertices) {

g->vertices = vertices;

g->adjMatrix = (int*)malloc(vertices * sizeof(int));

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

g->adjMatrix[i] = (int*)malloc(vertices * sizeof(int));

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

for (int j = 0; j < vertices; j++) {

g->adjMatrix[i][j] = 0;

}
}

void addEdge(Graph* g, int src, int dest) {

if (src >= 0 && src < g->vertices && dest >= 0 && dest < g->vertices) {

g->adjMatrix[src][dest] = 1;

g->adjMatrix[dest][src] = 1;

} else {

printf("Invalid vertex number.\n");

void BFS(Graph* g, int startVertex) {

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

int* queue = (int*)malloc(g->vertices * sizeof(int));

int front = -1, rear = -1;

for (int i = 0; i < g->vertices; i++) {

visited[i] = 0;

visited[startVertex] = 1;

queue[++rear] = startVertex;

printf("BFS Traversal: ");

while (front != rear) {

int currentVertex = queue[++front];

printf("%d ", currentVertex);

for (int i = 0; i < g->vertices; i++) {


if (g->adjMatrix[currentVertex][i] == 1 && !visited[i]) {

visited[i] = 1;

queue[++rear] = i;

printf("\n");

free(visited);

free(queue);

void displayGraph(Graph* g) {

printf("Adjacency Matrix:\n");

for (int i = 0; i < g->vertices; i++) {

for (int j = 0; j < g->vertices; j++) {

printf("%d ", g->adjMatrix[i][j]);

printf("\n");

int main() {

Graph g;

int choice, src, dest, startVertex;

printf("Enter number of vertices: ");

scanf("%d", &g.vertices);
initializeGraph(&g, g.vertices);

do {

printf("\nMenu:\n");

printf("1. Add edge\n");

printf("2. Display graph\n");

printf("3. BFS traversal\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter source and destination vertices (0 to %d): ", g.vertices -


1);

scanf("%d %d", &src, &dest);

addEdge(&g, src, dest);

break;

case 2:

displayGraph(&g);

break;

case 3:

printf("Enter the starting vertex for BFS: ");

scanf("%d", &startVertex);

BFS(&g, startVertex);

break;

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

break;

default:

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

break;

} while (choice != 4);

for (int i = 0; i < g.vertices; i++) {

free(g.adjMatrix[i]);

free(g.adjMatrix);

return 0;

}
OUTPUT:
Enter number of vertices: 4

Menu:

1. Add edge

2. Display graph

3. BFS traversal

4. Exit

Enter your choice: 1

Enter source and destination vertices (0 to 3): 0 1

Enter your choice: 1

Enter source and destination vertices (0 to 3): 1 2

Enter your choice: 2

Adjacency Matrix:

0100

1010

0100

0000

Enter your choice: 3

Enter the starting vertex for BFS: 0

BFS Traversal: 0 1 2

You might also like