sandeep 2
sandeep 2
number:24B11EC085
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:
Page
no:
Date: Roll
number:24B11EC085
#include <stdio.h>
struct Student
{
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:24B11EC085
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:24B11EC085
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:
Page
no:
Date: Roll
number:24B11EC085
Name: Aditya
Rno=143
Gender=m
Page
no:
Date: Roll
number:24B11EC085
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;
Page
no:
Date: Roll
number:24B11EC085
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;
}
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:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
2.Last element
3.Random element
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
Page
no:
Date: Roll
number:24B11EC085
Pivot index = 3
Step 2: Quick Sort Left Subarray [9, 2, 1] [9, 2, 1]
↑
Pivot
•Elements less than 9: [2, 1]
•No elements greater than 9
[1, 2, 9]
↑
Pivot placed
Pivot index = 2
Sorting [1, 2]
[1, 2]
↑
Pivot
•[1] is already sorted
•[2] is already sorted
Step 3: Quick Sort Right Subarray [15, 16, 11] [15, 16, 11]
↑
Pivot
•Elements less than 15: [11]
•Elements greater than 15: [16]
[11, 15, 16]
↑
Pivot placed
Pivot index = 5
Final Sorted Array
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
Practice 2.2
Aim: To perform sort of a given list of elements using merge sort.
Description:
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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
int i = low, j = mid + 1, k = 0;
// Merge elements in sorted order
while (i <= mid && j <= high)
{
if (arr[i] < arr[j])
{
b[k] = arr[i];
i++;
}
else
{
b[k] = arr[j];
j++;
}
k++;
}
// Copy remaining elements from left subarray while (i <= mid)
{
b[k] = arr[i];
Page
no:
Date: Roll
number:24B11EC085
i++; k++;
}
// Copy remaining elements from right subarray
while (j <= high)
{
b[k] = arr[j];
j++; k++;
}
// Copy merged elements back to original array
for (i = low, k = 0; i <= high; i++, k++)
arr[i] = b[k];
}
// Function to perform merge sort
void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int mid = (left + right) / 2; // Find the middle point // Recursively sort
first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
Page
no:
Date: Roll
number:24B11EC085
}
// 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");
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:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
1 8
0
1 1 1 11
2 0 2 530
231
432
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:24B11EC085
1 1 1 199
1 231
2 2
3 0 3 432
4 1 4
5 1 5 530
6 1 6 677
7 0 7
0
8 8
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)
{
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
a[k++] = bucket[j][i];
}
}
// Move to the next digit
div = div * 10;
}
}
// Function to print array elements
void printArray(int a[], int n)
{
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]);
}
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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.
Page
no:
Date: Roll
number:24B11EC085
7. Count Nodes:
o Traverse list → increment a counter for each node visited.
💡 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)
Page
no:
Date: Roll
number:24B11EC085
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");
Page
no:
Date: Roll
number:24B11EC085
scanf("%d",&e);
temp->data=e;
temp->link=NULL;
if(start==NULL)
{
start=temp;
last=temp;
}
else
{
temp->link=start;
start=temp;
}
}
Page
no:
Date: Roll
number:24B11EC085
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");
Page
no:
Date: Roll
number:24B11EC085
t1=start;
while(i<pos)
{
t2=t1;
t1=t1->link;
i++;
}
temp->link=t2->link;
t2->link=temp;
}
}
void firstdelete() // Function to Delete First NODE
{
if(start==NULL)
{
printf("\n\t Linked List is Empty, No Nodes to perform Delete Operation");
}
else
{
start=start->link;
printf("\n\t First Node is Deleted Successfully");
}
}
Page
no:
Date: Roll
number:24B11EC085
if(start==NULL)
printf("\n\t No Nodes in Linked List to delete");
else
{
t1=start;
while(t1->link!=NULL)
{
t2=t1;
t1=t1->link;
}
t2->link=NULL;
last=t2;
}
}
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)
Page
no:
Date: Roll
number:24B11EC085
{
t2=t1;
t1=t1->link;
i++;
}
t2->link=t1->link;
}
}
void disp()
{
if(start==NULL)
{
printf("\nNo elements in Linked List......................");
}
else
{
printf("\n\t\tLinked List elements are......................");
temp=start;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
}
}
Page
no:
Date: Roll
number:24B11EC085
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);
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;
Page
no:
Date: Roll
number:24B11EC085
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 30
-----Linked List Operations-------
1. First Insert
Page
no:
Date: Roll
number:24B11EC085
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
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
Page
no:
Date: Roll
number:24B11EC085
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
3. Middle Insert
4. First Delete
5. Last Delete
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
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
Page
no:
Date: Roll
number:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
Program:
#include<stdio.h>
#include<malloc.h>
struct node // Defining the Node structure.
{
int data;
struct node *rlink,*llink;
};
Page
no:
Date: Roll
number:24B11EC085
temp->rlink=start;
start=temp;
last->llink=temp;
}
}
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
t2=t1;
t1=t1->rlink;
i++;
}
temp->rlink=t1;
t1->llink=temp;
t2->rlink=temp;
temp->llink=t2;
}
}
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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;
while(t1!=NULL)
{
cout<<t1->data<<" ";
Page
no:
Date: Roll
number:24B11EC085
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)
{
case 1: firstinsert(); break;
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
2. Last Insert
3. Middle Insert
4. First Delete
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
Page
no:
Date: Roll
number:24B11EC085
4. First Delete
5. Last Delete
6. Middle Delete
7. display
8.Exit
Enter your Choice...7
Double Linked list elements START to LAST NODE are …… 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
Page
no:
Date: Roll
number:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
Program:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
{
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;
}
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;
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
}
else
{
start=start->link;
last->link=start;
printf("\n\t First Node is Deleted Successfully");
}
}
Page
no:
Date: Roll
number:24B11EC085
void disp()
{
if(start==NULL)
{
printf("\nNo elements in Linked List......................");
}
Page
no:
Date: Roll
number:24B11EC085
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)
{
//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");
Page
no:
Date: Roll
number:24B11EC085
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 */
OUTPUT
-----Linked List Operations-------
1. First Insert
2. Last Insert
3. Middle Insert
4. First Delete
Page
no:
Date: Roll
number:24B11EC085
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
2. Last Insert
3. Middle Insert
4. First Delete
5. Last Delete
6. Middle Delete
Page
no:
Date: Roll
number:24B11EC085
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
6. Middle Delete
7. display
8.Exit
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
If not full:
Increment top
Assign value 20 to stack[top]
🔹 Step 4: Push 30
Check if stack is full
If not full:
o Increment top
o Assign value 30 to stack[top]
🔹 Step 5: Peek (Display Top Element)
If top != -1, print stack[top]
🔹 Step 6: Pop (Remove Top Element)
Check if stack is empty (top == -1)
If not empty:
o Decrease top by 1
🔹 Step 7: Display Stack Elements (Top to Bottom)
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");
Page
no:
Date: Roll
number:24B11EC085
do {
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: printf("Exiting stack operations.\n"); break;
default: printf("Invalid choice.\n");
}
} while (ch != 4);
}
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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:
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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;
};
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) {
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
printf("\n\t 2. pop");
printf("\n\t 3. display");
printf("\n\t 4. exit");
printf("\n\tenter your choice....");
scanf("%d",&ch);
switch(ch)
{
case 1 : push();
break;
case 2 : pop();
break;
case 3 : display();
break;
case 4 : exit(0);
break;
default : printf("\n invalid choice,try again");
}
}
return 0;
}
Output:
Stack operations are:
1.push
2.pop
3.display
4.exit
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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
Create an empty stack to hold operands (numbers).
Page
no:
Date: Roll
number:24B11EC085
💡 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]
✅ Final Result = 16
Program:
Page
no:
Date: Roll
number:24B11EC085
#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:24B11EC085
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());
Page
no:
Date: Roll
number:24B11EC085
return 0;
}
OUTPUT:
Enter the expression : 453++
The result of the expression 453++ = 19
Page
no:
Date: Roll
number:24B11EC085
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].
Page
no:
Date: Roll
number:24B11EC085
o Increase front by 1.
4. Display Operation (Optional)
o Print elements from front to rear.
5. Reset Queue (Optional)
o If all elements are removed (front > rear), reset front = rear = -1.
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:24B11EC085
rear++;
printf("Enter queue elements ");
scanf("%d",&x);
Queue[rear]=x;
printf("element inserted");
}
}
void delete()
{
if(front==rear)
printf("queue is empty");
Page
no:
Date: Roll
number:24B11EC085
else
{
front++;
printf("delete data element is = %d",Queue[front]);
}
}
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
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
{
int data;
struct node *next;
};
struct node *front= NULL;
struct node *rear = NULL;
void enqueue()
{
struct node* new_n;
int d;
new_n = (struct node*)malloc(sizeof(struct node));
printf("enter an element :");
scanf("%d",&d);
new_n->data =d;
new_n->next =NULL;
if((front == NULL)&&(rear == NULL))
{
front =rear =new_n;
}
else
{
rear->next=new_n;
rear=new_n;
}
}
void dequeue()
Page
no:
Date: Roll
number:24B11EC085
{
struct node* temp;
temp=front;
if((front==NULL)&&(rear==NULL))
{
printf("queue is empty");
}
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)
Page
no:
Date: Roll
number:24B11EC085
{
printf("%d",temp->data);
temp=temp->next;
}
}
}
void main()
{
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;
Page
no:
Date: Roll
number:24B11EC085
case 4: exit(0);
break;
default: printf("\n invalid choice,try again");
}
}
}
Output:
QUEUE OPERATIONS ARE:
1. insert
2. delete
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
Page
no:
Date: Roll
number:24B11EC085
deleted node is 10
QUEUE OPERATIONS ARE:
1. insert
2. delete
3. display
4. exit
enter your choice :4
Page
no:
Date: Roll
number:24B11EC085
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
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
{
return (rear+1)%MAX_SIZE==front;
}
int isempty()
{
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()
Page
no:
Date: Roll
number:24B11EC085
{
if(isempty())
{
printf("queue underflow");
return;
}
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;
Page
no:
Date: Roll
number:24B11EC085
while(i!=rear)
{
printf("%d",queue[i]);
i=(i+1)%MAX_SIZE;
}
printf("%d\n",queue[rear]);
}
void main()
{
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");
Page
no:
Date: Roll
number:24B11EC085
}
}
}
Output:
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice1
enter element10
element 10 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice1
enter element20
element 20 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
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>
node *create();
void insert(node *,node *);
void preorder(node *);
int main()
{
char ch;
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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:24B11EC085
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.
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".
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
int main() {
struct Node* root = NULL;
Page
no:
Date: Roll
number:24B11EC085
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:24B11EC085
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.
Page
no:
Date: Roll
number:24B11EC085
Program:
#include <stdio.h>
#include <stdlib.h>
Page
no:
Date: Roll
number:24B11EC085
Page
no:
Date: Roll
number:24B11EC085
int main() {
int numNodes = 6; // Example graph with 6 nodes (0 to 5)
Page
no:
Date: Roll
number:24B11EC085
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(3, 5);
addEdge(4, 5);
return 0;
}
OUTPUT:
Breadth First Search starting from vertex 0: 0 1 2 3 4 5
Practice 5.4
Aim: Implement Graph Traversal using Depth First Search (DFS)
Page
no:
Date: Roll
number:24B11EC085
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.
3. Visited Tracking: Similar to BFS, DFS maintains a record of visited vertices to
prevent cycles and redundant processing. A boolean array or set is commonly used to
mark visited nodes.
Algorithm Steps (Conceptual - Recursive Approach):
1. Choose a starting vertex.
2. Mark the starting vertex as visited.
3. For each unvisited neighbor of the current vertex: a. Recursively call the DFS
function on that neighbor.
Algorithm Steps (Conceptual - Iterative Approach using a Stack):
1. Choose a starting vertex and push it onto a stack.
2. Create a set or array to keep track of visited vertices. Mark the starting vertex as
visited.
3. While the stack is not empty: a. Pop a vertex from the top of the stack. b. Process the
popped vertex (e.g., print it). c. For each unvisited neighbor of the popped vertex: i.
Mark the neighbor as visited. ii. Push the neighbor onto the stack.
Page
no:
Date: Roll
number:24B11EC085
Program:
#include <stdio.h>
#include <stdlib.h>
// Array to keep track of visited nodes (0 for not visited, 1 for visited)
int visited[MAX_NODES];
Page
no:
Date: Roll
number:24B11EC085
if (top == MAX_NODES - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = v;
}
Page
no:
Date: Roll
number:24B11EC085
newNode->next = adj[v];
adj[v] = newNode;
}
// Push the starting vertex onto the stack and mark it as visited
push(startVertex);
visited[startVertex] = 1;
Page
no:
Date: Roll
number:24B11EC085
visited[adjVertex] = 1;
push(adjVertex);
}
neighbor = neighbor->next;
}
}
printf("\n");
}
int main() {
int numNodes = 7; // Example graph with 7 nodes (0 to 6)
// Initialize adjacency lists
for (int i = 0; i < numNodes; i++) {
adj[i] = NULL;
}
Page
no:
Date: Roll
number:24B11EC085
OUTPUT:
Depth First Search starting from vertex 0: 0 2 6 5 1 4 3
Page
no: