sandeep 1
sandeep 1
number:24B11EC164
PRACTICE 1
Practice 1.1
Aim: Write a C program to find total, average of n students using structures
Description:
In C, structures are a way to group different types of variables under a single name. A
structure can hold variables of different data types, including arrays, pointers, and other
structures. This is particularly useful when you need to represent a record, such as a student
or an employee, where each record may contain different types of
information (name, age, salary, etc.).
Defining a Structure
You can define a structure using the struct keyword.
struct Person
{
char name[50];
int age;
float salary;
};
Array of structures:
An array of structures in programming is a collection where each element of the array is a
structure. A structure (often referred to as a struct) is a user-defined data type that groups
different data types together. This is useful when you want to
represent a record that holds various types of data under one name.
Program:
#include <stdio.h>
struct Student
Page
no:
Date: Roll
number:24B11EC164
{
char name[50];
int m1,m2,m3; // Assuming each student has 3 subjects
float total,avg;
};
int main()
{
int n, i;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student s[n];
// Input data for each student
for(i = 0; i < n; i++)
{
printf("enter name,3 subject marks of student %d\n",i+1);
scanf("%s%d%d%d",s[i].name,&s[i].m1,&s[i].m2,&s[i].m3); }
for(i=0;i<n;i++)
{
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3.0;
printf("Total and Average marks of Student %d=%.2f,%.2f\n",i+1,s[i].total,s[i].avg); }
return 0;
}
Page
no:
Date: Roll
number:24B11EC164
OUTPUT:
Enter the number of students: 2
enter name,3 subject marks of student 1
Aditya 56 78 57
enter name,3 subject marks of student 2
Vamc 99 98 67
Total and Average marks of Student 1=191.00,63.67
Total and Average marks of Student 2=264.00,88.00
Page
no:
Date: Roll
number:24B11EC164
Practice 1.2
AIM: Write a C Program copy one structure variable to another structure of the
same type
Description:
A structure assignment typically refers to the operation of assigning values between structures
or copying the contents of one structure to another. This can be done directly, using the
assignment operator (=), if the structures are of the same type. In a structure assignment, you
transfer the values of all fields from one structure to another.
Program:
#include<stdio.h>
struct student
{
char name[15];
int rno;
char gender;
};
int main()
{
struct student s1={"Srinu",143,'m'},s2;
s2=s1;
printf("The Student Details are:\n");
printf("Name:%s\nRno=%d\nGender=%c",s2.name,s2.rno,s2.gender); return 0;
}
OUTPUT:
The Student Details are:
Name: Aditya
Rno=143
Page
no:
Date: Roll
number:24B11EC164
Gender=m
Page
no:
Date: Roll
number:24B11EC164
Practice 1.3
AIM: Write a C Program read student name marks from the command line and
display the student details along with total
DESCRIPTION:
Command Line Arguments in C allow users to pass information to a program when executing
it from the command line or terminal. These arguments can be accessed inside the main()
function via the parameters argc (argument count) and argv (argument vector).
PROGRAM:
#include<stdio.h>
#include<string.h>
struct student
{
char name[10];
int s1,s2,s3,s4,s5;
};
int main(int argc,char *argv[])
{
struct student s;
int total;
strcpy(s.name,argv[1]);
s.s1=atoi(argv[2]);
s.s2=atoi(argv[3]);
s.s3=atoi(argv[4]);
s.s4=atoi(argv[5]);
s.s5=atoi(argv[6]);
total=s.s1+s.s2+s.s3+s.s4+s.s5;
printf("name\ts1\ts2\ts3\ts4\ts5\total\n");
printf("%s\t%d\t%d\t%d\t%d\t%d\t%d",s.name,s.s1,s.s2,s.s3,s.s4,s.s5,total);
return 0;
Page
no:
Date: Roll
number:24B11EC164
OUTPUT:
C:\Users\DS Programs>arg.exe Aditya 56 67 89 90 87
name s1 s2 s3 s4 s5 total
Aditya 56 67 89 90 87 389
Page
no:
Date: Roll
number:24B11EC164
PRACTICE 2
Practice 2.1
AIM : To perform sort of a given list of elements using Quick sort.
Description:
QuickSort is one of the best sorting algorithms that follows the divide-and-conquer approach
like Merge Sort but unlike Merge Sort, this algorithm does in place sorting. In this article, we
will learn how to implement quicksort in C language.
Introduction:
Quick sort is a sorting algorithm based on the partition and exchange that picks elements as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct
in the sorted array.
The key process in quick Sort is a partition. The target of partitions is to place the pivot (any
element can be chosen to be a pivot) at its correct position in the sorted array and put all
smaller elements to the left of the pivot, and all greater elements to the right of the pivot.
Partition is done recursively on each side of the pivot after the pivot is placed in its correct
position and this finally sorts the array.
Procedure:
• Open any C editor
• Write a C program
• Compile and run the code
• Note down the Output
Quicksort is a divide and conquer algorithm.
It divides the large array into smaller sub-arrays. And then quicksort recursively
sort the sub-arrays.e
Steps of QuickSort Algorithm:
1.Choose a Pivot: Select an element from the array as the pivot. Common
strategies include:
1.First element
2.Last element
3.Random element
Page
no:
Date: Roll
number:24B11EC164
4.Median of three
2.Partitioning:
1.Rearrange the elements so that:
1.Elements smaller than the pivot are placed to its left.
2.Elements greater than the pivot are placed to its right.
2.The pivot is now in its correct position.
Recursively Apply QuickSort:
1.Apply QuickSort on the left subarray (elements less than the pivot).
2.Apply QuickSort on the right subarray (elements greater than the
pivot).
Base Case:
1.When the subarray has one or zero elements, stop recursion.
Given Array:
[10, 15, 1, 2, 9, 16, 11]
Pivot Element: First element (10)
Step 1: Partitioning around Pivot (10)
[10, 15, 1, 2, 9, 16, 11]
↑
Pivot
•Elements less than 10: [1, 2, 9]
•Elements greater than 10: [15, 16, 11]
[9, 2, 1, 10, 15, 16, 11]
↑
Pivot placed
Pivot index = 3
Step 2: Quick Sort Left Subarray [9, 2, 1] [9, 2, 1]
↑
Pivot
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
OUTPUT:
How many number of elements you are going to enter?: 9 Enter 9 elements: 7 6 10 5 9 2
1 15 7
The Sorted elements are:
1 2 5 6 7 7 9 10 15
Page
no:
Date: Roll
number:24B11EC164
Practice 2.2
Aim: To perform sort of a given list of elements using merge sort.
Description:
Merge sort is a sorting algorithm that works by dividing an array into smaller sub arrays,
sorting each sub array, and then merging the sorted sub arrays back together to form the final
sorted array.
This process is repeated until the entire array is sorted.
Procedure:
Here is an example of how merge sort works: Let’s say we have an unsorted array of integers:
Page
no:
Date: Roll
number:24B11EC164
Program:
#include <stdio.h>
// Function to merge two halves of an array
void merge(int arr[], int low, int mid, int high)
{
int b[10]; // Temporary array
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
}
}
// Main function
int main()
{
int a[25],i,n;
printf("How many elements are you going to enter? "); scanf("%d", &n);
printf("Enter %d elements: ", n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergeSort(a, 0, n - 1);
printf("Sorted array:\n");
Page
no:
Date: Roll
number:24B11EC164
for(i=0;i<n;i++)
printf("%d\t",a[i]);
return 0;
}
OUTPUT:
Enter the number of elements to sort:6
Enter the elements:
40 60 30 50 10 20
List after sorting is
10 20 30 40 50 60
Page
no:
Date: Roll
number:24B11EC164
Practice 2.3
Aim : To perform sort of a given list of elements using Radix sort. Description:
Radix sort, to sort a given list of integers.
Radix Sort is a non-comparative sorting algorithm that sorts numbers by processing
individual digits. It works by sorting numbers digit by digit, starting from the least significant
digit (LSD) to the most significant digit (MSD) using a stable sorting algorithm (like
counting sort).
1.Find the Maximum Number: Determine the largest number in the array to
know the number of digits.
2.Sort Digit by Digit:
1.Sort the numbers based on the least significant digit (LSD). 2.Move to the next significant
digit and repeat.
3.Continue until the most significant digit (MSD) is sorted.
The Given array is
Largest=677
Nod=3//It will take 3 iterations
Iteration 1: Consider units position
•Insert 432 at b[2][0] and increments count[2] by 1
•Insert 8 at b[8][0] and increment count[8] by 1
•Insert 530 at b[0][0] and increment count[0] by 1
•Insert 90 at b[0][1] and increment count[0] by 1
•Insert 88 at b[8][1] and increment count[8] by 1
•Insert 231 at b[1][0] and increment count[1] by 1
•Insert 11 at b[1][1] and increment count[1] by 1
•Insert 45 at b[5][0] and increment count[5] by 1
•Insert 677 at b[7][0] and increment count[7] by 1
•Insert 199 at b[9][0] and increment count[9] by 1
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
3 3 3
4 1 4 45
5 0 5 677
6 0 6
7 1 7
8 1 8 88
2 90
199
9 9
Arrange the elements in above bucket from top to bottom
Page
no:
Date: Roll
number:24B11EC164
9 0 9
•Arrange the elements in above bucket from top to bottom
Program:
#include <stdio.h>
// Function to get the maximum value in an array
int getMax(int a[], int n)
{
int max = a[0], i;
for(i = 1; i < n; i++)
{
if(a[i] > max)
max = a[i];
}
return max; // Maximum element from the array
}
// Function to implement radix sort
void radixSort(int a[], int n)
{
int big, nod = 0, steps, count[10];
int i, j, k, bucket[10][n], loc, div = 1;
big = getMax(a, n);
// Count the number of digits in the largest number
while (big > 0)
{
nod++;
big = big / 10;
Page
no:
Date: Roll
number:24B11EC164
}
for (steps = 1; steps <= nod; steps++)
{
// Initialize count array
for (j = 0; j < 10; j++)
{ count[j] = 0; }
// Distribute elements into buckets
for (i = 0; i < n; i++)
{
loc = (a[i] / div) % 10;
bucket[loc][count[loc]++] = a[i];
}
// Collect elements back into the array
k = 0;
for (j = 0; j < 10; j++)
{ // Looping through digits 0-9
for (i = 0; i < count[j]; i++)
{
a[k++] = bucket[j][i];
}
}
// Move to the next digit
div = div * 10;
}
}
// Function to print array elements
void printArray(int a[], int n)
{
Page
no:
Date: Roll
number:24B11EC164
int i;
for (i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main()
{
int a[100],n,i;
printf("\nEnter No.of elements ");
scanf("%d",&n);
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Before sorting, array elements are:\n");
printArray(a, n);
radixSort(a, n);
printf("After applying Radix sort, array elements are:\n"); printArray(a, n);
return 0;
}
OUTPUT:
enter the range:5
Enter the elements:
54132
Array after sorting: 1 2 3 4 5
Page
no:
Date: Roll
number:24B11EC164
PRACTICE 3
Practice 3.1
Aim: Write a C program to implement Single Linked List.
Description:
A Single Linked List is a dynamic data structure used to store a collection of elements where
each element (called a node) points to the next node in the sequence. Unlike arrays, linked
lists are not stored in contiguous memory locations and allow for efficient insertion and
deletion of elements.
Procedure:
1. Define a Node Structure:
o Each node has two parts: data and a pointer to the next node (next).
2. Create the Head Node:
o Initialize the head of the list as NULL (empty list).
3. Insertion Operations:
o At Beginning: Create a new node → point its next to current head → update
head.
o At End: Traverse to last node → set last node’s next to new node.
o At Position: Traverse to desired position → adjust pointers accordingly.
4. Deletion Operations:
o From Beginning: Update head to next node → free the old head.
o From End: Traverse to second last node → set its next to NULL → free last
node.
o From Position: Traverse to previous node → adjust links → free node.
5. Display the List:
o Start from head → print each node’s data while moving to the next.
6. Search Operation:
o Traverse each node → compare data with target → report position if found.
7. Count Nodes:
o Traverse list → increment a counter for each node visited.
Page
no:
Date: Roll
number:24B11EC164
💡 Operations:
o Insert 10
o Insert 20
o Insert 30
o Display list
o Delete last node
o Display list
o
✅ Step-by-Step Example
o Initial State:
head = NULL
🔹 Insert 10
o CreateNode(10) → newNode = [10 | NULL]
o List is empty → head = newNode
✅ List: 10 → NULL
🔹 Insert 20
o CreateNode(20) → newNode = [20 | NULL]
o Traverse to last node (10)
o Link 10.next = newNode
✅ List: 10 → 20 → NULL
🔹 Insert 30
o CreateNode(30) → newNode = [30 | NULL]
o Traverse to last node (20)
o Link 20.next = newNode
✅ List: 10 → 20 → 30 → NULL
🔹 Display List
Output: 10 20 30
🔹 Delete From End
o Traverse to second last node (20)
Page
no:
Date: Roll
number:24B11EC164
Program:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *link;
};
struct node *start=NULL,*temp,*last,*t1,*t2;
void firstinsert() // Function to insert NODE at First
{
int e;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n\tEnter an element to store in Node");
scanf("%d",&e);
temp->data=e;
temp->link=NULL;
if(start==NULL)
{
start=temp;
last=temp;
Page
no:
Date: Roll
number:24B11EC164
}
else
{
temp->link=start;
start=temp;
}
}
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
t2->link=NULL;
last=t2;
Page
no:
Date: Roll
number:24B11EC164
}
}
void middledelete() // Function to Delete particular NODE
{
int pos,i=1;
printf("\nEnter the position to delete the Node");
scanf("%d",&pos);
if(start==NULL)
printf("\n\tNo Element to Delete, Linked List is EMPTY");
else
{
t1=start;
while(i<pos)
{
t2=t1;
t1=t1->link;
i++;
}
t2->link=t1->link;
}
}
void disp()
{
if(start==NULL)
{
printf("\nNo elements in Linked List......................");
}
Page
no:
Date: Roll
number:24B11EC164
else
{
printf("\n\t\tLinked List elements are......................");
temp=start;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
}
}
int main()
{
int ch,k;
while(1)
{
//system("cls");
printf("\n\t\t\t-----Linked List Operations-------");
printf("\n\n\t\t1. First Insert");
printf("\n\n\t\t2. Last Insert");
printf("\n\n\t\t3. Middle Insert");
printf("\n\n\t\t4. First Delete");
printf("\n\n\t\t5. Last Delete");
printf("\n\n\t\t6. Middle Delete");
printf("\n\n\t\t7. display");
printf("\n\n\n\n\t\t8.Exit");
printf("\n\n\tEnter your Choice...");
scanf("%d",&ch);
Page
no:
Date: Roll
number:24B11EC164
switch(ch)
{
case 1: firstinsert(); break;
case 2: lastinsert(); break;
case 3: middleinsert(); break;
case 4: firstdelete(); break;
case 5: lastdelete(); break;
case 6: middledelete(); break;
case 7: disp(); break;
case 8: exit(0);
} /* Switch closed */
} /* while closed */
return 0;
}/* main closed */
OUTPUT:
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
Page
no:
Date: Roll
number:24B11EC164
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 30
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 20
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 10
Page
no:
Date: Roll
number:24B11EC164
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Linked list elements are …… 10 20 30
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...6
Enter the position to delete the node 2
-----Linked List Operations-------
1. First Insert
2. Last Insert
Page
no:
Date: Roll
number:24B11EC164
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Linked list elements are …… 10 30
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Page
no:
Date: Roll
number:24B11EC164
Practice 3.2
Aim: Write a C program to reverse elements of a single linked list.
Description:
Break the linked list into two parts - first node and rest of the linked list.
Call reverse function for rest of the linked list.
Link rest and first.
Change the head pointer.
Program:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
int main()
{
struct node *p = NULL;
int n;
return 0;
}
Page
no:
Date: Roll
number:24B11EC164
{
struct node *p, *q, *r;
p = q = r = *head;
p = p->next->next;
q = q->next;
r->next = NULL;
q->next = r;
while (p != NULL)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
*head = q;
}
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
Page
no:
Date: Roll
number:24B11EC164
printf("\n");
}
OUTPUT:
Enter data into the list
Enter number: 1
Do you wish to continue [1/0]: 1
Enter number: 2
Do you wish to continue [1/0]: 1
Enter number: 3
Do you wish to continue [1/0]: 1
Enter number: 4
Do you wish to continue [1/0]: 1
Enter number: 5
Do you wish to continue [1/0]: 0
Page
no:
Date: Roll
number:24B11EC164
Practice 3.3
Aim: Write a C program to implement Double Linked List.
Description:
A Doubly Linked List (DLL) is a type of linked data structure that consists of a sequence of
elements called nodes, where each node contains three parts:
1. Data – The value to be stored.
2. Pointer to the next node – (next)
3. Pointer to the previous node – (prev)
Unlike a singly linked list (which can only be traversed in one direction), a doubly linked list
allows bidirectional traversal — both forward and backward — because each node has
links to both its next and previous nodes.
Procedure:
1️.Create a Node
Allocate memory for a new node.
Set the data field.
Initialize both prev and next pointers to NULL.
2️.Insert at Beginning
1. Create a new node.
2. Set newNode.next = head.
3. If head is not NULL, set head.prev = newNode.
4. Set head = newNode.
3️.Insert at End
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
2. Adjust links:
o node.prev.next = node.next
o node.next.prev = node.prev
3. Free the node.
8️.Traverse Forward
1. Start from head.
2. While current ≠ NULL:
o Print current.data
o Move to current.next
9️.Traverse Backward
1. Go to the last node by traversing next pointers.
2. While current ≠ NULL:
o Print current.data
o Move to current.prev
Program:
#include<stdio.h>
#include<malloc.h>
struct node // Defining the Node structure.
{
int data;
struct node *rlink,*llink;
};
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
if(start==NULL)
{
start=temp;
last=temp;
}
else
{
last->rlink=temp;
temp->llink=last;
last=temp;
}
}
Page
no:
Date: Roll
number:24B11EC164
start=temp;
last=temp;
}
else
{
printf("\n Insdie of middle insert fun");
t1=start;
while(i<pos)
{
t2=t1;
t1=t1->rlink;
i++;
}
temp->rlink=t1;
t1->llink=temp;
t2->rlink=temp;
temp->llink=t2;
}
}
Page
no:
Date: Roll
number:24B11EC164
t1=start->rlink;
start=start->rlink;
t1->llink=NULL;
cout<<"\n\t First Node is Deleted Successfully";
}
}
Page
no:
Date: Roll
number:24B11EC164
t1=start;
while(i<pos)
{
t2=t1;
t1=t1->rlink;
i++;
}
t2->rlink=t1->rlink;
}
}
void disp()
{
if(start==NULL)
{
printf("\nNo elements in Linked List......................");
}
else
{
printf("\n\t\t Double Linked List elements START to LAST NODE are...................\n\t:");
t1=start;
while(t1!=NULL)
{
cout<<t1->data<<" ";
t1=t1->rlink;
}
printf("\n\n\n\t\t Double Linked List elements LAST to START are..........\n\t:");
t1=last;
Page
no:
Date: Roll
number:24B11EC164
while(t1!=NULL)
{
cout<<t1->data<<" ";
t1=t1->llink;
}
cout<<t1->data;
}
}
int main()
{
int ch;
while(1)
{
//system("cls");
printf("\n\t\t\t-----Doubly Linked List Operations-------");
printf("\n\n\t\t1. First Insert");
printf(\n\n\t\t2. Last Insert");
printf("\n\n\t\t3. Middle Insert)";
printf("\n\n\t\t4. First Delete");
printf("\n\n\t\t5. Last Delete");
printf("\n\n\t\t6. Middle Delete");
printf("\n\n\t\t7. display");
printf("\n\n\n\n\t\t9.Exit");
printf("\n\n\tEnter your Choice...");
scanf("%d",&ch);
switch(ch)
{
Page
no:
Date: Roll
number:24B11EC164
OUTPUT:
----- Double Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 30
----- Double Linked List Operations-------
Page
no:
Date: Roll
number:24B11EC164
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 20
----- Double Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 10
----- Double Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
Page
no:
Date: Roll
number:24B11EC164
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Double Linked list elements START to LAST NODE are …… 10 20 30
----- Double Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...4
First node is deleted successfully
----- Double Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Page
no:
Date: Roll
number:24B11EC164
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Page
no:
Date: Roll
number:24B11EC164
Practice 3.4
Aim: Write a C program to implement Circular Linked List.
Description:
A Circular Linked List (CLL) is a variation of a linked list in which the last node points
back to the first node, forming a circular loop. This makes the list cyclic rather than ending
with a NULL pointer like in singly or doubly linked lists.
Depending on the structure, a circular linked list can be:
Singly Circular – Each node has one pointer (next), and the last node’s next points to
the first node.
Doubly Circular – Each node has two pointers (prev and next), and both ends link
back to each other.
Procedure:
1️.Create a Node
Allocate memory for a new node.
Set the data field.
Set the next pointer to NULL.
2️.Insert at Beginning
1. Create a new node.
2. If the list is empty:
o Set newNode.next = newNode
o Set head = newNode
3. Else:
o Traverse to the last node (node whose next points to head)
o Set newNode.next = head
o Update last node’s next = newNode
o Set head = newNode
3️.Insert at End
1. Create a new node.
2. If the list is empty:
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Program:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *start=NULL,*last=NULL,*temp,*t1,*t2;
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
start=temp;
last=temp;
}
else
{
last->link=temp;
last=temp;
}
}
void middleinsert() // Function to insert NODE at Particular Position
{
int e,pos,i=1;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n\tEnter an element to store in Node");
scanf("%d",&e);
temp->data=e;
temp->link=NULL;
printf("\n Enter the postion to insert");
scanf("%d",&pos);
if(start==NULL)
{
start=temp;
}
else
{
printf("\n Insdie of middle insert fun");
t1=start;
while(i<pos)
Page
no:
Date: Roll
number:24B11EC164
{
t2=t1;
t1=t1->link;
i++;
}
temp->link=t2->link;
t2->link=temp;
}
}
Page
no:
Date: Roll
number:24B11EC164
else
{
t1=start;
while(t1->link!=NULL)
{
t2=t1;
t1=t1->link;
}
t2->link=NULL;
last=t2;
}
}
Page
no:
Date: Roll
number:24B11EC164
}
t2->link=t1->link;
}
}
void disp()
{
if(start==NULL)
{
printf("\nNo elements in Linked List......................");
}
else
{
printf("\n\t\tLinked List elements are......................");
t1=start;
while(t1->link!=start)
{
printf("%d",t1->data);
t1=t1->link;
}
printf(" %d ",t1->data);
}
}
int main()
{
int ch;
while(1)
Page
no:
Date: Roll
number:24B11EC164
{
//system("cls");
printf("\n\t\t\t-----Linked List Operations-------");
printf("\n\n\t\t1. First Insert");
printf("\n\n\t\t2. Last Insert");
printf("\n\n\t\t3. Middle Insert");
printf("\n\n\t\t4. First Delete");
printf("\n\n\t\t5. Last Delete");
printf("\n\n\t\t6. Middle Delete");
printf("\n\n\t\t7. display");
printf("\n\n\n\n\t\t8.Exit");
printf("\n\n\tEnter your Choice...");
scanf("%d",&ch);
switch(ch)
{
case 1: firstinsert(); break;
case 2: lastinsert(); break;
case 3: middleinsert(); break;
case 4: firstdelete(); break ;
case 5: lastdelete(); break;
case 6: middledelete(); break;
case 7: disp(); break;
case 8: exit(0);
} /* Swith closed */
} /* while closed */
return 0;
}/* main closed */
Page
no:
Date: Roll
number:24B11EC164
OUTPUT
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 10
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...1
Enter an element to store in node 20
-----Linked List Operations-------
1. First Insert
Page
no:
Date: Roll
number:24B11EC164
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Linked list elements are …… 10 20
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...4
First node ki deleted successfully
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
Page
no:
Date: Roll
number:24B11EC164
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Linked list elements are …… 20
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Page
no:
Date: Roll
number:24B11EC164
PRACTICE 4
Practice 4.1.1
Aim: Write a C program to implement Stack operations using array.
Description:
A stack is a linear data structure that follows the LIFO principle:
LIFO = Last In, First Out
This means:
The last element that is added (pushed) to the stack will be the first one to be
removed (popped).
Stack Operations
1. Push – Add an element to the top of the stack.
2. Pop – Remove the top element from the stack.
3. Peek/Top – View the top element without removing it.
4. IsEmpty – Check if the stack is empty.
5. IsFull – Check if the stack is full.
Procedure:
Step 1: Define Stack
Create an array to hold the stack elements.
Initialize a variable top = -1.
🔹 Step 2: Push 10
🔹 Step 3: Push 20
Again check if stack is full
If not full:
Increment top
Page
no:
Date: Roll
number:24B11EC164
Program:
#include <stdio.h>
int stack[100], n, top = -1, ch;
void push();
void pop();
void display();
void main() {
printf("Enter size of stack: ");
scanf("%d", &n);
printf("Stack operations: 1. Push 2. Pop 3. Display 4. Exit\n");
do {
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch) {
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Element inserted
Enter your choice :3
Stack elements are 30 20 10
Enter your choice :2
Deleted element is : 30
Enter your choice : 3
Stack elements are : 20 10
Enter your choice : 4
Exiting stack operations
Practice 4.1.2
Aim: Write a C program to implement Stack operations as linked list.
Description:
A stack is a LIFO (Last In, First Out) data structure where:
You push (insert) elements at the top.
You pop (remove) elements from the top.
Procedure:
🔹 Step 1: Define the Node Structure
Each node stores an integer value and a pointer to the next node.
🔹 Step 2: Initialize the Stack
top will always point to the top of the stack.
If top == NULL, the stack is empty.
🔹 Step 3: Push 10
Procedure:
1. Create a new node.
2. Assign data 10 to it.
3. Point newNode->next to top (currently NULL).
4. Set top = newNode.
Page
no:
Date: Roll
number:24B11EC164
🔹 Step 4: Push 20
Procedure:
1. Create a new node.
2. Assign data 20 to it.
3. Point newNode->next to top (currently node with 10).
4. Set top = newNode.
🔹 Step 5: Peek (Top Element)
Display the element at top.
🔹 Step 6: Pop (Remove Top Element)
Procedure:
1. Check if stack is empty.
2. Store top node in temp.
3. Set top = top->next (now points to 10).
4. Free temp.
🔹 Step 7: Display Stack
Procedure:
Start from top.
Traverse and print each data.
🔚 Final Stack Status:
After pushing: 20 → 10
After popping once: 10
Program:
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *link;
Page
no:
Date: Roll
number:24B11EC164
};
struct stack *top=NULL,*p,*temp,*temp1;
void push() {
int ele;
printf("\nEnter element: ");
scanf("%d", &ele);
p = (struct stack *)malloc(sizeof(struct stack));
p->data = ele;
p->link = top;
top = p;
}
void pop() {
if (top == NULL) {
printf("\nThere are no elements to pop");
} else {
struct stack *temp = top;
printf("\nDeleted element is %d", top->data);
top = top->link;
free(temp);
}
}
void display() {
struct stack *temp = top;
if (temp == NULL) {
printf("\nThere are no elements in the stack");
} else {
printf("\nStack elements are: ");
while (temp != NULL) {
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
}
return 0;
}
Output:
Stack operations are:
1.push
2.pop
3.display
4.exit
Enter your choice ….1
Enter the element :10
Stack operations are:
1.push
2.pop
3.display
4.exit
Enter your choice ….1
Enter the element :20
Stack operations are:
1.push
2.pop
3.display
4.exit
Enter your choice ….3
Stack elements are : 20 10
Stack operations are:
1.push
2.pop
Page
no:
Date: Roll
number:24B11EC164
3.display
4.exit
Enter your choice ….2
Deleted element : 20
Stack operations are:
1.push
2.pop
3.display
4.exit
Enter your choice ….3
Stack elements are : 10
Stack operations are:
1.push
2.pop
3.display
4.exit
Enter your choice ….4
Practice 4.2
Aim: Write a C program to implement post fix evalution
Description:
A postfix expression is a mathematical expression where the operator comes after the
operands.
Example:
Infix: 2 + 3
Postfix: 2 3 +
Procedure:
✅ Step 1: Initialize a Stack
Page
no:
Date: Roll
number:24B11EC164
💡 Example: Evaluate 5 3 + 2 *
🔹 Expression:
Postfix = 5 3 + 2 *
🔹 Process:
Step Action Stack
1 Push 5 [5]
2 Push 3
[5, 3]
3 +→5+3=8
[8]
4 Push 2
[8, 2]
s5 * → 8 * 2 = 16
[16]
Page
no:
Date: Roll
number:24B11EC164
✅ Final Result = 16
Program:
#include<stdio.h>
#include<ctype.h>
int stack[20];
int top;
top = -1;
void push(int x)
{
stack[++top]=x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("enter the expression:");
scanf("%s",exp);
e=exp;
while(*e!='\0')
{
if(is_digit(*e))
{
num=*e-0;
Page
no:
Date: Roll
number:24B11EC164
push(num);
}
Else
{
n1=pop();
n2=pop();
switch(*e)
{
case '+' :
n3=n1+n2;
break;
case '-' :
n3=n2-n1;
break;
case '*' :
n3=n1*n2;
break;
case '/' :
n3=n2/n1;
break;
}
push(n3);
}
e++;
}
printf("\n the result for the expression %s = %d\n\n",exp,pop());
return 0;
}
Page
no:
Date: Roll
number:24B11EC164
OUTPUT:
Enter the expression : 453++
The result of the expression 453++ = 19
Page
no:
Date: Roll
number:24B11EC164
Practice 4.3.1
Aim: Write a C program to implement Queue by using Array.
Description:
A queue using an array is a way to store data in a First In, First Out (FIFO) order. This
means the first element added is the first one to be removed.
In this method, we use an array and two variables:
front to track the first element,
rear to track the last element.
👉 Basic operations:
Enqueue: Add an element at the end (rear).
Dequeue: Remove an element from the front (front).
It's like people standing in a line—first person in line gets served first.
Procedure: ✅ Procedure to Implement Queue Using Array
1. Initialize the queue
o Create an array of a fixed size.
o Set front = -1 and rear = -1.
2. Enqueue (Insert) Operation
o Check if the queue is full (rear == size - 1):
If yes, print "Queue is full".
o If queue is empty (front == -1), set front = 0.
o Increase rear by 1.
o Add the new element at queue[rear].
3. Dequeue (Remove) Operation
o Check if the queue is empty (front == -1 or front > rear):
If yes, print "Queue is empty".
o Get the element at queue[front].
o Increase front by 1.
4. Display Operation (Optional)
Page
no:
Date: Roll
number:24B11EC164
Program:
#include<stdio.h>
#include<stdlib.h>
int Queue[100],n,i,front=-1,rear=-1,x,ch;
void insert();
void delete();
void display();
void main()
{
Page
no:
Date: Roll
number:24B11EC164
}
}
void insert()
{
if(rear==n-1)
{
printf("Queue is full\n");
}
else
{
rear++;
printf("Enter queue elements ");
scanf("%d",&x);
Queue[rear]=x;
printf("element inserted");
}
}
void delete()
{
if(front==rear)
printf("queue is empty");
else
{
front++;
printf("delete data element is = %d",Queue[front]);
}
}
Page
no:
Date: Roll
number:24B11EC164
void display()
{
if(front==rear)
printf("Queue is empty");
else{
printf("Queue elements are :\n");
for(i=front + 1;i<=rear;i++)
{
printf("%d",Queue[i]);
}
}
}
Output:
Enter queue size: 3
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 1
Enter queue element: 10
Element inserted
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 1
Enter queue element: 20
Element inserted
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 3
Queue elements are:
10 20
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 2
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Practice 4.3.2
Aim:Write a C program to implement Queue using Linked list.
Description:
A queue using a linked list is a data structure that stores elements in a First In, First Out
(FIFO) order, just like a regular queue. But instead of using an array, it uses nodes
connected by pointers.
Each node has:
Data: the value of the element.
Next: a pointer to the next node in the queue.
✅ Main Features:
No fixed size: Unlike arrays, it can grow or shrink as needed.
Two pointers are used:
o front: points to the first element (to be removed).
o rear: points to the last element (where new elements are added).
🔧 Operations:
Enqueue: Create a new node and add it at the end (rear).
Dequeue: Remove the node at the front and update the front pointer.
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
}
else
{
printf("deleted node is %d",front->data);
front=front->next;
free(temp);
}
}
void display()
{
struct node *temp;
temp=front;
if((front==NULL)&&(rear==NULL))
{
printf("queue is empty");
}
else
{
temp=front;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
}
void main()
{
Page
no:
Date: Roll
number:24B11EC164
int ch;
while (1)
{
printf("\nqueue operations are ");
printf("\n 1.insert");
printf("\n 2.delete");
printf("\n 3.display");
printf("\n 4.exit");
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3: display();
break;
case 4: exit(0);
break;
default: printf("\n invalid choice,try again");
}
}
}
Output:
QUEUE OPERATIONS ARE:
1. insert
2. delete
Page
no:
Date: Roll
number:24B11EC164
3. display
4. exit
enter your choice :1
enter an element10
QUEUE OPERATIONS ARE:
1. insert
2. delete
3. display
4. exit
enter your choice :1
enter an element20
QUEUE OPERATIONS ARE:
1. insert
2. delete
3. display
4. exit
enter your choice :3
1020
QUEUE OPERATIONS ARE:
1. insert
2. delete
3. display
4. exit
enter your choice :2
deleted node is 10
QUEUE OPERATIONS ARE:
1. insert
Page
no:
Date: Roll
number:24B11EC164
2. delete
3. display
4. exit
enter your choice :4
Page
no:
Date: Roll
number:24B11EC164
Practice 4.4
Aim: Write a C program to implement circular queue.
Description:
A circular queue is a special type of queue where the last position is connected back to the
first position to make a circle. It also follows the FIFO (First In, First Out) principle.
In a circular queue using an array, the rear wraps around to the beginning of the array
when it reaches the end, if there is free space at the front. This helps in efficiently utilizing
memory, unlike a normal linear queue.
🔧 Key Concepts:
We use an array to store elements.
Two pointers:
o front → points to the first element.
o rear → points to the last element.
Circular movement is handled using:
rear = (rear + 1) % size
front = (front + 1) % size
✅ Operations:
1. Enqueue: Insert an element at rear position.
2. Dequeue: Remove an element from front position.
3. Display: Print all elements from front to rear.
Procedure:
Initialize the Queue
Create an array of fixed size.
Set front = -1, rear = -1.
Enqueue (Insert) Operation
Check if the queue is full:
(rear + 1) % size == front
o If yes, print "Queue is full".
If the queue is empty (front == -1):
Page
no:
Date: Roll
number:24B11EC164
o Set front = 0.
Move rear forward in a circular way:
rear = (rear + 1) % size
Insert the new element at queue[rear].
Dequeue (Remove) Operation
Check if the queue is empty:
front == -1
o If yes, print "Queue is empty".
Store the element at queue[front].
If front == rear: (only one element)
o Set front = -1 and rear = -1 (queue becomes empty).
Else:
o Move front forward in a circular way:
front = (front + 1) % size
Display Operation (Optional)
If queue is empty (front == -1), print "Queue is empty".
Else:
o Start from front, print elements until rear, using circular logic:
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 5
int queue[MAX_SIZE];
int front=-1; rear=-1;
int isfull()
{
return (rear+1)%MAX_SIZE==front;
}
int isempty()
Page
no:
Date: Roll
number:24B11EC164
{
return front==-1;
}
void enqueue()
{
int data;
printf("\n enter element:");
scanf("%d",&data);
if(isfull())
{
printf("queue overflow");
return;
}
if(front==-1)
{
front=0;
}
rear=(rear+1)%MAX_SIZE;
queue[rear]=data;
printf("element %d inserted\n",data);
}
void dequeue()
{
if(isempty())
{
printf("queue underflow");
return;
}
Page
no:
Date: Roll
number:24B11EC164
int data=queue[front];
if(front==rear)
{
front=rear=-1;
}
else
{
front=(front+1)%MAX_SIZE;
}
printf("deleted elements %d",data);
}
void display()
{
if(isempty())
{
printf("queue is empty");
return;
}
printf("queue elements");
int i=front;
while(i!=rear)
{
printf("%d",queue[i]);
i=(i+1)%MAX_SIZE;
}
printf("%d\n",queue[rear]);
}
void main()
Page
no:
Date: Roll
number:24B11EC164
{
int ch;
while(1)
{
printf("\n\t queue operations are ");
printf("\n\t 1.insert");
printf("\n\t 2.delete");
printf("\n\t 3.display");
printf("\n\t 4.exit");
printf("\n\t enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4: exit(0); break;
default: printf("invalid choice,try again");
}
}
}
Output:
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice1
enter element50
element 50 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice3
Queue elements10 20 30 40 50
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice2
deleted element10
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice2
deleted element20
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
PRACTICE 5
Practice 5.1
Aim: Implement Binary search tree (BST).
Description:
For a binary tree to be a binary search tree, the data of all the nodes in the left sub-tree of the
root node should be ≤ the data of the root. The data of all the nodes in the right subtree of the
root node should be > the data of the root.
program:
#includ e<stdio.h>
#include<stdlib.h>
Page
no:
Date: Roll
number:24B11EC164
{
int data;
struct BST *left;
struct BST *right;
}node;
node *create();
void insert(node *,node *);
void preorder(node *);
int main()
{
char ch;
node *root=NULL,*temp;
do
{
temp=create();
if(root==NULL)
root=temp;
else
insert(root,temp);
printf("Do you want to enter more(y/n)?");
getchar();
scanf("%c",&ch);
}while(ch=='y'|ch=='Y');
printf("nPreorder Traversal: ");
preorder(root);
return 0;
}
node *create()
{
node *temp;
printf("Enter data:");
temp=(node*)malloc(sizeof(node));
scanf("%d",&temp->data);
temp->left=temp->right=NULL;
return temp;
}
Page
no:
Date: Roll
number:24B11EC164
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}
OUTPUT:
Enter data:5
Do you want to enter more(y/n)?y
Enter data:10
Do you want to enter more(y/n)?y
Enter data:13
Do you want to enter more(y/n)?y
Enter data:2
Do you want to enter more(y/n)?y
Enter data:3
Do you want to enter more(y/n)?n
Preorder Traversal: 5 2 3 10 13
Page
no:
Date: Roll
number:24B11EC164
Practice 5.2
Aim: Implement Binary search Tree (BST) Traversals.
Description:
The C program you provided implements a fundamental data structure called a Binary Search
Tree (BST) and demonstrates its core operation of traversal. Here's a breakdown of what the
code does:
Core Concepts:
Binary Search Tree (BST):
o A tree-like way to store data (in this case, numbers) where each "branching
point" (node) has at most two "sub-branches" (children) – a left one and a right
one.
Page
no:
Date: Roll
number:24B11EC164
o The key rule is: numbers smaller than the current number go to the left, and
numbers larger go to the right. This makes it easy to find things later.
Nodes: Each piece of data in the tree is held in a node. A node contains the number itself
(data) and pointers (left, right) to its left and right "sub-branches".
Insertion: The insert function adds new numbers to the tree. It figures out the correct spot to
put the new number based on the BST rule (smaller to the left, bigger to the right).
Traversals: These are ways to visit and list all the numbers in the tree in a specific order:
o Inorder: Visits the left side, then the current number, then the right side. For a
BST, this lists the numbers in sorted order.
o Preorder: Visits the current number first, then the left side, then the right side.
o Postorder: Visits the left side, then the right side, and finally the current
number.
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the Binary Search Tree
struct Node {
int data;
struct Node *left;
struct Node *right;
};
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
int main() {
struct Node* root = NULL;
Page
no:
Date: Roll
number:24B11EC164
printf("\n");
return 0;
}
OUTPUT:
Inorder traversal: 20 30 40 50 60 70 80
Preorder traversal: 50 30 20 40 70 60 80
Post order traversal: 20 40 30 60 80 70 50
Page
no:
Date: Roll
number:24B11EC164
Practice 5.3
Aim: Implement Graph Traversal using Breadth First Search (BFS)
Description:
Breadth First Search (BFS) is a fundamental algorithm used to explore or traverse a
graph data structure. It systematically visits all the vertices (nodes) of a graph, starting from a
designated source vertex, by exploring the neighbor vertices at the present depth prior to
moving on to the vertices at the next depth level.
1. Exploration Strategy (Level by Level):
o BFS explores the graph layer by layer. It begins at the starting vertex.
o First, it visits all the immediate neighbors (vertices directly connected by an
edge) of the starting vertex.
o Then, for each of those neighbors, it visits their unvisited neighbors.
o This process continues, expanding outwards like ripples on a pond, ensuring
that all vertices at a shorter distance (in terms of the number of edges) from
the source are visited before those at a greater distance.
2. Queue Data Structure:
o BFS utilizes a queue to manage the order in which vertices are visited.
o The starting vertex is enqueued.
o While the queue is not empty:
A vertex is dequeued from the front of the queue.
This dequeued vertex is marked as visited.
All its unvisited neighbors are then enqueued.
o The FIFO (First-In, First-Out) nature of the queue ensures the level-by-level
exploration.
3. Visited Tracking:
o To prevent cycles (visiting the same vertex multiple times) and to ensure that
the algorithm terminates, BFS maintains a record of visited vertices.
o Typically, a boolean array or a set is used to mark vertices as visited once they
have been processed.
Algorithm Steps (Conceptual):
1. Choose a starting vertex.
2. Create a queue and enqueue the starting vertex.
3. Mark the starting vertex as visited.
4. While the queue is not empty: a. Dequeue a vertex from the front of the queue. b.
Process the dequeued vertex (e.g., print it, perform some operation). c. For each
unvisited neighbor of the dequeued vertex: i. Mark the neighbor as visited. ii.
Enqueue the neighbor.
Page
no:
Date: Roll
number:24B11EC164
Program:
#include <stdio.h>
#include <stdlib.h>
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
int main() {
int numNodes = 6; // Example graph with 6 nodes (0 to 5)
return 0;
}
OUTPUT:
Breadth First Search starting from vertex 0: 0 1 2 3 4 5
Page
no:
Date: Roll
number:24B11EC164
Practice 5.4
Aim: Implement Graph Traversal using Depth First Search (DFS)
Description:
Depth First Search (DFS) is a graph traversal algorithm that explores as far as
possible along each branch before backtracking. It starts at a chosen source vertex and
explores a path as deeply as possible until a vertex with no unvisited adjacent vertices is
reached. At this point, the algorithm backtracks to the most recently visited vertex that still
has unvisited neighbors and continues the exploration down a different branch. This process
repeats until all reachable vertices from the source have been visited.
Key Concepts of DFS:
1. Depth-First Exploration: DFS prioritizes going deep into the graph. It follows one
path until it can no longer proceed further before exploring alternative paths.
2. Stack (or Recursion): DFS is typically implemented using either:
o A stack data structure (iterative approach): Keeps track of the vertices to
visit. The algorithm pushes unvisited neighbors onto the stack and pops the
last visited vertex to backtrack.
o Recursion (recursive approach): The function calls itself on unvisited
neighbors, implicitly using the call stack for backtracking.
Page
no:
Date: Roll
number:24B11EC164
Program:
#include <stdio.h>
#include <stdlib.h>
Page
no:
Date: Roll
number:24B11EC164
// Array to keep track of visited nodes (0 for not visited, 1 for visited)
int visited[MAX_NODES];
Page
no:
Date: Roll
number:24B11EC164
// Push the starting vertex onto the stack and mark it as visited
push(startVertex);
visited[startVertex] = 1;
Page
no:
Date: Roll
number:24B11EC164
Page
no:
Date: Roll
number:24B11EC164
addEdge(2, 6);
int startVertex = 0;
DFS(startVertex, numNodes);
return 0;
}
OUTPUT:
Depth First Search starting from vertex 0: 0 2 6 5 1 4 3
Page
no: