0% found this document useful (0 votes)
31 views70 pages

DS LAB MANUAL

The document is a laboratory manual for the Data Structures Lab (CS1208) for B. Tech students in various computer science specializations. It outlines the department's vision and mission, course objectives, program outcomes, and specific lab instructions, along with a syllabus detailing various C programming tasks related to data structures. Additionally, it provides examples of C programs for recursion, queues, and other data structures.

Uploaded by

raju reddy
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)
31 views70 pages

DS LAB MANUAL

The document is a laboratory manual for the Data Structures Lab (CS1208) for B. Tech students in various computer science specializations. It outlines the department's vision and mission, course objectives, program outcomes, and specific lab instructions, along with a syllabus detailing various C programming tasks related to data structures. Additionally, it provides examples of C programs for recursion, queues, and other data structures.

Uploaded by

raju reddy
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/ 70

DATA STRUCTURES LAB

(CS1208)
LABORATORY MANUAL & RECORD

B. Tech (Common for CSE, AI, AI&ML and AI&DS)


(With effect from 2022-23 admitted batches)
(I YEAR- IISEM)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

SANKETIKA VIDYA PARISHAD ENGINEERING


COLLEGE
(APPROVED BY AICTE, AFFILIARED TO ANDHRA UNIVERSITY,
ACCREDITED BY NAAC-A GRADE, ISO 9001:2015 CERFIFIED)
PM PALEM, VISAKHAPATNAM-41,
www.svpce.edu.in

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


INSTITUTE VISION AND MISSION
VISION
To be a premier institute of knowledge of share quality research and development
technologies towards national buildings

MISSION
1. Develop the state of the art environment of high quality of learning
2. Collaborate with industries and academic towards training research innovation and
entrepreneurship

3. Create a platform of active participation co-circular and extra- circular activities

DEPARTMENT VISION AND MISSION


VISION
To impart quality education for producing highly talented globally recognizable techno carts
and entrepreneurs with innovative ideas in computer science and engineering to meet
industrial needs and societal expectations

MISSION
 To impart high standard value-based technical education in all aspects of Computer
Science and Engineering through the state of the art infrastructure and innovative
approach.

 To produce ethical, motivated, and skilled engineers through theoretical knowledge


and practical applications.

 To impart the ability for tackling simple to complex problems individually as well as
in a team.

 To develop globally competent engineers with strong foundations, capable of “out of


the box” thinking so as to adapt to the rapidly changing scenarios requiring socially
conscious green computing solutions.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)


Graduates of B. Tech in computer science and Engineering Programme shall be able to
PEO1: Strong foundation of knowledge and skills in the field of Computer Science and
Engineering.

PEO2: Provide solutions to challenging problems in their profession by applying computer


engineering theory and practices.

PEO3: Produce leadership and are effective in multidisciplinary environment.

PROGRAMME SPECIFIC OUTCOMES (PSOs)


PSO1: Ability to design and develop computer programs and understand the structure and
development methodologies of software systems.

PSO2: Ability to apply their skills in the field of networking, web design, cloud computing
and data analytics.

PSO3: Ability to understand the basic and advanced computing technologies towards getting
employed or to become an entrepreneur
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PROGRAM OUTCOMES

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem Analysis: Identify, formulate, research literature, and analyze complex


engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3. Design/Development of Solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct Investigations of Complex Problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.

6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

7. Environment and Sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9. Individual and Team Work: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, give and
receive clear instructions.

11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-Long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE OBJECTIVES
• To implement stacks and queues using arrays and linked lists.

• To develop programs for searching and sorting algorithms.

• To write programs using concepts of various trees.

• To implement programs using graphs.

COURSE OUTCOMES (CO)

After completion of the course, students will be able to:


CO1: Design the c programming in type casting and mathh functions
CO2: Develop the programming by using decision making statements
CO3: Demonstrate effective use of C features including arrays, strings
CO4: Illustrate modular programming using functions
CO5: Create the programming by using pointers and files
CO6: Apply the file concepts in structure and unions
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.

3. Student should enter into the laboratory with:

a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.

b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.

c. Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.

5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.

6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.

7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.

8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.

9. Students must take the permission of the faculty in case of any urgency to go out; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.

10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly
CS1208 DATA STRUCTURES LAB
Syllabus

1. Write a C program to print array elements using recursion.


2. Write a C program to solve the towers of Hanoi problem using
recursion.
3. a)Write a C program for implementing the operations on queue.
b)Write a C program for implementing the operations on priority queue.
4. Write a C program for implementing the operations on circular queue.
5. Write a C program for implementing the operations on stacks.
6. Write a C program for evaluating a given postfix expression using
stack.
7. Write a C program for evaluating a given infix expression to Postfix
expression.
8. a)Write a C program for implement the operations on single Linked list.
b)Write a C program for implement the operations on double Linked list.
9. Write a C program for representation of polynomial using
circular linked list and for the addition of two such polynomials
10. Write a C program to create a binary search tree and for implementing the in-order, pre-
order and post-order traversal using recursion.
11. Write a C program for sorting a list using Bubble sort
12. Write a C program for sorting a list and then apply binary search.
13. a)Write a C program for finding the shortest transitive closure of a
digraph.
b) Write a C program for finding the shortest path from a given
source to any vertex in an digraph using Dijkstra’s algorithm.
14. a)Write a C program for finding the Depth First Search of a graph.
b) Write a C program for finding the Breadth First Search of a graph.

References:
1. Data Structures Using C and C++ Yddish Langsam, Moshe J. Augenstein and Aaron
M.Tanenbaum, Prentice Hall Of India (2nd Edition)
2. Data Structures, Algorithms and Applications with C++, Sahani Mc-Graw Hill.
TABLE OF CONTENTS

Sl. CONTENT Page


No No
1 Write a C program to print array elements using recursion.
2 Write a C program to solve the towers of Hanoi problem using
recursion.
3 a)Write a C program for implementing the operations on queue.
b)Write a C program for implementing the operations on priority queue.
4 Write a C program for implementing the operations on circular queue.
5 Write a C program for implementing the operations on stacks.

6 Write a C program for evaluating a given postfix expression using


stack.
7 Write a C program for evaluating a given infix expression to Postfix
expression.
8 a)Write a C program for implement the operations on single Linked list.
b)Write a C program for implement the operations on double Linked
list.
9 Write a C program for representation of polynomial using
circular linked list and for the addition of two such polynomials
10 Write a C program to create a binary search tree and for implementing
the in-order, pre-order and post-order traversal using recursion.
11 Write a C program for sorting a list using Bubble sort
12 Write a C program for sorting a list and then apply binary search.
13 a)Write a C program for finding the shortest transitive closure of a
digraph.
b) Write a C program for finding the shortest path from a given
source to any vertex in an digraph using Dijkstra’s algorithm.
14 a)Write a C program for finding the Depth First Search of a graph.
b) Write a C program for finding the Breadth First Search of a graph
Viva-Voce Questions

PROGRAM - 1
Aim : Write a C program to print array elements using recursion.

Program :

#include <stdio.h>

void printArray(int arr[], int size, int index)

if (index == size) {

return;

printf("%d ", arr[index]);

printArray(arr, size, index + 1);

int main() {

int arr[] = {10, 20, 30, 40, 50};

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

printf("Array elements are: ");

printArray(arr, size, 0);

return 0;

Output :

Array elements are : 10 20 30 40 50

PROGRAM – 2
Aim : Write a C program to solve the towers of Hanoi problem using
recursion.

Program :

#include <stdio.h>

void towersOfHanoi(int n, char source, char auxiliary, char destination) {

if (n == 1) {

printf("Move disk 1 from %c to %c\n", source, destination);

return;

towersOfHanoi(n - 1, source, destination, auxiliary);

printf("Move disk %d from %c to %c\n", n, source, destination);

towersOfHanoi(n - 1, auxiliary, source, destination);

int main() {

int n;

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

scanf("%d", &n);

printf("Steps to solve the Towers of Hanoi problem:\n");

towersOfHanoi(n, 'A', 'B', 'C');

return 0;

Output :
Enter the number of disks: 3

Steps to solve the Towers of Hanoi problem:

Move disk 1 from A to C

Move disk 2 from A to B

Move disk 1 from C to B

Move disk 3 from A to C

Move disk 1 from B to A

Move disk 2 from B to C

Move disk 1 from A to C

PROGRAM – 3

Aim :
a) Write a C program for implementing the operations on queue.

Program :

#include <stdio.h>

#define MAX 100

typedef struct {

int items[MAX];

int front;

int rear;

} Queue;

void initializeQueue(Queue *q) {

q->front = -1;

q->rear = -1;
}

int isEmpty(Queue *q) {

return q->front == -1;

int isFull(Queue *q) {

return q->rear == MAX - 1;

void enqueue(Queue *q, int value) {

if (isFull(q)) {

printf("Queue is full!\n");

return;

if (isEmpty(q)) {

q->front = 0;

q->rear++;

q->items[q->rear] = value;

printf("Enqueued: %d\n", value);

int dequeue(Queue *q) {

if (isEmpty(q)) {

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

return -1;

int value = q->items[q->front];

if (q->front == q->rear) {

q->front = q->rear = -1; // Reset the queue


} else {

q->front++;

printf("Dequeued: %d\n", value);

return value;

void display(Queue *q) {

if (isEmpty(q)) {

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

return;

printf("Queue elements: ");

for (int i = q->front; i <= q->rear; i++) {

printf("%d ", q->items[i]);

printf("\n");

int main() {

Queue q;

initializeQueue(&q);

int choice, value;

do {

printf("\nQueue Operations:\n");

printf("1. Enqueue\n");

printf("2. Dequeue\n");

printf("3. Display\n");

printf("4. Exit\n");
printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to enqueue: ");

scanf("%d", &value);

enqueue(&q, value);

break;

case 2:

dequeue(&q);

break;

case 3:

display(&q);

break;

case 4:

printf("Exiting...\n");

break;

default:

printf("Invalid choice!\n");

} while (choice != 4);

return 0;

Output :

Queue Operations:

1. Enqueue

2. Dequeue
3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 55

Enqueued: 55

Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 72

Enqueued: 72

Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 32

Enqueued: 32

Queue Operations:

1. Enqueue

2. Dequeue
3. Display

4. Exit

Enter your choice: 3

Queue elements: 55 72 32

Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 2

Dequeued: 55

Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 3

Queue elements: 72 32

Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 4


Exiting..

Aim :
b) Write a C program for implementing the operations on priority queue.

Program :

#include <stdio.h>
#include <stdlib.h>
struct PriorityQueue {
int *arr;
int size;
int capacity;
};
struct PriorityQueue* createPriorityQueue(int capacity) {
struct PriorityQueue *pq = (struct PriorityQueue*)malloc(sizeof(struct PriorityQueue));
pq->capacity = capacity;
pq->size = 0;
pq->arr = (int*)malloc(capacity * sizeof(int));
return pq;
}
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
void heapify(struct PriorityQueue *pq, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < pq->size && pq->arr[left] > pq->arr[largest]) {
largest = left;
}
if (right < pq->size && pq->arr[right] > pq->arr[largest]) {
largest = right;
}
if (largest != i) {
swap(&pq->arr[i], &pq->arr[largest]);
heapify(pq, largest);
}
}
void insert(struct PriorityQueue *pq, int element) {
if (pq->size == pq->capacity) {
printf("Priority Queue is full!\n");
return;
}
pq->size++;
int i = pq->size - 1;
pq->arr[i] = element;
while (i != 0 && pq->arr[(i - 1) / 2] < pq->arr[i]) {
swap(&pq->arr[i], &pq->arr[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
int extractMax(struct PriorityQueue *pq) {
if (pq->size <= 0) {
printf("Priority Queue is empty!\n");
return -1;
}
if (pq->size == 1) {
pq->size--;
return pq->arr[0];
}
int root = pq->arr[0];
pq->arr[0] = pq->arr[pq->size - 1];
pq->size--;
heapify(pq, 0);
return root;
}
int getMax(struct PriorityQueue *pq) {
if (pq->size <= 0) {
printf("Priority Queue is empty!\n");
return -1;
}
return pq->arr[0];
}
void display(struct PriorityQueue *pq) {
if (pq->size == 0) {
printf("Priority Queue is empty!\n");
return;
}
printf("Priority Queue elements: ");
for (int i = 0; i < pq->size; i++) {
printf("%d ", pq->arr[i]);
}
printf("\n");
}
int main() {
struct PriorityQueue *pq = createPriorityQueue(10);
insert(pq, 3);
insert(pq, 1);
insert(pq, 4);
insert(pq, 5);
insert(pq, 2);
display(pq);
printf("Maximum Element: %d\n", getMax(pq));
printf("Extracted Maximum Element: %d\n", extractMax(pq));
display(pq);
printf("Extracted Maximum Element: %d\n", extractMax(pq));
display(pq);
free(pq->arr);
free(pq);
return 0;
}

Output :

Priority Queue elements: 5 4 3 1 2

Maximum Element: 5

Extracted Maximum Element: 5

Priority Queue elements: 4 2 3 1

Extracted Maximum Element: 4

Priority Queue elements: 3 2 1

PROGRAM – 4

Aim : Write a C program for implementing the operations on circular queue.

Program :

#include <stdio.h>
#define MAX 100
typedef struct {
int items[MAX];
int front;
int rear;
} CircularQueue;
void initializeQueue(CircularQueue *q) {
q->front = -1;
q->rear = -1;
}
int isEmpty(CircularQueue *q) {
return q->front == -1;
}
int isFull(CircularQueue *q) {
return (q->rear + 1) % MAX == q->front;
}
void enqueue(CircularQueue *q, int value) {
if (isFull(q)) {
printf("Circular Queue is full!\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = value;
printf("Enqueued: %d\n", value);
}
int dequeue(CircularQueue *q) {
if (isEmpty(q)) {
printf("Circular Queue is empty!\n");
return -1;
}
int value = q->items[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1; // Reset the queue
} else {
q->front = (q->front + 1) % MAX;
}
printf("Dequeued: %d\n", value);
return value;
}
void display(CircularQueue *q) {
if (isEmpty(q)) {
printf("Circular Queue is empty!\n");
return;
}
printf("Circular Queue elements: ");
int i = q->front;
while (1) {
printf("%d ", q->items[i]);
if (i == q->rear) {
break;
}
i = (i + 1) % MAX;
}
printf("\n");
}
int main() {
CircularQueue q;
initializeQueue(&q);
int choice, value;
do {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
dequeue(&q);
break;
case 3:
display(&q);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}

Output :

Circular Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 99

Enqueued: 99

Circular Queue Operations:


1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 22

Enqueued: 22

Circular Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 1

Enter value to enqueue: 75

Enqueued: 75

Circular Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 3

Circular Queue elements: 99 22 75

Circular Queue Operations:

1. Enqueue
2. Dequeue

3. Display

4. Exit

Enter your choice: 2

Dequeued: 99

Circular Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 3

Circular Queue elements: 22 75

Circular Queue Operations:

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice: 4

Exiting...

PROGRAM – 5
Aim : Write a C program for implementing the operations on stacks.

Program :

#include <stdio.h>
#define MAX 100
typedef struct {
int items[MAX];
int top;
} Stack;
void initializeStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full!\n");
return;
}
s->items[++s->top] = value;
printf("Pushed: %d\n", value);
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
int value = s->items[s->top--];
printf("Popped: %d\n", value);
return value;
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
return s->items[s->top];
}
void display(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i <= s->top; i++) {
printf("%d ", s->items[i]);
}
printf("\n");
}
int main() {
Stack s;
initializeStack(&s);
int choice, value;
do {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(&s, value);
break;
case 2:
pop(&s);
break;
case 3:
value = peek(&s);
if (value != -1) {
printf("Top element: %d\n", value);
}
break;
case 4:
display(&s);
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 5);
return 0;
}

Output :

Stack Operations:
1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 1

Enter value to push: 55

Pushed: 55

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 1

Enter value to push: 12

Pushed: 12

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 1

Enter value to push: 35

Pushed: 35
Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 1

Enter value to push: 95

Pushed: 95

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 4

Stack elements: 55 12 35 95

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 3

Top element: 95
Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 2

Popped: 95

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 4

Stack elements: 55 12 35

Stack Operations:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice: 5

Exiting...
PROGRAM – 6

Aim : Write a C program for evaluating a given postfix expression using


stack.

Program :

#include <stdio.h>
#include <ctype.h>
#define MAX 100
typedef struct {
int items[MAX];
int top;
} Stack;
void initializeStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full!\n");
return;
}
s->items[++s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
return s->items[s->top--];
}
int evaluatePostfix(const char *expression) {
Stack s;
initializeStack(&s);
for (int i = 0; expression[i] != '\0'; i++) {
char ch = expression[i];
if (isdigit(ch)) {
push(&s, ch - '0');
} else {
int operand2 = pop(&s);
int operand1 = pop(&s);
switch (ch) {
case '+':
push(&s, operand1 + operand2);
break;
case '-':
push(&s, operand1 - operand2);
break;
case '*':
push(&s, operand1 * operand2);
break;
case '/':
if (operand2 != 0) {
push(&s, operand1 / operand2);
} else {
printf("Error: Division by zero!\n");
return -1;
}
break;
default:
printf("Error: Invalid operator '%c'!\n", ch);
return -1;
}
return pop(&s);
}
int main() {
char expression[MAX];
printf("Enter a postfix expression: ");
scanf("%s", expression);
int result = evaluatePostfix(expression);
if (result != -1) {
printf("The result of the postfix expression is: %d\n", result);
}
return 0;
}

Output :

Enter a postfix expression: 23+


The result of the postfix expression is: 5

PROGRAM – 7

Aim : Write a C program for evaluating a given infix expression to Postfix


expression.

Program :

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
typedef struct {
char data[MAX];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX - 1;
}
void push(Stack *s, char element) {
if (isFull(s)) {
printf("Stack Overflow\n");
return;
}
s->data[++(s->top)] = element;
}
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow\n");
return '\0';
}
return s->data[(s->top)--];
}
char peek(Stack *s) {
if (isEmpty(s)) {
return '\0';
}
return s->data[s->top];
}
int isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
void infixToPostfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i = 0, k = 0;
while (infix[i]) {
if (isdigit(infix[i]) || isalpha(infix[i])) {
postfix[k++] = infix[i];
} else if (infix[i] == '(') {
push(&s, infix[i]);
} else if (infix[i] == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[k++] = pop(&s);
}
pop(&s); // Remove '(' from stack
} else if (isOperator(infix[i])) {
while (!isEmpty(&s) && precedence(peek(&s)) >= precedence(infix[i])) {
postfix[k++] = pop(&s);
}
push(&s, infix[i]);
}
i++;
}
while (!isEmpty(&s)) {
postfix[k++] = pop(&s);
}
postfix[k] = '\0';
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter an infix expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}

Output :

Enter an infix expression: 2+3

Postfix expression: 23+

PROGRAM – 8

Aim :
a) Write a C program for implement the operations on single Linked list.

Program :

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
printf("Inserted %d at the beginning.\n", data);
}
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
printf("Inserted %d at the end.\n", data);
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
printf("Inserted %d at the end.\n", data);
}
void deleteByValue(struct Node** head, int value) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = *head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == value) {
*head = temp->next;
free(temp);
printf("Deleted %d from the list.\n", value);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Value %d not found in the list.\n", value);
return;
}
prev->next = temp->next;
free(temp);
printf("Deleted %d from the list.\n", value);
}
void displayList(struct Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
printf("Linked list: ");
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
int choice, value;
do {
printf("\nSingle Linked List Operations:\n");
printf("1. Insert at beginning\n");
printf("2. Insert at end\n");
printf("3. Delete by value\n");
printf("4. Display list\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert at beginning: ");
scanf("%d", &value);
insertAtBeginning(&head, value);
break;
case 2:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(&head, value);
break;
case 3:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteByValue(&head, value);
break;
case 4:
displayList(head);
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 5);
return 0;
}

Output :

Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 1

Enter value to insert at beginning: 25

Inserted 25 at the beginning.

Single Linked List Operations:

1. Insert at beginning
2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 1

Enter value to insert at beginning: 63

Inserted 63 at the beginning.

Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 2

Enter value to insert at end: 15

Inserted 15 at the end.

Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 2

Enter value to insert at end: 74

Inserted 74 at the end.


Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 4

Linked list: 63 -> 25 -> 15 -> 74 -> NULL

Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 3

Enter value to delete: 15

Deleted 15 from the list.

Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 4

Linked list: 63 -> 25 -> 74 -> NULL


Single Linked List Operations:

1. Insert at beginning

2. Insert at end

3. Delete by value

4. Display list

5. Exit

Enter your choice: 5

Exiting...

PROGRAM – 8

Aim :
b) Write a C program for implement the operations on double Linked list.

Program :

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
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;
}
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
void deleteNode(struct Node** head, int key) {
struct Node* temp = *head;
if (temp != NULL && temp->data == key) {
*head = temp->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) return;
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
free(temp);
}
void printListFromHead(struct Node* head) {
struct Node* temp = head;
printf("List from head: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
void printListFromTail(struct Node* head) {
struct Node* temp = head;
if (temp == NULL) {
printf("List from tail: NULL\n");
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
printf("List from tail: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->prev;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertAtBeginning(&head, 10);
insertAtBeginning(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);

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


printListFromHead(head);
printListFromTail(head);
deleteNode(&head, 20);
printf("Doubly Linked List after deletion:\n");
printListFromHead(head);
printListFromTail(head);
return 0;
}

Output :

Doubly Linked List:

List from head: 20 -> 10 -> 30 -> 40 -> NULL

List from tail: 40 -> 30 -> 10 -> 20 -> NULL

Doubly Linked List after deletion:

List from head: 10 -> 30 -> 40 -> NULL

List from tail: 40 -> 30 -> 10 -> NULL

PROGRAM – 9
Aim : Write a C program for representation of polynomial using
circular linked list and for the addition of two such polynomials

Program :

#include <stdio.h>
#include <stdlib.h>
struct Node {
int coefficient;
int exponent;
struct Node* next;
};
struct Node* createNode(int coefficient, int exponent) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = newNode; // Circular link
return newNode;
}
void insertTerm(struct Node** poly, int coefficient, int exponent) {
struct Node* newNode = createNode(coefficient, exponent);
if (*poly == NULL) {
*poly = newNode;
return;
}
struct Node* temp = *poly;
while (temp->next != *poly && temp->next->exponent > exponent) {
temp = temp->next;
}
if (temp->next == *poly || temp->next->exponent < exponent) {
newNode->next = temp->next;
temp->next = newNode;
} else {
temp->next->coefficient += coefficient;
free(newNode);
}
}
struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {
struct Node* result = NULL;
struct Node* temp1 = poly1;
struct Node* temp2 = poly2;
do {
insertTerm(&result, temp1->coefficient, temp1->exponent);
temp1 = temp1->next;
} while (temp1 != poly1);
do {
insertTerm(&result, temp2->coefficient, temp2->exponent);
temp2 = temp2->next;
} while (temp2 != poly2);
return result;
}
void displayPolynomial(struct Node* poly) {
if (poly == NULL) {
printf("Polynomial is empty.\n");
return;
}
struct Node* temp = poly;
do {
printf("%d x^%d", temp->coefficient, temp->exponent);
temp = temp->next;
if (temp != poly) {
printf(" + ");
}
} while (temp != poly);
printf("\n");
}
int main() {
struct Node* poly1 = NULL;
struct Node* poly2 = NULL;
struct Node* result = NULL;
insertTerm(&poly1, 3, 3);
insertTerm(&poly1, 2, 2);
insertTerm(&poly1, 5, 1);
insertTerm(&poly1, 6, 0);
insertTerm(&poly2, 4, 3);
insertTerm(&poly2, 3, 2);
insertTerm(&poly2, 2, 1);
insertTerm(&poly2, 1, 0);
printf("Polynomial 1: ");
displayPolynomial(poly1);
printf("Polynomial 2: ");
displayPolynomial(poly2);
result = addPolynomials(poly1, poly2);
printf("Sum of polynomials: ");
displayPolynomial(result);
return 0;
}

Output :

Polynomial 1: 3 x^3 + 2 x^2 + 5 x^1 + 6 x^0


Polynomial 2: 4 x^3 + 3 x^2 + 2 x^1 + 1 x^0
Sum of polynomials: 7 x^3 + 5 x^2 + 7 x^1 + 7 x^0

PROGRAM – 10

Aim : Write a C program to create a binary search tree and for implementing the in-order,
pre-order and post-order traversal using recursion.

Program :

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
void inorderTraversal(struct Node* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
void preorderTraversal(struct Node* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(struct Node* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}

int main() {
struct Node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

printf("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;
}

Output :

In-order traversal: 20 30 40 50 60 70 80

Pre-order traversal: 50 30 20 40 70 60 80

Post-order traversal: 20 40 30 60 80 70 50

PROGRAM – 11

Aim : Write a C program for sorting a list using Bubble sort

Program :

#include <stdio.h>

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

int i, j, temp;

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

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

if (arr[j] > arr[j + 1]) {

temp = arr[j];

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


arr[j + 1] = temp;

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

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

printf("%d ", arr[i]);

printf("\n");

int main() {

int n, i;

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

scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);

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

scanf("%d", &arr[i]);

printf("Original array: ");

printArray(arr, n);

bubbleSort(arr, n);
printf("Sorted array: ");

printArray(arr, n);

return 0;

Output :

Enter the number of elements: 4


Enter 4 elements:
55
10
6
22
Original array: 55 10 6 22
Sorted array: 6 10 22 55

PROGRAM – 12

Aim : Write a C program for sorting a list and then apply binary search.

Program :

#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key)
return mid; // Key found at index mid
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; // Key not found
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n, i, key, result;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
printf("Enter the element to search: ");
scanf("%d", &key);
result = binarySearch(arr, n, key);
if (result != -1) {
printf("Element %d found at index %d\n", key, result);
} else {
printf("Element %d not found in the array\n", key);
}
return 0;
}

Output :

Enter the number of elements: 4


Enter 4 elements:
22
55
7
10
Sorted array: 7 10 22 55
Enter the element to search: 22
Element 22 found at index 2

PROGRAM – 13

Aim :
a) Write a C program for finding the shortest transitive closure of a
digraph.

Program :

#include <stdio.h>

#include <stdlib.h>

#define MAX 100


void printMatrix(int graph[MAX][MAX], int V) {

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

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

printf("%d ", graph[i][j]);

printf("\n");

void transitiveClosure(int graph[MAX][MAX], int V) {

int reach[MAX][MAX];

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

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

reach[i][j] = graph[i][j];

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

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

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

reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);

printf("Transitive Closure of the given graph:\n");

printMatrix(reach, V);

int main() {

int V;

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


scanf("%d", &V);

int graph[MAX][MAX];

printf("Enter the adjacency matrix of the graph (0 for no edge, 1 for edge):\n");

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

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

scanf("%d", &graph[i][j]);

transitiveClosure(graph, V);

return 0;

Output :

Enter the number of vertices: 4

Enter the adjacency matrix of the graph (0 for no edge, 1 for edge):

0100

0011

0001

0000

Transitive Closure of the given graph:

0111

0011

0001

0000
PROGRAM – 13

Aim :
b) Write a C program for finding the shortest path from a given
source to any vertex in an digraph using Dijkstra’s algorithm.

Program :

#include <stdio.h>

#include <limits.h>

#define MAX_VERTICES 10

int minDistance(int dist[], int visited[], int n) {

int min = INT_MAX, minIndex;

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

if (visited[v] == 0 && dist[v] <= min) {

min = dist[v];

minIndex = v;

return minIndex;

void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int source, int n) {

int dist[MAX_VERTICES]; // Array to store the shortest distance from source

int visited[MAX_VERTICES]; // Boolean array to track processed vertices

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

dist[i] = INT_MAX;

visited[i] = 0;

dist[source] = 0;

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


int u = minDistance(dist, visited, n);

visited[u] = 1;

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

if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] <

dist[v])

dist[v] = dist[u] + graph[u][v];

printf("Vertex \t Distance from Source\n");

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

if (dist[i] == INT_MAX)

printf("%d \t INF\n", i); // If no path exists, print INF

else

printf("%d \t %d\n", i, dist[i]);

int main() {

int n, source;

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

scanf("%d", &n);

int graph[MAX_VERTICES][MAX_VERTICES];

printf("Enter the adjacency matrix (0 for no edge, any positive number for edge weight):\
n");

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

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


scanf("%d", &graph[i][j]);

printf("Enter the source vertex: ");

scanf("%d", &source);

dijkstra(graph, source, n);

return 0;

Output :

Enter the number of vertices: 4

Enter the adjacency matrix (0 for no edge, any positive number for edge weight):

0500

0040

0002

0000

Enter the source vertex: 0

Vertex Distance from Source

0 0

1 5

2 9

3 11
PROGRAM – 14

Aim :
a) Write a C program for finding the Depth First Search of a graph.

Program :

#include <stdio.h>

#include <stdlib.h>

#define MAX_VERTICES 10

struct Node {

int vertex;

struct Node* next;

};

struct Graph {

int numVertices;

struct Node* adjLists[MAX_VERTICES];

int visited[MAX_VERTICES]; // Visited array

};

struct Node* createNode(int v) {

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

newNode->vertex = v;

newNode->next = NULL;

return newNode;

void initGraph(struct Graph* graph, int vertices) {

graph->numVertices = vertices;

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

graph->adjLists[i] = NULL;
graph->visited[i] = 0; // Initially, all vertices are unvisited

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

struct Node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

void DFS(struct Graph* graph, int vertex) {

graph->visited[vertex] = 1;

printf("%d ", vertex);

struct Node* adjList = graph->adjLists[vertex];

while (adjList != NULL) {

int connectedVertex = adjList->vertex;

if (!graph->visited[connectedVertex]) {

DFS(graph, connectedVertex); // Recursive DFS call

adjList = adjList->next;

void DFSFull(struct Graph* graph) {

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

if (!graph->visited[i]) {

DFS(graph, i); // Perform DFS from unvisited vertex


}

int main() {

struct Graph graph;

int vertices, edges, src, dest;

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

scanf("%d", &vertices);

initGraph(&graph, vertices);

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

scanf("%d", &edges);

printf("Enter the edges (source and destination vertices):\n");

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

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

addEdge(&graph, src, dest);

printf("\nDepth First Search (DFS) starting from vertex 0:\n");

DFSFull(&graph);

return 0;

Output :

Enter the number of vertices: 5

Enter the number of edges: 6

Enter the edges (source and destination vertices):

0 1

0 2
1 3

1 4

2 4

3 4

Depth First Search (DFS) starting from vertex 0:

0 2 4 3 1

PROGRAM – 14

Aim :
b) Write a C program for finding the Breadth First Search of a graph.

Program :

#include <stdio.h>

#include <stdlib.h>

#define MAX_VERTICES 10

struct Node {

int vertex;

struct Node* next;

};

struct Graph {

int numVertices;

struct Node* adjLists[MAX_VERTICES];

int visited[MAX_VERTICES]; // Visited array

};

struct Node* createNode(int v) {

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

newNode->vertex = v;
newNode->next = NULL;

return newNode;

void initGraph(struct Graph* graph, int vertices) {

graph->numVertices = vertices;

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

graph->adjLists[i] = NULL;

graph->visited[i] = 0; // Initially, all vertices are unvisited

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

struct Node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

void BFS(struct Graph* graph, int startVertex) {

struct Node* queue[MAX_VERTICES]; // Queue to store vertices for BFS

int front = -1, rear = -1; // Queue pointers

graph->visited[startVertex] = 1;

queue[++rear] = (struct Node*)malloc(sizeof(struct Node));

queue[rear]->vertex = startVertex;

while (front != rear) {

front++;

int currentVertex = queue[front]->vertex;


printf("%d ", currentVertex);

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

while (temp != NULL) {

int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0) {

graph->visited[adjVertex] = 1;

rear++;

queue[rear] = (struct Node*)malloc(sizeof(struct Node));

queue[rear]->vertex = adjVertex;

temp = temp->next;

void BFSFull(struct Graph* graph) {

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

if (!graph->visited[i]) {

BFS(graph, i); // Perform BFS from unvisited vertex

int main() {

struct Graph graph;

int vertices, edges, src, dest;

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

scanf("%d", &vertices);

initGraph(&graph, vertices);
printf("Enter the number of edges: ");

scanf("%d", &edges);

printf("Enter the edges (source and destination vertices):\n");

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

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

addEdge(&graph, src, dest);

printf("\nBreadth First Search (BFS) starting from vertex 0:\n");

BFSFull(&graph);

return 0;

OUTPUT :
Enter the number of vertices: 5

Enter the number of edges: 6

Enter the edges (source and destination vertices):

0 1

0 2

1 3

1 4

2 4

3 4

Breadth First Search (BFS) starting from vertex 0:

0 2 1 4 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy