0% found this document useful (0 votes)
5 views

sandeep 2

The document outlines various C programming practices, including calculating total and average marks for students using structures, copying structure variables, reading student details from command line arguments, and implementing sorting algorithms like Quick Sort, Merge Sort, and Radix Sort. Each practice includes an aim, description, program code, and sample output. The document serves as a practical guide for learning and applying C programming concepts related to structures and sorting algorithms.

Uploaded by

pnavaneethn07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

sandeep 2

The document outlines various C programming practices, including calculating total and average marks for students using structures, copying structure variables, reading student details from command line arguments, and implementing sorting algorithms like Quick Sort, Merge Sort, and Radix Sort. Each practice includes an aim, description, program code, and sample output. The document serves as a practical guide for learning and applying C programming concepts related to structures and sorting algorithms.

Uploaded by

pnavaneethn07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

Date: Roll

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

[1, 2, 9, 10, 11, 15, 16]


This completes the Quick Sort process! 🚀
Program:
#include <stdio.h>
void quicksort(int array[], int first, int last){
int i, j, pivot, temp;
if (first < last)
{ pivot = first; // Choosing first element as pivot
i = first;
j = last;
while (i < j) {
while (array[i] <= array[pivot] && i < last)
i++;
while (array[j] > array[pivot])
j--;
if (i < j) { // Swap elements at i and j
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Swap pivot with array[j] to place it in the correct position
temp = array[pivot];
array[pivot] = array[j];
array[j] = temp;
// Recursively sort the sub-arrays

Page
no:
Date: Roll
number:24B11EC085

quicksort(array, first, j - 1);


quicksort(array, j + 1, last);
}
}
int main() { // Changed void main() to int main()
int i, n, array[25];
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", &array[i]);
quicksort(array, 0, n - 1);
printf("The sorted elements are:\n");
for (i = 0; i < n; i++)
printf("%d ", array[i]);
return 0; // Return 0 to indicate successful execution }

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:

•Finally, the array is completely sorted. •Result of sorted array is 0 , 2 , 4 ,6.

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

•Insert 677 at b[7][0] and increment count[7] by 1


•Insert 199 at b[9][0] and increment count[9] by 1

Arrange the elements in above bucket from top to bottom

Iteration 2: Consider tens position


•Insert 530 at b[3][0] and increments count[3] by 1
•Insert 90 at b[9][0] and increment count[9] by 1
•Insert 231 at b[3][1] and increment count[3] by 1
•Insert 11 at b[1][0] and increment count[1] by 1
•Insert 432 at b[3][2] and increment count[3] by 1
•Insert 45 at b[4][0] and increment count[4] by 1
•Insert 677 at b[7][0] and increment count[7] by 1
•Insert 8 at b[0][0] and increment count[0] by 1
•Insert 88 at b[8][0] and increment count[8] by 1
•Insert 199 at b[9][1] and increment count[9] by 1
0 Count b 0 1 2 3 4 5 6 7 8 9

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

Iteration 3: Consider hundreds position


•Insert 8 at b[0][0] and increments count[0] by 1
•Insert 11 at b[0][1] and increment count[0] by 1
•Insert 530 at b[5][0] and increment count[5] by 1
•Insert 231 at b[2][0] and increment count[2] by 1
•Insert 432 at b[4][0] and increment count[4] by 1
•Insert 45 at b[0][2] and increment count[0] by 1
•Insert 677 at b[6][0] and increment count[6] by 1
•Insert 88 at b[0][3] and increment count[0] by 1
•Insert 90 at b[0][4] and increment count[0] by 1
•Insert 199 at b[1][0] and increment count[1] by 1
0 Count b 0 1 2 3 4 5 6 7 8 9
5 8 11 45 88 90
0

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

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;
}
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++)
{

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

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: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

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)
o Free node after 20 (30)
o Set 20.next = NULL
✅ List: 10 → 20 → NULL
🔹 Display List Again
Output: 10 20

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;
}
}

void lastinsert() // Function to insert NODE at Ending


{
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)
{

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");
}
}

void lastdelete() // Function to Delete Last NODE


{

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

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
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

Enter your Choice...8

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;
};

void create(struct node **);


void reverse(struct node **);
void release(struct node **);
void display(struct node *);

int main()
{
struct node *p = NULL;
int n;

printf("Enter data into the list\n");


create(&p);
printf("Displaying the nodes in the list:\n");
display(p);
printf("Reversing the list...\n");
reverse(&p);
printf("Displaying the reversed list:\n");
display(p);
release(&p);

return 0;

Page
no:
Date: Roll
number:24B11EC085

void reverse(struct node **head)


{
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;
}

void create(struct node **head)


{
int c, ch;
struct node *temp, *rear;

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");
}

void display(struct node *p)


{
while (p != NULL)
{
printf("%d\t", p->num);
p = p->next;
}
printf("\n");
}

void release(struct node **head)


{
struct node *temp = *head;
*head = (*head)->next;
while ((*head) != NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}

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

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

Displaying the nodes in the list:


1 2 3 4 5
Reversing the list...
Displaying the reversed list:
5 4 3 2 1

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

 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
1. Create a new node.
2. If the list is empty, set head = newNode.
3. Else:
o Traverse to the last node.
o Set lastNode.next = newNode.
o Set newNode.prev = lastNode.
4️. Insert at a Given Position (pos)
1. If position is 1, use Insert at Beginning.
2. Traverse to (pos - 1) node.
3. Create a new node.
4. Adjust links:
o newNode.next = current.next
o newNode.prev = current
o current.next.prev = newNode
o current.next = newNode
5️Delete from Beginning
1. If list is empty, exit.

Page
no:
Date: Roll
number:24B11EC085

2. Set temp = head.


3. Set head = head.next.
4. If head is not NULL, set head.prev = NULL.
5. Free temp.
6️.Delete from End
1. If list is empty, exit.
2. Traverse to the last node.
3. Set last.prev.next = NULL.
4. Free last node.
7️.Delete from a Given Position (pos)
1. Traverse to the node at position.
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

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;
};

void firstinsert() // Function to insert NODE at First


{
struct node *start=NULL,*temp=NULL,*last=NULL,*t1=NULL,*t2=NULL;
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->llink=NULL;
temp->rlink=NULL;
if(start==NULL)
{
start=temp;
last=temp;
}
else
{

Page
no:
Date: Roll
number:24B11EC085

temp->rlink=start;
start=temp;
last->llink=temp;
}
}

void lastinsert() // Function to insert NODE at Ending


{
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->rlink=NULL;
temp->llink=NULL;
if(start==NULL)
{
start=temp;
last=temp;
}
else
{
last->rlink=temp;
temp->llink=last;
last=temp;
}

Page
no:
Date: Roll
number:24B11EC085

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->llink=NULL;
temp->rlink=NULL;
printf("\n Enter the postion to insert");
scanf("%d",&pos);
if(start==NULL)
{
start=temp;
last=temp;
}
else
{
printf("\n Insdie of middle insert fun");
t1=start;
while(i<pos)
{

Page
no:
Date: Roll
number:24B11EC085

t2=t1;
t1=t1->rlink;
i++;
}
temp->rlink=t1;
t1->llink=temp;
t2->rlink=temp;
temp->llink=t2;
}
}

void firstdelete() // Function to Delete First NODE


{
if(start==NULL)
{
printf("\n\t Linked List is Empty, No Nodes to perform Delete Operation");
}
else
{
t1=start->rlink;
start=start->rlink;
t1->llink=NULL;
cout<<"\n\t First Node is Deleted Successfully";
}
}

Page
no:
Date: Roll
number:24B11EC085

void lastdelete() // Function to Delete Last NODE


{
if(start==NULL)
printf("\n\t No Nodes in Linked List to delete");
else
{
t1=last->llink;
t1->rlink=NULL;
last=t1;
}
}

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->rlink;

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

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:
----- 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

Enter your Choice...8

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

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
o Set lastNode.next = newNode
o Set newNode.next = head
4️.Insert at a Specific Position (pos)
1. If pos == 1, call Insert at Beginning.
2. Traverse to the (pos - 1)-th node.
3. Set newNode.next = current.next
4. Set current.next = newNode
5️.Delete from Beginning
1. If the list is empty, exit.
2. If there is only one node:
o Free the node and set head = NULL
3. Else:
o Traverse to the last node
o Set last.next = head.next
o Free the old head
o Update head = head.next
6️.Delete from End
1. If the list is empty, exit.
2. If there is only one node:

Page
no:
Date: Roll
number:24B11EC085

o Free it and set head = NULL


3. Else:
o Traverse to the second last node
o Set secondLast.next = head
o Free the last node
7.Delete from a Specific Position (pos)
1. If pos == 1, call Delete from Beginning.
2. Traverse to the (pos - 1)-th node.
3. Set temp = current.next
4. Set current.next = temp.next
5. Free temp
8️.Traverse the List
1. If head == NULL, print “Empty List”
2. Start from head
3. Do the following loop:
o Print current.data
o Move current = current.next
o Repeat until current == head

Program:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;

Page
no:
Date: Roll
number:24B11EC085

struct node *link;


};
struct node *start=NULL,*last=NULL,*temp,*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;
}
else
{
temp->link=start;
start=temp;
last=temp;
}
}

void lastinsert() // Function to insert NODE at Ending

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

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)
{
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");

Page
no:
Date: Roll
number:24B11EC085

}
else
{
start=start->link;
last->link=start;
printf("\n\t First Node is Deleted Successfully");
}
}

void lastdelete() // Function to Delete Last NODE


{
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;
}
}

Page
no:
Date: Roll
number:24B11EC085

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: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

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

Enter your Choice...8

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

 Check if stack is full (top == 4)


 If not full:
o Increment top
o Assign value 10 to stack[top]

🔹 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);
}

// Function to push an element into the stack


void push() {
int x;
if (top == n - 1) {
printf("Stack is full\n");
} else {
printf("Enter element: ");
scanf("%d", &x);
top++;
stack[top] = x;
printf("Element inserted\n");
}

Page
no:
Date: Roll
number:24B11EC085

// Function to pop an element from the stack


void pop() {
if (top == -1) {
printf("Stack is empty\n");
} else {
printf("Deleted element is: %d\n", stack[top]);
top--;
}
}

// Function to display the stack elements


void display() {
if (top == -1) {
printf("Stack is empty\n");
} else {
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
Output :
Enter size of stack : 5

Page
no:
Date: Roll
number:24B11EC085

Stack operation 1.push 2.pop 3.display 4.exit


Enter your choice : 1
Enter element : 10
Element inserted
Enter your choice : 1
Enter element : 20
Element inserted
Enter your choice : 1
Enter element : 30
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:

Page
no:
Date: Roll
number:24B11EC085

🔹 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.
🔹 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

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

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) {
printf("%d ", temp->data);
temp = temp->link;
}
}
}
int main(){
int ch;
while(1)
{
printf("\n\tstack operations are:");
printf("\n\t 1. push");

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

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
3.display
4.exit
Enter your choice ….2
Deleted element : 20
Stack operations are:
1.push
2.pop

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).

✅ Step 2: Read the Postfix Expression from Left to Right


For each character/token in the expression:

Page
no:
Date: Roll
number:24B11EC085

➤ If it’s an operand (number):


 Push it onto the stack.
➤ If it’s an operator (+, -, *, /):
 Pop two elements from the stack.
 Apply the operator:
result = operand2 operator operand1
 Push the result back onto the stack.

✅ Step 3: Final Answer


After the entire expression is processed, the result will be at the top of the stack.

💡 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()
{

printf("Enter queue size:");


scanf("%d",&n);
printf("Queue operation: 1.insert 2.delete 3.Display 4. Exit");
while(1)
{
printf("Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: delete(); break;

Page
no:
Date: Roll
number:24B11EC085

case 3: display(); break;


case 4: printf("Exit from queue:");exit(0);
default: printf("\n INVAILD CHOICE,try again");
}
}
}
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");

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

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
Deleted data element is: 10
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 3
Queue elements are:
20
Queue operations : 1.insert 2.delete 3.display 4.exit
Enter your choice: 4
Exit from queue.

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.

It works like a line of people:


 New person joins at the rear.
 First person in line leaves from the front.
Procedure:
✅ Procedure for Queue Using Linked List
1. Define a Node Structure
o Each node should have:
 data: to store the value.

Page
no:
Date: Roll
number:24B11EC085

 next: pointer to the next node.


2. Initialize the Queue
o Create two pointers: front and rear.
o Set both to NULL initially (empty queue).
3. Enqueue (Insert) Operation
o Create a new node with the given data.
o Set next of the new node to NULL.
o If the queue is empty (front == NULL):
 Set both front and rear to the new node.
o Else:
 Set rear->next to the new node.
 Update rear to the new node.
4. Dequeue (Remove) Operation
o Check if the queue is empty (front == NULL):
 If yes, print "Queue is empty".
o Else:
 Store the front node in a temp pointer.
 Move front to front->next.
 Free the temp node.
 If front becomes NULL, set rear = NULL (queue is now empty).
5. Display Operation (Optional)
o Start from front and print all node values until NULL.
Program:
#include<stdio.h>
#include<stdlib.h>
struct node

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

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
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

o If yes, print "Queue is full".


 If the queue is empty (front == -1):
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()

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

Enter your choice1


enter element30
element 30 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice1
enter element40
element 40 inserted
QUEUE OPERATIONS ARE
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

Page
no:
Date: Roll
number:24B11EC085

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
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice3
Queue elements30 40 50
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit

Page
no:
Date: Roll
number:24B11EC085

Enter your choice1


enter element60
element 60 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice1
enter element70
element 70 inserted
QUEUE OPERATIONS ARE
1.Insert
2.Delete
3.disp
4.Exit
Enter your choice3
Queue elements30 40 50 60 70

QUEUE OPERATIONS ARE


1.Insert
2.Delete
3.disp
4.Exit
Enter your choice 4

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>

typedef struct BST


{
int data;
struct BST *left;
struct BST *right;
}node;

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;
}

void insert(node *root,node *temp)


{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)

Page
no:
Date: Roll
number:24B11EC085

insert(root->right,temp);
else
root->right=temp;
}
}

void preorder(node *root)


{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}

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;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

Page
no:
Date: Roll
number:24B11EC085

// Function to insert a new node into the BST


struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}

// Function for Inorder traversal (Left-Root-Right)


void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

// Function for Preorder traversal (Root-Left-Right)


void preorderTraversal(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);

Page
no:
Date: Roll
number:24B11EC085

preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

// Function for Postorder traversal (Left-Right-Root)


void postorderTraversal(struct Node* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}

int main() {
struct Node* root = NULL;

// Insert some nodes into the BST


root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

Page
no:
Date: Roll
number:24B11EC085

printf("Inorder traversal: ");


inorderTraversal(root);
printf("\n");

printf("Preorder traversal: ");


preorderTraversal(root);
printf("\n");

printf("Postorder traversal: ");


postorderTraversal(root);
printf("\n");

// In a real application, you would need to free the allocated memory


// for the nodes to avoid memory leaks.

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

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.

Program:

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

#define MAX_NODES 100

// Structure to represent the adjacency list for each node


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

// Array of adjacency lists representing the graph


struct Node* adj[MAX_NODES];

// Array to keep track of visited nodes


int visited[MAX_NODES];

// Queue structure for BFS


int queue[MAX_NODES];
int front = -1;
int rear = -1;

// Function to add an edge to the graph

Page
no:
Date: Roll
number:24B11EC085

void addEdge(int u, int v) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = adj[u];
adj[u] = newNode;

// For an undirected graph, add the reverse edge as well


newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = u;
newNode->next = adj[v];
adj[v] = newNode;
}

