DSA Lab Manual Program 1 to 11
DSA Lab Manual Program 1 to 11
Program 1
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
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
1
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
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
return B
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
Pseudocode:
function sparseMatrixRepresentation(A):
m = number of rows in A
n = number of columns in A
sparseList = new list
Code:
#include <stdio.h>
#include <stdlib.h>
// 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;
// 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);
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");
}
return 0;
}
4
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
}
}
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
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
Pseudocode:
function binarySearch(array, target):
low = 0
high = length(array) - 1
9
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
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;
int arr[size];
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;
default:
printf("Invalid choice\n");
break;
}
printf("Program written by Aayush Mehta\nRegistration Number: 11023210098\nSection:
B");
return 0;
}
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])
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])
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;
int arr[size];
switch (choice) {
case 1: // Bubble Sort
bubbleSort(arr, size);
15
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
default:
printf("Invalid choice\n");
break;
}
return 0;
}
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
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
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
Pseudocode:
function mergeSort(array):
if length(array) > 1:
mid = length(array) / 2
leftHalf = array[0..mid]
rightHalf = array[mid..end]
i=j=k=0
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;
int arr[size];
switch (choice) {
case 1: // Quick Sort
quickSort(arr, 0, size - 1);
printf("Sorted array using Quick Sort:\n");
printArray(arr, size);
break;
default:
printf("Invalid choice\n");
break;
}
21
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
return 0;
}
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
Code:
#include <stdio.h>
#include <stdlib.h>
// 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
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
return 0;
}
if (current == NULL) {
printf("Position out of bounds!\n");
free(newNode);
return;
}
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
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);
}
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.
Pseudocode:
struct Node {
int data;
36
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
struct DoublyLinkedList {
Node* head;
};
Code:
#include <stdio.h>
#include <stdlib.h>
// 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
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;
}
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;
}
42
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
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 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
Code:
#include <stdio.h>
#include <stdlib.h>
}
}
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 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
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>
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
54
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
Pseudocode:
Stack implementation using Linked List:
// Node structure
struct Node {
int data
Node* next
}
// Stack structure
struct Stack {
Node* top
}
// Queue structure
struct Queue {
Node* front
Node* rear
}
queue.front = NULL
queue.rear = NULL
Code:
#include <stdio.h>
#include <stdlib.h>
// Stack structure
struct Stack {
struct Node* top;
};
// Queue structure
struct Queue {
struct Node* front;
struct Node* rear;
};
// Stack Functions
// Queue Functions
// 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);
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
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
62
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
return output
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
// Stack structure
struct Stack {
int top;
char items[MAX];
};
}
push(&s, token);
}
}
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
Output:
65
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
Program 11
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
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
66
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
// Stack structure
struct Stack {
int top;
int items[MAX];
};
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
}
68
Reg. No. – 11023210098
Section – “B”
03rd Sept 2024 Aayush Mehta
return 0;
}
Output:
69
Reg. No. – 11023210098
Section – “B”