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

DSA Lab Manual Program 1 to 11

The document outlines two C programs: one for matrix operations including addition, multiplication, transpose, and triangular matrix checks, and another for linear and binary search algorithms. It provides detailed algorithms, pseudocode, and complete C code for each program. The document also includes instructions for user input and output for the matrix operations and search methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DSA Lab Manual Program 1 to 11

The document outlines two C programs: one for matrix operations including addition, multiplication, transpose, and triangular matrix checks, and another for linear and binary search algorithms. It provides detailed algorithms, pseudocode, and complete C code for each program. The document also includes instructions for user input and output for the matrix operations and search methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

03rd Sept 2024 Aayush Mehta

Program 1

Aim  Write a program in C to implement matrix operations:


a. Addition
b. Multiplication
c. Transpose
d. Upper and lower triangular matrix
e. Sparse-matrix

Algorithm:
1. Matrix Addition
1. Input: Two matrices A and B of size m x n.
2. Initialize a new matrix C of size m x n.
3. For each element C[i][j]:
 C[i][j] = A[i][j] + B[i][j]
4. Output matrix C.

Pseudocode:
function matrixAddition(A, B):
m = number of rows in A
n = number of columns in A
C = new matrix of size m x n

for i from 0 to m-1:


for j from 0 to n-1:
C[i][j] = A[i][j] + B[i][j]

return C

2. Matrix Multiplication
1. Input: Two matrices A (size m x n) and B (size n x p).
2. Initialize a new matrix C of size m x p.
3. For each element C[i][j]:
 C[i][j] = 0
 For k from 0 to n-1:
 C[i][j] += A[i][k] * B[k][j]
4. Output matrix C.

Pseudocode:
function matrixMultiplication(A, B):
m = number of rows in A
n = number of columns in A
p = number of columns in B
C = new matrix of size m x p

for i from 0 to m-1:


for j from 0 to p-1:
C[i][j] = 0

1
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

for k from 0 to n-1:


C[i][j] += A[i][k] * B[k][j]

return C

3. Matrix Transpose
1. Input: A matrix A of size m x n.
2. Initialize a new matrix B of size n x m.
3. For each element B[j][i]:
 B[j][i] = A[i][j]
4. Output matrix B.

Pseudocode:
function matrixTranspose(A):
m = number of rows in A
n = number of columns in A
B = new matrix of size n x m

for i from 0 to m-1:


for j from 0 to n-1:
B[j][i] = A[i][j]

return B

4. Upper and Lower Triangular Matrix


 Upper Triangular:
1. Input: A matrix A of size n x n.
2. For each element A[i][j] where i > j:
 If A[i][j] ≠ 0, it is not upper triangular.
3. Output true if all elements below the main diagonal are zero, else false.
 Lower Triangular:
1. Input: A matrix A of size n x n.
2. For each element A[i][j] where i < j:
 If A[i][j] ≠ 0, it is not lower triangular.
3. Output true if all elements above the main diagonal are zero, else false.

Pseudocode:
function isUpperTriangular(A):
n = number of rows in A
for i from 1 to n-1:
for j from 0 to i-1:
if A[i][j] ≠ 0:
return false
return true

function isLowerTriangular(A):
n = number of rows in A
for i from 0 to n-1:
for j from i+1 to n-1:
2
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

if A[i][j] ≠ 0:
return false
return true

5. Sparse Matrix Representation


1. Input: A matrix A of size m x n.
2. Initialize an empty list or array to store non-zero elements.
3. For each element A[i][j]:
 If A[i][j] ≠ 0:
 Add (i, j, A[i][j]) to the list.
4. Output the list of non-zero elements.

Pseudocode:
function sparseMatrixRepresentation(A):
m = number of rows in A
n = number of columns in A
sparseList = new list

for i from 0 to m-1:


for j from

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

#define MAX 100

// Function prototypes
void inputMatrix(int matrix[MAX][MAX], int *rows, int *cols);
void printMatrix(int matrix[MAX][MAX], int rows, int cols);
void addMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int rows, int
cols);
void multiplyMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int
rowsA, int colsA, int rowsB, int colsB);
void transposeMatrix(int A[MAX][MAX], int B[MAX][MAX], int rows, int cols);
int isUpperTriangular(int matrix[MAX][MAX], int size);
int isLowerTriangular(int matrix[MAX][MAX], int size);
void sparseMatrixRepresentation(int matrix[MAX][MAX], int rows, int cols);

int main() {
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int rowsA, colsA, rowsB, colsB;

// Input first matrix


printf("Enter the dimensions of the first matrix (rows and columns): ");
scanf("%d %d", &rowsA, &colsA);
printf("Enter the elements of the first matrix:\n");
inputMatrix(A, &rowsA, &colsA);
3
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Input second matrix


printf("Enter the dimensions of the second matrix (rows and columns): ");
scanf("%d %d", &rowsB, &colsB);
printf("Enter the elements of the second matrix:\n");
inputMatrix(B, &rowsB, &colsB);

// Matrix Addition
if (rowsA == rowsB && colsA == colsB) {
addMatrices(A, B, C, rowsA, colsA);
printf("Result of Addition:\n");
printMatrix(C, rowsA, colsA);
} else {
printf("Matrices cannot be added due to dimension mismatch.\n");
}

// Matrix Multiplication
if (colsA == rowsB) {
multiplyMatrices(A, B, C, rowsA, colsA, rowsB, colsB);
printf("Result of Multiplication:\n");
printMatrix(C, rowsA, colsB);
} else {
printf("Matrices cannot be multiplied due to dimension mismatch.\n");
}

// Matrix Transpose
transposeMatrix(A, C, rowsA, colsA);
printf("Transpose of the first matrix:\n");
printMatrix(C, colsA, rowsA);

// Check for Upper and Lower Triangular


if (isUpperTriangular(A, rowsA)) {
printf("The first matrix is an upper triangular matrix.\n");
} else {
printf("The first matrix is not an upper triangular matrix.\n");
}

if (isLowerTriangular(A, rowsA)) {
printf("The first matrix is a lower triangular matrix.\n");
} else {
printf("The first matrix is not a lower triangular matrix.\n");
}

// Sparse Matrix Representation


printf("Sparse matrix representation of the first matrix:\n");
sparseMatrixRepresentation(A, rowsA, colsA);

return 0;
}
4
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Function to input a matrix


void inputMatrix(int matrix[MAX][MAX], int *rows, int *cols) {
for (int i = 0; i < *rows; i++) {
for (int j = 0; j < *cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
}

// Function to print a matrix


void printMatrix(int matrix[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

// Function to add two matrices


void addMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int rows, int
cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}

// Function to multiply two matrices


void multiplyMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int
rowsA, int colsA, int rowsB, int colsB) {
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
C[i][j] = 0; // Initialize the result matrix element
for (int k = 0; k < colsA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}

// Function to transpose a matrix


void transposeMatrix(int A[MAX][MAX], int B[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
B[j][i] = A[i][j];
}
5
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

}
}

// Function to check if a matrix is upper triangular


int isUpperTriangular(int matrix[MAX][MAX], int size) {
for (int i = 1; i < size; i++) {
for (int j = 0; j < i; j++) {
if (matrix[i][j] != 0) {
return 0; // Not upper triangular
}
}
}
return 1; // Is upper triangular
}

// Function to check if a matrix is lower triangular


int isLowerTriangular(int matrix[MAX][MAX], int size) {
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (matrix[i][j] != 0) {
return 0; // Not lower triangular
}
}
}
return 1; // Is lower triangular
}

// Function to represent a sparse matrix


void sparseMatrixRepresentation(int matrix[MAX][MAX], int rows, int cols) {
printf("Row\tColumn\tValue\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] != 0) {
printf("%d\t%d\t%d\n", i, j, matrix[i][j]);
}
}
}
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");
}

6
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Output:

7
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

8
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 2

Aim  Write a program in C to implement linear search and binary search.

Algorithm:
1. Linear Search Algorithm:
Linear Search is a simple search algorithm that checks every element in a list until the desired
element is found or the list ends.
1. Start with the first element of the array.
2. Compare the current element with the target value.
3. If the current element is equal to the target value, return the index of the current
element.
4. If the current element is not equal to the target value, move to the next element.
5. Repeat steps 2-4 until the target value is found or the end of the array is reached.
6. If the end of the array is reached and the target value is not found, return -1
(indicating that the target is not in the array).

Pseudocode:
function linearSearch(array, target):
for i from 0 to length(array) - 1:
if array[i] == target:
return i // Target found at index i
return -1 // Target not found

2. Binary Search Algorithm:


Binary Search is a more efficient search algorithm that works on sorted arrays. It repeatedly
divides the search interval in half.
1. Start with two pointers: low (set to the first index) and high (set to the last
index) of the array.
2. While low is less than or equal to high:
 Calculate the middle index: mid = (low + high) / 2.
 If the element at mid is equal to the target value, return mid.
 If the element at mid is less than the target value, set low = mid +
1 (search in the right half).
 If the element at mid is greater than the target value, set high = mid -
1 (search in the left half).
3. If the target value is not found, return -1.

Pseudocode:
function binarySearch(array, target):
low = 0
high = length(array) - 1

while low <= high:


mid = (low + high) / 2
if array[mid] == target:
return mid // Target found at index mid
else if array[mid] < target:

9
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

low = mid + 1 // Search in the right half


else:
high = mid - 1 // Search in the left half

return -1 // Target not found

Code:
#include <stdio.h>

// Function prototypes
int linearSearch(int arr[], int size, int target);
int binarySearch(int arr[], int size, int target);

int main() {
int choice, size, target;

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &size);

int arr[size];

// Input the elements of the array


printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Ask user for the target value


printf("Enter the target value to search: ");
scanf("%d", &target);

// Ask user for the search method


printf("Choose search method:\n1. Linear Search\n2. Binary Search\n");
scanf("%d", &choice);

switch (choice) {
case 1: // Linear Search
{
int result = linearSearch(arr, size, target);
if (result != -1) {
printf("Linear Search: Element found at index %d\n", result);
} else {
printf("Linear Search: Element not found\n");
}
}
break;

case 2: // Binary Search


10
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// First, sort the array for binary search


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

int result = binarySearch(arr, size, target);


if (result != -1) {
printf("Binary Search: Element found at index %d\n", result);
} else {
printf("Binary Search: Element not found\n");
}
break;

default:
printf("Invalid choice\n");
break;
}
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");
return 0;
}

// Function to perform linear search


int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Target found at index i
}
}
return -1; // Target not found
}

// Function to perform binary search


int binarySearch(int arr[], int size, int target) {
int low = 0;
int high = size - 1;

while (low <= high) {


int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid; // Target found at index mid
} else if (arr[mid] < target) {
11
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

low = mid + 1; // Search in the right half


} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Target not found
}

Output:

12
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

13
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 3

Aim  Write a program in C to implement Bubble sort, selection and insertion sort.

Algorithm:
1. Bubble Sort Algorithm
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. The pass through the list is
repeated until the list is sorted.
1. Start with the first element of the array.
2. Compare the current element with the next element.
3. If the current element is greater than the next element, swap them.
4. Move to the next element and repeat steps 2-3 until the end of the array is reached.
5. Repeat the entire process for the array until no swaps are needed (the array is sorted).

Pseudocode:
function bubbleSort(array):
n = length(array)
for i from 0 to n-1:
for j from 0 to n-i-2:
if array[j] > array[j+1]:
swap(array[j], array[j+1])

2. Selection Sort Algorithm


Selection Sort is a sorting algorithm that divides the input list into two parts: a sorted part and
an unsorted part. It repeatedly selects the smallest (or largest) element from the unsorted part
and moves it to the end of the sorted part.
1. Start with the first element as the minimum.
2. Compare this minimum with the next elements in the array to find the smallest
element.
3. Swap the smallest element found with the first element.
4. Move the boundary of the sorted part one element to the right.
5. Repeat steps 1-4 for the remaining unsorted elements.

Pseudocode:
function selectionSort(array):
n = length(array)
for i from 0 to n-1:
minIndex = i
for j from i+1 to n-1:
if array[j] < array[minIndex]:
minIndex = j
swap(array[i], array[minIndex])

3. Insertion Sort Algorithm


Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a
time. It is much less efficient on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort.

14
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

1. Start with the second element (the first element is considered sorted).
2. Compare the current element with the elements in the sorted part (to its left).
3. Shift all elements in the sorted part that are greater than the current element to the
right.
4. Insert the current element into its correct position in the sorted part.
5. Repeat steps 2-4 for all elements in the array.

Pseudocode:
function insertionSort(array):
n = length(array)
for i from 1 to n-1:
key = array[i]
j=i-1
while j >= 0 and array[j] > key:
array[j + 1] = array[j]
j=j-1
array[j + 1] = key

Code:
#include <stdio.h>

// Function prototypes
void bubbleSort(int arr[], int size);
void selectionSort(int arr[], int size);
void insertionSort(int arr[], int size);
void printArray(int arr[], int size);

int main() {
int choice, size;

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &size);

int arr[size];

// Input the elements of the array


printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Ask user for the sorting method


printf("Choose sorting method:\n1. Bubble Sort\n2. Selection Sort\n3. Insertion Sort\n");
scanf("%d", &choice);

switch (choice) {
case 1: // Bubble Sort
bubbleSort(arr, size);
15
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("Sorted array using Bubble Sort:\n");


printArray(arr, size);
break;

case 2: // Selection Sort


selectionSort(arr, size);
printf("Sorted array using Selection Sort:\n");
printArray(arr, size);
break;

case 3: // Insertion Sort


insertionSort(arr, size);
printf("Sorted array using Insertion Sort:\n");
printArray(arr, size);
break;

default:
printf("Invalid choice\n");
break;
}

return 0;
}

// Function to perform Bubble Sort


void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to perform Selection Sort


void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap arr[i] and arr[minIndex]
int temp = arr[i];
16
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

// Function to perform Insertion Sort


void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1] that are greater than key
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");
}

Output:

17
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

18
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 4

Aim  Write a program in C to implement Quick sort and Merge Sort.

Algorithm:
1. Quick Sort Algorithm
Quick Sort is a divide-and-conquer algorithm that sorts an array by selecting a 'pivot' element
and partitioning the other elements into two sub-arrays according to whether they are less
than or greater than the pivot. The sub-arrays are then sorted recursively.
Algorithm:
1. Choose a pivot element from the array.
2. Partition the array into two sub-arrays:
 Elements less than the pivot.
 Elements greater than the pivot.
3. Recursively apply the above steps to the sub-arrays.
4. Combine the sorted sub-arrays and the pivot to get the final sorted array.

Pseudocode:
function quickSort(array, low, high):
if low < high:
pivotIndex = partition(array, low, high)
quickSort(array, low, pivotIndex - 1) // Sort left sub-array
quickSort(array, pivotIndex + 1, high) // Sort right sub-array

19
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

function partition(array, low, high):


pivot = array[high] // Choose the last element as pivot
i = low - 1
for j from low to high - 1:
if array[j] < pivot:
i=i+1
swap(array[i], array[j])
swap(array[i + 1], array[high])
return i + 1

2. Merge Sort Algorithm


Merge Sort is another divide-and-conquer algorithm that divides the array into two halves,
sorts them, and then merges the sorted halves back together.
Algorithm:
1. Divide the unsorted array into two halves.
2. Recursively sort both halves.
3. Merge the two sorted halves into a single sorted array.

Pseudocode:
function mergeSort(array):
if length(array) > 1:
mid = length(array) / 2
leftHalf = array[0..mid]
rightHalf = array[mid..end]

mergeSort(leftHalf) // Sort the left half


mergeSort(rightHalf) // Sort the right half

i=j=k=0

// Merge the sorted halves


while i < length(leftHalf) and j < length(rightHalf):
if leftHalf[i] < rightHalf[j]:
array[k] = leftHalf[i]
i=i+1
else:
array[k] = rightHalf[j]
j=j+1
k=k+1

// Copy remaining elements of leftHalf, if any


while i < length(leftHalf):
array[k] = leftHalf[i]
i=i+1
k=k+1

// Copy remaining elements of rightHalf, if any


while j < length(rightHalf):
array[k] = rightHalf[j]
20
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

j=j+1
k=k+1

Code:
#include <stdio.h>

// Function prototypes
void quickSort(int arr[], int low, int high);
int partition(int arr[], int low, int high);
void mergeSort(int arr[], int left, int right);
void merge(int arr[], int left, int mid, int right);
void printArray(int arr[], int size);

int main() {
int choice, size;

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &size);

int arr[size];

// Input the elements of the array


printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Ask user for the sorting method


printf("Choose sorting method:\n1. Quick Sort\n2. Merge Sort\n");
scanf("%d", &choice);

switch (choice) {
case 1: // Quick Sort
quickSort(arr, 0, size - 1);
printf("Sorted array using Quick Sort:\n");
printArray(arr, size);
break;

case 2: // Merge Sort


mergeSort(arr, 0, size - 1);
printf("Sorted array using Merge Sort:\n");
printArray(arr, size);
break;

default:
printf("Invalid choice\n");
break;
}
21
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:


B");

return 0;
}

// Function to perform Quick Sort


void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1); // Sort left sub-array
quickSort(arr, pivotIndex + 1, high); // Sort right sub-array
}
}

// Function to partition the array


int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the last element as pivot
int i = low - 1; // Index of smaller element
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i + 1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1; // Return the partitioning index
}

// Function to perform Merge Sort


void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2; // Find the middle point
mergeSort(arr, left, mid); // Sort first half
mergeSort(arr, mid + 1, right); // Sort second half
merge(arr, left, mid, right); // Merge the sorted halves
}
}

// Function to merge two halves


void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1; // Size of left sub-array
22
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

int n2 = right - mid; // Size of right sub-array

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temporary arrays


for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// Merge the temporary arrays back into arr[left..right]


i = 0; // Initial index of first sub-array
j = 0; // Initial index of second sub-array
k = left; // Initial index of merged sub-array
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

23
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Output:

24
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 5

Aim  Write a program in C to implement singly linked list and perform the following
operations on it:
a. Insertion in beginning
b. Insertion at the end
c. insertion at specific location
d. deletion in beginning
e. deletion at the end
f. deletion at specific location

Algorithm:
1. Insertion at the Beginning
 Create a new node.
 Set the new node's next pointer to the current head.
 Update the head to point to the new node.
2. Insertion at the End
 Create a new node.
 If the list is empty, set the head to the new node.
 Otherwise, traverse to the end of the list and set the last node's next pointer to
the new node.
3. Insertion at a Specific Location
 Create a new node.
 If the specified location is 0, perform insertion at the beginning.
 Otherwise, traverse to the node just before the specified location and adjust
pointers accordingly.
4. Deletion at the Beginning
 If the list is empty, return.
 Update the head to point to the second node.
5. Deletion at the End
 If the list is empty, return.
 If there is only one node, set the head to NULL.
 Otherwise, traverse to the second-to-last node and set its next pointer
to NULL.
6. Deletion at a Specific Location
 If the specified location is 0, perform deletion at the beginning.
 Otherwise, traverse to the node just before the specified location and adjust
pointers accordingly.

Pseudocode:
struct Node {
int data;
struct Node* next;
};

struct LinkedList {
Node* head;
};

25
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Function to insert at the beginning


function insertAtBeginning(LinkedList* list, int data):
Node* newNode = createNode(data)
newNode->next = list->head
list->head = newNode

// Function to insert at the end


function insertAtEnd(LinkedList* list, int data):
Node* newNode = createNode(data)
if list->head is NULL:
list->head = newNode
else:
Node* current = list->head
while current->next is not NULL:
current = current->next
current->next = newNode

// Function to insert at a specific location


function insertAtLocation(LinkedList* list, int data, int position):
if position == 0:
insertAtBeginning(list, data)
else:
Node* newNode = createNode(data)
Node* current = list->head
for i from 0 to position - 2:
if current is NULL:
return // Position is out of bounds
current = current->next
newNode->next = current->next
current->next = newNode

// Function to delete at the beginning


function deleteAtBeginning(LinkedList* list):
if list->head is NULL:
return // List is empty
Node* temp = list->head
list->head = list->head->next
free(temp)

// Function to delete at the end


function deleteAtEnd(LinkedList* list):
if list->head is NULL:
return // List is empty
if list->head->next is NULL:
free(list->head)
list->head = NULL
else:
Node* current = list->head
26
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

while current->next->next is not NULL:


current = current->next
free(current->next)
current->next = NULL

// Function to delete at a specific location


function deleteAtLocation(LinkedList* list, int position):
if position == 0:
deleteAtBeginning(list)
else:
Node* current = list->head
for i from 0 to position - 2:
if current is NULL or current->next is NULL:
return // Position is out of bounds
current = current->next
Node* temp = current->next
if temp is NULL:
return // Position is out of bounds
current->next = temp->next
free(temp)

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

// Define the structure for a node in the linked list


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

// Function prototypes
struct Node* createNode(int data);
void insertAtBeginning(struct Node** head, int data);
void insertAtEnd(struct Node** head, int data);
void insertAtLocation(struct Node** head, int data, int position);
void deleteAtBeginning(struct Node** head);
void deleteAtEnd(struct Node** head);
void deleteAtLocation(struct Node** head, int position);
void printList(struct Node* head);
void freeList(struct Node* head);

int main() {
struct Node* head = NULL; // Initialize the head of the list
int choice, data, position;

while (1) {
printf("\nSingly Linked List Operations:\n");
printf("1. Insert at Beginning\n");
27
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("2. Insert at End\n");


printf("3. Insert at Specific Location\n");
printf("4. Delete at Beginning\n");
printf("5. Delete at End\n");
printf("6. Delete at Specific Location\n");
printf("7. Print List\n");
printf("8. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data to insert at end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter data to insert: ");
scanf("%d", &data);
printf("Enter position to insert at: ");
scanf("%d", &position);
insertAtLocation(&head, data, position);
break;
case 4:
deleteAtBeginning(&head);
break;
case 5:
deleteAtEnd(&head);
break;
case 6:
printf("Enter position to delete at: ");
scanf("%d", &position);
deleteAtLocation(&head, position);
break;
case 7:
printList(head);
break;
case 8:
freeList(head);
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
28
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:


B");

return 0;
}

// Function to create a new node


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

// Function to insert a node at the beginning


void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}

// Function to insert a node at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}

// Function to insert a node at a specific location


void insertAtLocation(struct Node** head, int data, int position) {
if (position < 0) {
printf("Invalid position!\n");
return;
}
if (position == 0) {
insertAtBeginning(head, data);
return;
}
struct Node* newNode = createNode(data);
struct Node* current = *head;
for (int i = 0; i < position - 1; i++) {
29
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

if (current == NULL) {
printf("Position out of bounds!\n");
free(newNode);
return;
}
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}

// Function to delete a node at the beginning


void deleteAtBeginning(struct Node** head) {
if (*head == NULL) {
printf("List is empty!\n");
return;
}
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
}

// Function to delete a node at the end


void deleteAtEnd(struct Node** head) {
if (*head == NULL) {
printf("List is empty!\n");
return;
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return;
}
struct Node* current = *head;
while (current->next->next != NULL) {
current = current->next;
}
free(current->next);
current->next = NULL;
}

// Function to delete a node at a specific location


void deleteAtLocation(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty!\n");
return;
}
if (position < 0) {
printf("Invalid position!\n");
30
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

return;
}
if (position == 0) {
deleteAtBeginning(head);
return;
}
struct Node* current = *head;
for (int i = 0; i < position - 1; i++) {
if (current == NULL || current->next == NULL) {
printf("Position out of bounds!\n");
return;
}
current = current->next;
}
struct Node* temp = current->next;
if (temp == NULL) {
printf("Position out of bounds!\n");
return;
}
current->next = temp->next;
free(temp);
}

// Function to print the linked list


void printList(struct Node* head) {
if (head == NULL) {
printf("List is empty!\n");
return;
}
struct Node* current = head;
printf("Linked List: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

// Function to free the linked list


void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}

31
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Output:

32
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

33
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

34
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

35
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 6

Aim  Write a program in C to implement insertion and deletion operation in doubly linked
list.

Algorithm:
Algorithm for Insertion Operations
1. Insertion at the Beginning
 Create a new node.
 Set the new node's next pointer to the current head.
 If the current head is not NULL, set the current head's prev pointer to the new
node.
 Update the head to point to the new node.
 Set the new node's prev pointer to NULL.
2. Insertion at the End
 Create a new node.
 If the list is empty (head is NULL), set the head to the new node.
 Otherwise, traverse to the last node.
 Set the last node's next pointer to the new node.
 Set the new node's prev pointer to the last node.
 Set the new node's next pointer to NULL.
3. Insertion at a Specific Location
 Create a new node.
 If the specified location is 0, perform insertion at the beginning.
 Otherwise, traverse to the node just before the specified location.
 Adjust the pointers of the new node and the surrounding nodes accordingly.

Algorithm for Deletion Operations


1. Deletion at the Beginning
 If the list is empty (head is NULL), return.
 Update the head to point to the second node.
 If the new head is not NULL, set its prev pointer to NULL.
 Free the old head node.
2. Deletion at the End
 If the list is empty, return.
 If there is only one node, free it and set the head to NULL.
 Otherwise, traverse to the last node.
 Update the second-to-last node's next pointer to NULL.
 Free the last node.
3. Deletion at a Specific Location
 If the specified location is 0, perform deletion at the beginning.
 Otherwise, traverse to the node just before the specified location.
 Adjust the pointers of the surrounding nodes accordingly.
 Free the node to be deleted.

Pseudocode:
struct Node {
int data;

36
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

struct Node* next;


struct Node* prev;
};

struct DoublyLinkedList {
Node* head;
};

// Function to insert at the beginning


function insertAtBeginning(DoublyLinkedList* list, int data):
Node* newNode = createNode(data)
newNode->next = list->head
newNode->prev = NULL
if list->head is not NULL:
list->head->prev = newNode
list->head = newNode

// Function to insert at the end


function insertAtEnd(DoublyLinkedList* list, int data):
Node* newNode = createNode(data)
if list->head is NULL:
newNode->prev = NULL
list->head = newNode
else:
Node* current = list->head
while current->next is not NULL:
current = current->next
current->next = newNode
newNode->prev = current
newNode->next = NULL

// Function to insert at a specific location


function insertAtLocation(DoublyLinkedList* list, int data, int position):
if position == 0:
insertAtBeginning(list, data)
else:
Node* newNode = createNode(data)
Node* current = list->head
for i from 0 to position - 1:
if current is NULL:
return // Position is out of bounds
current = current->next
newNode->next = current
newNode->prev = current->prev
if current->prev is not NULL:
current->prev->next = newNode
current->prev = newNode

// Function to delete at the beginning


37
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

function deleteAtBeginning(DoublyLinkedList* list):


if list->head is NULL:
return // List is empty
Node* temp = list->head
list->head = list->head->next
if list->head is not NULL:
list->head->prev = NULL
free(temp)

// Function to delete at the end


function deleteAtEnd(DoublyLinkedList* list):
if list->head is NULL

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

// Define the structure for a node in the doubly linked list


struct Node {
int data;
struct Node* next;
struct Node* prev;
};

// Function prototypes
struct Node* createNode(int data);
void insertAtBeginning(struct Node** head, int data);
void insertAtEnd(struct Node** head, int data);
void insertAtLocation(struct Node** head, int data, int position);
void deleteAtBeginning(struct Node** head);
void deleteAtEnd(struct Node** head);
void deleteAtLocation(struct Node** head, int position);
void printList(struct Node* head);
void freeList(struct Node* head);

int main() {
struct Node* head = NULL; // Initialize the head of the list
int choice, data, position;

while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Insert at Specific Location\n");
printf("4. Delete at Beginning\n");
printf("5. Delete at End\n");
printf("6. Delete at Specific Location\n");
printf("7. Print List\n");
printf("8. Exit\n");
38
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data to insert at end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter data to insert: ");
scanf("%d", &data);
printf("Enter position to insert at: ");
scanf("%d", &position);
insertAtLocation(&head, data, position);
break;
case 4:
deleteAtBeginning(&head);
break;
case 5:
deleteAtEnd(&head);
break;
case 6:
printf("Enter position to delete at: ");
scanf("%d", &position);
deleteAtLocation(&head, position);
break;
case 7:
printList(head);
break;
case 8:
freeList(head);
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");

return 0;
}

// Function to create a new node


39
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}

// Function to insert a node at the beginning


void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
newNode->prev = NULL;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}

// Function to insert a node at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
newNode->next = NULL;
}

// Function to insert a node at a specific location


void insertAtLocation(struct Node** head, int data, int position) {
if (position < 0) {
printf("Invalid position!\n");
return;
}
if (position == 0) {
insertAtBeginning(head, data);
return;
}
struct Node* newNode = createNode(data);
struct Node* current = *head;
for (int i = 0; i < position - 1; i++) {
40
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

if (current == NULL) {
printf("Position out of bounds!\n");
free(newNode);
return;
}
current = current->next;
}
newNode->next = current->next;
newNode->prev = current;
if (current->next != NULL) {
current->next->prev = newNode;
}
current->next = newNode;
}

// Function to delete a node at the beginning


void deleteAtBeginning(struct Node** head) {
if (*head == NULL) {
printf("List is empty!\n");
return;
}
struct Node* temp = *head;
*head = (*head)->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
}

// Function to delete a node at the end


void deleteAtEnd(struct Node** head) {
if (*head == NULL) {
printf("List is empty!\n");
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
if (current->prev != NULL) {
current->prev->next = NULL;
} else {
// If there was only one node
*head = NULL;
}
free(current);
}

// Function to delete a node at a specific location


41
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

void deleteAtLocation(struct Node** head, int position) {


if (*head == NULL) {
printf("List is empty!\n");
return;
}
if (position < 0) {
printf("Invalid position!\n");
return;
}
struct Node* current = *head;
if (position == 0) {
deleteAtBeginning(head);
return;
}
for (int i = 0; i < position; i++) {
if (current == NULL) {
printf("Position out of bounds!\n");
return;
}
current = current->next;
}
if (current == NULL) {
printf("Position out of bounds!\n");
return;
}
if (current->prev != NULL) {
current->prev->next = current->next;
}
if (current->next != NULL) {
current->next->prev = current->prev;
}
free(current);
}

// Function to print the doubly linked list


void printList(struct Node* head) {
if (head == NULL) {
printf("List is empty!\n");
return;
}
struct Node* current = head;
printf("Doubly Linked List: ");
while (current != NULL) {
printf("%d <-> ", current->data);
current = current->next;
}
printf("NULL\n");
}

42
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Function to free the doubly linked list


void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}

Output:

43
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

44
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

45
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 7

Aim  Write a program in C to implement stack and stack operations (PUSH, POP and
traverse) using array.

Algorithm:
1. Initialize the Stack:
Create an array of a fixed size (e.g., MAX_SIZE).
Initialize a variable top to -1 to indicate that the stack is empty.
2. Push Operation:
Check if the stack is full (i.e., top == MAX_SIZE - 1).
If full, print an error message (stack overflow).
If not full, increment top and assign the new value to stack[top].
3. Pop Operation:
Check if the stack is empty (i.e., top == -1).
If empty, print an error message (stack underflow).
If not empty, retrieve the value from stack[top], decrement top, and return
the value.
4. Traverse Operation:
Check if the stack is empty (i.e., top == -1).
If empty, print a message indicating that the stack is empty.
If not empty, iterate from top to 0 and print each element.

Pseudocode:
Define MAX_SIZE as a constant (e.g., 100)

Define Stack:
array stack[MAX_SIZE]
integer top = -1

Function Push(stack, value):


if top == MAX_SIZE - 1:
Print "Stack Overflow"
else:
top = top + 1
stack[top] = value

Function Pop(stack):
if top == -1:
Print "Stack Underflow"
return NULL
else:
value = stack[top]
top = top - 1
return value

Function Traverse(stack):
if top == -1:

46
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Print "Stack is empty"


else:
for i from top down to 0:
Print stack[i]

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

#define MAX_SIZE 100 // Define the maximum size of the stack

// Define the stack structure


struct Stack {
int arr[MAX_SIZE]; // Array to hold stack elements
int top; // Index of the top element
};

// Function to initialize the stack


void initStack(struct Stack* stack) {
stack->top = -1; // Stack is initially empty
}

// Function to check if the stack is full


int isFull(struct Stack* stack) {
return stack->top == MAX_SIZE - 1; // Returns 1 if full, 0 otherwise
}

// Function to check if the stack is empty


int isEmpty(struct Stack* stack) {
return stack->top == -1; // Returns 1 if empty, 0 otherwise
}

// Function to push an element onto the stack


void push(struct Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow\n");
} else {
stack->arr[++stack->top] = value; // Increment top and add value
printf("Pushed %d onto the stack\n", value);
}
}

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1; // Return -1 to indicate an error
} else {
return stack->arr[stack->top--]; // Return the top value and decrement top
47
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

}
}

// Function to traverse and print the stack


void traverse(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
} else {
printf("Stack elements: ");
for (int i = stack->top; i >= 0; i--) {
printf("%d ", stack->arr[i]);
}
printf("\n");
}
}

// Main function to demonstrate stack operations


int main() {
struct Stack stack; // Create a stack instance
initStack(&stack); // Initialize the stack

// Perform stack operations


push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
traverse(&stack); // Should print: 30 20 10

printf("Popped: %d\n", pop(&stack)); // Should pop 30


traverse(&stack); // Should print: 20 10

printf("Popped: %d\n", pop(&stack)); // Should pop 20


traverse(&stack); // Should print: 10

printf("Popped: %d\n", pop(&stack)); // Should pop 10


traverse(&stack); // Should print: Stack is empty

printf("Popped: %d\n", pop(&stack)); // Should indicate underflow


printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");

return 0;
}

48
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Output:

49
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 8

Aim  Write a program in C to implement queue and its operations (insertion, deletion and
traverse) using array.

Algorithm:
1. Initialize the Queue:
Create an array of a fixed size (e.g., MAX_SIZE).
Initialize front to 0, rear to -1, and size to 0.
2. Enqueue Operation:
Check if the queue is full (i.e., size == MAX_SIZE).
If full, print an error message (queue overflow).
If not full, increment rear (circularly) and add the new value
to queue[rear].
Increment the size.
3. Dequeue Operation:
Check if the queue is empty (i.e., size == 0).
If empty, print an error message (queue underflow).
If not empty, retrieve the value from queue[front],
increment front (circularly), and decrement the size.
4. Traverse Operation:
Check if the queue is empty (i.e., size == 0).
If empty, print a message indicating that the queue is empty.
If not empty, iterate from front to rear and print each element.

Pseudocode:
Define MAX_SIZE as a constant (e.g., 100)

Define Queue:
array queue[MAX_SIZE]
integer front = 0
integer rear = -1
integer size = 0

Function Enqueue(queue, value):


if size == MAX_SIZE:
Print "Queue Overflow"
else:
rear = (rear + 1) % MAX_SIZE
queue[rear] = value
size = size + 1

Function Dequeue(queue):
if size == 0:
Print "Queue Underflow"
return NULL
else:
value = queue[front]

50
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

front = (front + 1) % MAX_SIZE


size = size - 1
return value

Function Traverse(queue):
if size == 0:
Print "Queue is empty"
else:
for i from 0 to size - 1:
index = (front + i) % MAX_SIZE
Print queue[index]

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

#define MAX_SIZE 100 // Define the maximum size of the queue

// Define the queue structure


struct Queue {
int arr[MAX_SIZE]; // Array to hold queue elements
int front; // Index of the front element
int rear; // Index of the rear element
int size; // Current size of the queue
};

// Function to initialize the queue


void initQueue(struct Queue* queue) {
queue->front = 0; // Initialize front
queue->rear = -1; // Initialize rear
queue->size = 0; // Initialize size
}

// Function to check if the queue is full


int isFull(struct Queue* queue) {
return queue->size == MAX_SIZE; // Returns 1 if full, 0 otherwise
}

// Function to check if the queue is empty


int isEmpty(struct Queue* queue) {
return queue->size == 0; // Returns 1 if empty, 0 otherwise
}

// Function to enqueue an element into the queue


void enqueue(struct Queue* queue, int value) {
if (isFull(queue)) {
printf("Queue Overflow\n");
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE; // Circular increment
51
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

queue->arr[queue->rear] = value; // Add value to the queue


queue->size++; // Increment the size
printf("Enqueued %d\n", value);
}
}

// Function to dequeue an element from the queue


int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue Underflow\n");
return -1; // Return -1 to indicate an error
} else {
int value = queue->arr[queue->front]; // Get the front value
queue->front = (queue->front + 1) % MAX_SIZE; // Circular increment
queue->size--; // Decrement the size
return value; // Return the dequeued value
}
}

// Function to traverse and print the queue


void traverse(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
} else {
printf("Queue elements: ");
for (int i = 0; i < queue->size; i++) {
int index = (queue->front + i) % MAX_SIZE; // Calculate index
printf("%d ", queue->arr[index]); // Print each element
}
printf("\n");
}
}

// Main function to demonstrate queue operations


int main() {
struct Queue queue; // Create a queue instance
initQueue(&queue); // Initialize the queue

// Perform queue operations


enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
traverse(&queue); // Should print: 10 20 30

printf("Dequeued: %d\n", dequeue(&queue)); // Should dequeue 10


traverse(&queue); // Should print: 20 30

printf("Dequeued: %d\n", dequeue(&queue)); // Should dequeue 20


traverse(&queue); // Should print: 30
52
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

printf("Dequeued: %d\n", dequeue(&queue)); // Should dequeue 30


traverse(&queue); // Should print: Queue is empty

printf("Dequeued: %d\n", dequeue(&queue)); // Should indicate underflow

printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:


B");

return 0;
}

Output:

53
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 9

Aim  Write a program in C to implement stacks and queues using linked list.

Algorithm:
1. Node Structure:
Define a structure for the node:
struct Node { int data; struct Node* next; };
2. Stack Structure:
Define a structure for the stack:
struct Stack { struct Node* top; };
3. Initialize Stack:
Create a function to initialize the stack:
Function initStack(stack):
stack.top = NULL
4. Push Operation:
Create a function to push an element onto the stack:
Function push(stack, value):
newNode = createNode(value)
newNode.next = stack.top
stack.top = newNode
5. Pop Operation:
Create a function to pop an element from the stack:
Function pop(stack):
if stack.top is NULL:
Print "Stack Underflow"
return NULL
value = stack.top.data
temp = stack.top
stack.top = stack.top.next
free(temp)
return value
6. Traverse Operation:
Create a function to traverse the stack:
Function traverse(stack):
current = stack.top
while current is not NULL:
Print current.data
current = current.next

Queue Implementation Using Linked List


1. Node Structure:
Define a structure for the node:
struct Node { int data; struct Node* next; };
2. Queue Structure:
Define a structure for the queue:
struct Queue { struct Node* front; struct Node* rear; };
3. Initialize Queue:

54
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Create a function to initialize the queue:


Function initQueue(queue):
queue.front = NULL
queue.rear = NULL
4. Enqueue Operation:
Create a function to enqueue an element into the queue:
Function enqueue(queue, value):
newNode = createNode(value)
if queue.rear is NULL:
queue.front = newNode
queue.rear = newNode
else:
queue.rear.next = newNode
queue.rear = newNode
5. Dequeue Operation:
Create a function to dequeue an element from the queue:
Function dequeue(queue):
if queue.front is NULL:
Print "Queue Underflow"
return NULL
value = queue.front.data
temp = queue.front
queue.front = queue.front.next
if queue.front is NULL:
queue.rear = NULL
free(temp)
return value
6. Traverse Operation:
Create a function to traverse the queue:
Function traverse(queue):
current = queue.front
while current is not NULL:
Print current.data
current = current.next

Pseudocode:
Stack implementation using Linked List:
// Node structure
struct Node {
int data
Node* next
}

// Stack structure
struct Stack {
Node* top
}

// Function to initialize the stack


55
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Function initStack(Stack stack):


stack.top = NULL

// Function to create a new node


Function createNode(int value):
Node* newNode = new Node
newNode.data = value
newNode.next = NULL
return newNode

// Function to push an element onto the stack


Function push(Stack stack, int value):
Node* newNode = createNode(value)
newNode.next = stack.top
stack.top = newNode

// Function to pop an element from the stack


Function pop(Stack stack):
if stack.top is NULL:
Print "Stack Underflow"
return NULL
int value = stack.top.data
Node* temp = stack.top
stack.top = stack.top.next
free(temp)
return value

// Function to traverse the stack


Function traverseStack(Stack stack):
Node* current = stack.top
while current is not NULL:
Print current.data
current = current.next

Queue implementation using Linked List:


// Node structure
struct Node {
int data
Node* next
}

// Queue structure
struct Queue {
Node* front
Node* rear
}

// Function to initialize the queue


Function initQueue(Queue queue):
56
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

queue.front = NULL
queue.rear = NULL

// Function to create a new node


Function createNode(int value):
Node* newNode = new Node
newNode.data = value
newNode.next = NULL
return newNode

// Function to enqueue an element into the queue


Function enqueue(Queue queue, int value):
Node* newNode = createNode(value)
if queue.rear is NULL:
queue.front = newNode
queue.rear = newNode
else:
queue.rear.next = newNode
queue.rear = newNode

// Function to dequeue an element from the queue


Function dequeue(Queue queue):
if queue.front is NULL:
Print "Queue Underflow"
return NULL
int value = queue.front.data
Node* temp = queue.front
queue.front = queue.front.next
if queue.front is NULL:
queue.rear = NULL
free(temp)
return value

// Function to traverse the queue


Function traverseQueue(Queue queue):
Node* current = queue.front
while current is not NULL:
Print current.data
current = current.next

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

// Node structure for linked list


struct Node {
int data;
struct Node* next;
};
57
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Stack structure
struct Stack {
struct Node* top;
};

// Queue structure
struct Queue {
struct Node* front;
struct Node* rear;
};

// Function to create a new node


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

// Stack Functions

// Function to initialize the stack


void initStack(struct Stack* stack) {
stack->top = NULL;
}

// Function to push an element onto the stack


void push(struct Stack* stack, int value) {
struct Node* newNode = createNode(value);
newNode->next = stack->top;
stack->top = newNode;
}

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (stack->top == NULL) {
printf("Stack Underflow\n");
return -1; // Indicate underflow
}
int value = stack->top->data;
struct Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
return value;
}

// Function to traverse the stack