// Function to enqueue a vertex


void enqueue(int v) {
if (rear == MAX_NODES - 1) {
printf("Queue Overflow\n");
return;
}
if (front == -1) {
front = 0;
}
queue[++rear] = v;
}

// Function to dequeue a vertex


int dequeue() {
if (front == -1) {
printf("Queue Underflow\n");
return -1; // Indicate an empty queue
}
int v = queue[front++];
if (front > rear) {
front = rear = -1; // Reset queue if it becomes empty
}
return v;
}

// Breadth First Search function

Page
no:
Date: Roll
number:24B11EC085

void BFS(int startVertex, int numNodes) {


// Initialize visited array
for (int i = 0; i < numNodes; i++) {
visited[i] = 0;
}

// Enqueue the starting vertex and mark it as visited


enqueue(startVertex);
visited[startVertex] = 1;

printf("Breadth First Search starting from vertex %d: ", startVertex);

while (front != -1) {


int currentVertex = dequeue();
printf("%d ", currentVertex);

// Traverse the adjacency list of the current vertex


struct Node* neighbor = adj[currentVertex];
while (neighbor != NULL) {
int adjVertex = neighbor->vertex;
if (!visited[adjVertex]) {
visited[adjVertex] = 1;
enqueue(adjVertex);
}
neighbor = neighbor->next;
}
}
printf("\n");
}

int main() {
int numNodes = 6; // Example graph with 6 nodes (0 to 5)

// Initialize adjacency lists


for (int i = 0; i < numNodes; i++) {
adj[i] = NULL;
}

// Add edges to the graph (example undirected graph)

Page
no:
Date: Roll
number:24B11EC085

addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(3, 5);
addEdge(4, 5);

// Perform BFS starting from vertex 0


BFS(0, numNodes);

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>

#define MAX_NODES 100

// Structure to represent an adjacency list node


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

// Array of adjacency lists representing the graph


struct Node* adj[MAX_NODES];

// Array to keep track of visited nodes (0 for not visited, 1 for visited)
int visited[MAX_NODES];

// Stack for DFS (using array for simplicity)


int stack[MAX_NODES];
int top = -1;

// Function to push onto the stack


void push(int v) {

Page
no:
Date: Roll
number:24B11EC085

if (top == MAX_NODES - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = v;
}

// Function to pop from the stack


int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1; // Indicate empty stack
}
return stack[top--];
}

// Function to add an edge to the graph (undirected)


void addEdge(int u, int v) {
// Add edge from u to v
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = adj[u];
adj[u] = newNode;
// Add edge from v to u (for undirected graph)
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = u;

Page
no:
Date: Roll
number:24B11EC085

newNode->next = adj[v];
adj[v] = newNode;
}

// Depth First Search function (Iterative using stack)


void DFS(int startVertex, int numNodes) {
// Initialize visited array
for (int i = 0; i < numNodes; i++) {
visited[i] = 0;
}

// Push the starting vertex onto the stack and mark it as visited
push(startVertex);
visited[startVertex] = 1;

printf("Depth First Search starting from vertex %d: ", startVertex);

while (top != -1) {


int currentVertex = pop();
printf("%d ", currentVertex);

// Traverse the adjacency list of the current vertex


struct Node* neighbor = adj[currentVertex];
while (neighbor != NULL) {
int adjVertex = neighbor->vertex;
if (!visited[adjVertex]) {

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;
}

// Add edges to the graph (example undirected graph)


addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(1, 4);
addEdge(2, 5);
addEdge(2, 6);
int startVertex = 0;
DFS(startVertex, numNodes);
return 0;
}

Page
no:
Date: Roll
number:24B11EC085

OUTPUT:
Depth First Search starting from vertex 0: 0 2 6 5 1 4 3

Page
no:

You might also like