void traverseStack(struct Stack* stack) {
58
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

struct Node* current = stack->top;


printf("Stack: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

// Queue Functions

// Function to initialize the queue


void initQueue(struct Queue* queue) {
queue->front = NULL;
queue->rear = NULL;
}

// Function to enqueue an element into the queue


void enqueue(struct Queue* queue, int value) {
struct Node* newNode = createNode(value);
if (queue->rear == NULL) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}

// Function to dequeue an element from the queue


int dequeue(struct Queue* queue) {
if (queue->front == NULL) {
printf("Queue Underflow\n");
return -1; // Indicate underflow
}
int value = queue->front->data;
struct Node* temp = queue->front;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
return value;
}

// Function to traverse the queue


void traverseQueue(struct Queue* queue) {
struct Node* current = queue->front;
printf("Queue: ");
59
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

while (current != NULL) {


printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

// Main function to demonstrate stack and queue operations


int main() {
struct Stack stack;
struct Queue queue;

// Stack operations
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
traverseStack(&stack);
printf("Popped from stack: %d\n", pop(&stack));
traverseStack(&stack);

// Queue operations
initQueue(&queue);
enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
traverseQueue(&queue);
printf("Dequeued from queue: %d\n", dequeue(&queue));
traverseQueue(&queue);

printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:


B");

return 0;
}

Output:

60
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

61
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 10

Aim  Write a program in C to convert infix to postfix expression using stacks.

Algorithm:
1. Initialize:
Create an empty stack for operators.
Create an empty list for the output (postfix expression).
2. Read the Infix Expression:
Read the infix expression from left to right.
3. Process Each Token:
For each token in the infix expression:
If the token is an operand (e.g., A, B, 1, 2):
Add it to the output list.
If the token is an operator (e.g., +, -, *, /):
While there is an operator at the top of the stack with greater than
or equal precedence:
Pop operators from the stack to the output list.
Push the current operator onto the stack.
If the token is a left parenthesis (:
Push it onto the stack.
If the token is a right parenthesis ):
While the top of the stack is not a left parenthesis:
Pop operators from the stack to the output list.
Pop the left parenthesis from the stack (but do not add it to the
output list).
4. End of Expression:
After reading all tokens, pop all operators from the stack to the output list.
5. Output:
The output list now contains the postfix expression.

Pseudocode:
function infixToPostfix(infix):
stack = empty stack
output = empty list

for each token in infix:


if token is operand:
output.append(token)
else if token is operator:
while stack is not empty and precedence(stack.top) >= precedence(token):
output.append(stack.pop())
stack.push(token)
else if token is '(':
stack.push(token)
else if token is ')':
while stack is not empty and stack.top is not '(':
output.append(stack.pop())

62
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

stack.pop() // Pop the '(' from the stack

while stack is not empty:


output.append(stack.pop())

return output

Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX 100

// Stack structure
struct Stack {
int top;
char items[MAX];
};

// Function to create a stack


void initStack(struct Stack* s) {
s->top = -1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* s) {
return s->top == -1;
}

// Function to push an item onto the stack


void push(struct Stack* s, char item) {
if (s->top < MAX - 1) {
s->items[++(s->top)] = item;
} else {
printf("Stack Overflow\n");
}
}

// Function to pop an item from the stack


char pop(struct Stack* s) {
if (!isEmpty(s)) {
return s->items[(s->top)--];
} else {
printf("Stack Underflow\n");
return '\0'; // Return null character on underflow
}
}
63
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Function to get the top item of the stack


char peek(struct Stack* s) {
if (!isEmpty(s)) {
return s->items[s->top];
} else {
return '\0'; // Return null character if stack is empty
}
}

// Function to check operator precedence


int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0; // For non-operators
}
}

// Function to convert infix to postfix


void infixToPostfix(char* infix, char* postfix) {
struct Stack s;
initStack(&s);
int j = 0; // Index for postfix expression

for (int i = 0; infix[i] != '\0'; i++) {


char token = infix[i];

// If the token is an operand, add it to the output


if (isalnum(token)) {
postfix[j++] = token;
}
// If the token is '(', push it onto the stack
else if (token == '(') {
push(&s, token);
}
// If the token is ')', pop from the stack to the output until '(' is found
else if (token == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
pop(&s); // Pop the '(' from the stack
}
// If the token is an operator
else {
while (!isEmpty(&s) && precedence(peek(&s)) >= precedence(token)) {
postfix[j++] = pop(&s);
64
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

}
push(&s, token);
}
}

// Pop all the operators from the stack


while (!isEmpty(&s)) {
postfix[j++] = pop(&s);
}

postfix[j] = '\0'; // Null-terminate the postfix expression


}

// Main function to demonstrate the conversion


int main() {
char infix[MAX], postfix[MAX];

printf("Enter an infix expression: ");


fgets(infix, MAX, stdin);
infix[strcspn(infix, "\n")] = 0; // Remove newline character

infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);

printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:


B");

return 0;
}

Output:

65
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

Program 11

Aim  Write a program in C to evaluate a postfix expression using stacks.

Algorithm:
1. Initialize:
Create an empty stack for operands.
2. Read the Postfix Expression:
Read the postfix expression from left to right.
3. Process Each Token:
For each token in the postfix expression:
If the token is an operand (e.g., a number):
Push it onto the stack.
If the token is an operator (e.g., +, -, *, /):
Pop the top two operands from the stack.
Apply the operator to these operands:
For addition (+): operand1 + operand2
For subtraction (-): operand1 - operand2
For multiplication (*): operand1 * operand2
For division (/): operand1 / operand2
Push the result back onto the stack.
4. End of Expression:
After reading all tokens, the final result will be the only item left in the stack.
5. Output:
The value remaining in the stack is the result of the postfix expression.

Pseudocode:
function evaluatePostfix(postfix):
stack = empty stack

for each token in postfix:


if token is operand:
stack.push(token)
else if token is operator:
operand2 = stack.pop()
operand1 = stack.pop()
result = applyOperator(operand1, operand2, token)
stack.push(result)

return stack.pop() // The final result

Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX 100

66
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

// Stack structure
struct Stack {
int top;
int items[MAX];
};

// Function to create a stack


void initStack(struct Stack* s) {
s->top = -1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* s) {
return s->top == -1;
}

// Function to push an item onto the stack


void push(struct Stack* s, int item) {
if (s->top < MAX - 1) {
s->items[++(s->top)] = item;
} else {
printf("Stack Overflow\n");
}
}

// Function to pop an item from the stack


int pop(struct Stack* s) {
if (!isEmpty(s)) {
return s->items[(s->top)--];
} else {
printf("Stack Underflow\n");
return -1; // Return -1 on underflow
}
}

// Function to evaluate the postfix expression


int evaluatePostfix(char* postfix) {
struct Stack s;
initStack(&s);
char* token = strtok(postfix, " "); // Tokenize the input by spaces

while (token != NULL) {


// If the token is a number, push it onto the stack
if (isdigit(token[0])) {
push(&s, atoi(token)); // Convert string to integer
}
// If the token is an operator
else {
67
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

int operand2 = pop(&s);


int operand1 = pop(&s);
int result;

switch (token[0]) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
printf("Error: Division by zero\n");
return -1; // Return -1 for division by zero
}
break;
default:
printf("Invalid operator: %s\n", token);
return -1; // Return -1 for invalid operator
}
push(&s, result);
}
token = strtok(NULL, " "); // Get the next token
}

return pop(&s); // The final result


}

// Main function to demonstrate the evaluation


int main() {
char postfix[MAX];

printf("Enter a postfix expression: ");


fgets(postfix, MAX, stdin);
postfix[strcspn(postfix, "\n")] = 0; // Remove newline character

int result = evaluatePostfix(postfix);


if (result != -1) {
printf("Result: %d\n", result);
}
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");

68
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta

return 0;
}

Output:

69
Reg. No. – 11023210098
Section – “B”

You might also like