0% found this document useful (0 votes)
56 views34 pages

Safal Dsa

Here is a program to print the elements of a linked list: #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printList(struct Node* node) { while (node != NULL) { printf("Element: %d\n", node->data); node = node->next; } } int main() { struct Node* head = NULL; struct Node* first = (struct Node*) malloc(sizeof(struct Node)); first->data = 1; first->next = NULL; head = first; struct Node* second =

Uploaded by

mallmridul3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views34 pages

Safal Dsa

Here is a program to print the elements of a linked list: #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printList(struct Node* node) { while (node != NULL) { printf("Element: %d\n", node->data); node = node->next; } } int main() { struct Node* head = NULL; struct Node* first = (struct Node*) malloc(sizeof(struct Node)); first->data = 1; first->next = NULL; head = first; struct Node* second =

Uploaded by

mallmridul3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

1|Page Data Structure And Algorithm using C

E1. Write a program to find the mean and the median of the numbers stored
in an array

Syntax:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
float calculate_mean(int arr[], int size) {
float sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
float calculate_median(int arr[], int size) {
float median;
int temp;
// Sort the array first
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Calculate median
if (size % 2 == 0)
median = (arr[size / 2 - 1] + arr[size / 2]) / 2.0;
else
median = arr[size / 2];
return median;
}
int main() {
int numbers[SIZE] = {5, 3, 1, 9, 7, 2, 8, 4, 6, 0};
float mean, median;
mean = calculate_mean(numbers, SIZE);
median = calculate_median(numbers, SIZE);
printf("Mean = %.2f\n", mean);
printf("Median = %.2f\n", median);
return 0;
}
Output:

Mean = 4.50

Median = 4.50

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
2|Page Data Structure And Algorithm using C

E2. Write a program to insert one element in an array and delete an


element from an- array.
Syntax:
#include <stdio.h>
#define MAX_SIZE 100
void insertElement(int arr[], int *size, int element, int position) {
if (*size >= MAX_SIZE) {
printf("Array is full, insertion failed.\n");
return;
}
if (position < 0 || position > *size) {
printf("Invalid position for insertion.\n");
return;
}
// Shift elements to the right to make space for the new element
for (int i = *size; i > position; i--) {
arr[i] = arr[i - 1];
}
// Insert the new element
arr[position] = element;
(*size)++;
}
void deleteElement(int arr[], int *size, int position) {
if (*size <= 0) {
printf("Array is empty, deletion failed.\n");
return;
}
if (position < 0 || position >= *size) {
printf("Invalid position for deletion.\n");
return;
}
// Shift elements to the left to fill the gap
for (int i = position; i < *size - 1; i++) {
arr[i] = arr[i + 1];
}
(*size)--;
}
void displayArray(int arr[], int size) {
printf("Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[MAX_SIZE] = {1, 2, 3, 4, 5};
int size = 5;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
3|Page Data Structure And Algorithm using C

// Insert an element at position 2


insertElement(arr, &size, 10, 2);
displayArray(arr, size);

// Delete element at position 3


deleteElement(arr, &size, 3);
displayArray(arr, size);
return 0;
}

Output:

Array: 1 2 10 3 4 5

Array: 1 2 10 4 5

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
4|Page Data Structure And Algorithm using C

E3. Write a program to Linear & Binary search for a number in an array.
Syntax:
#include <stdio.h>
int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i; // Return the index where the key is found
}
}
return -1; // Return -1 if key is not found
}
int binarySearch(int arr[], int size, int key) {
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
return mid; // Return the index where the key is found
} else if (arr[mid] < key) {
low = mid + 1; // Search the right half
} else {
high = mid - 1; // Search the left half
}
}
return -1; // Return -1 if key is not found
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int size = sizeof(arr) / sizeof(arr[0]);
int key = 13;
int linearIndex = linearSearch(arr, size, key);
if (linearIndex != -1) {
printf("Linear search: Key %d found at index %d\n", key,
linearIndex);
} else {
printf("Linear search: Key %d not found\n", key);
}
int binaryIndex = binarySearch(arr, size, key);
if (binaryIndex != -1) {
printf("Binary search: Key %d found at index %d\n", key,
binaryIndex);
} else {
printf("Binary search: Key %d not found\n", key);
}

return 0;
}

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
5|Page Data Structure And Algorithm using C

Output:
Linear search: Key 13 found at index 6
Binary search: Key 13 found at index 6

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
6|Page Data Structure And Algorithm using C

E4. Write a program to store the marks obtained by 10 students in 5 courses in


a two-dimensional array.
Syntax:

#include <stdio.h>

#define STUDENTS 10

#define COURSES 5

int main() {

int marks[STUDENTS][COURSES];

// Input marks for each student and course

printf("Enter marks for %d students in %d courses:\n", STUDENTS, COURSES);

for (int i = 0; i < STUDENTS; i++) {

printf("Enter marks for student %d:\n", i + 1);

for (int j = 0; j < COURSES; j++) {

printf("Enter marks for course %d: ", j + 1);

scanf("%d", &marks[i][j]);

// Display the marks for each student

printf("\nMarks for %d students in %d courses:\n", STUDENTS, COURSES);

for (int i = 0; i < STUDENTS; i++) {

printf("Student %d: ", i + 1);

for (int j = 0; j < COURSES; j++) {

printf("%d ", marks[i][j]);

printf("\n");

return 0;

}Output:

Enter marks for 10 students in 5 courses:

Enter marks for student 1:

Enter marks for course 1: 80

Enter marks for course 2: 75

Enter marks for course 3: 85

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
7|Page Data Structure And Algorithm using C

Enter marks for course 4: 90

Enter marks for course 5: 88

...

Marks for 10 students in 5 courses:

Student 1: 80 75 85 90 88

Student 2: ...

...

Student 10: ...

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
8|Page Data Structure And Algorithm using C

E5. Write a program to implement single linked list, including insertion,


deletion and searching
in the linked list.
Syntax:

#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};
// Function to insert a new node at the beginning of the linked list
void insertAtBeginning(struct Node** head, int newData) {
// Allocate memory for new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Check if memory allocation was successful
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
// Assign data to the new node
newNode->data = newData;
// Link the new node to the current head
newNode->next = *head;
// Update the head to point to the new node
*head = newNode;
}
// Function to delete a node with given key from the linked list
void deleteNode(struct Node** head, int key) {
// Initialize pointers for traversal and previous node
struct Node* temp = *head;
struct Node* prev = NULL;
// If the key is found at the head

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
9|Page Data Structure And Algorithm using C

if (temp != NULL && temp->data == key) {


*head = temp->next;
free(temp); // Free memory of the node to be deleted
return;
}
// Traverse the list to find the key
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If key is not present in the list
if (temp == NULL) {
printf("Key not found in the list\n");
return;
}
// Unlink the node containing the key from the linked list
prev->next = temp->next;
free(temp); // Free memory of the node to be deleted
}
// Function to display the linked list
void displayList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
// Initialize an empty linked list
struct Node* head = NULL;
// Insert some elements at the beginning of the list
insertAtBeginning(&head, 10);

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
10 | P a g e Data Structure And Algorithm using C

insertAtBeginning(&head, 20);
insertAtBeginning(&head, 30);
// Display the list
printf("Initial linked list: ");
displayList(head);
// Delete a node with key 20 from the list
deleteNode(&head, 20);
// Display the updated list
printf("Updated linked list: ");
displayList(head);
return 0;
}

Output:
Ini al linked list: 30 -> 20 -> 10 -> NULL
Updated linked list: 30 -> 10 -> NULL

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
11 | P a g e Data Structure And Algorithm using C

E6. Write a program to print the elements of a linked list in reverse order without
disturbing the linked list.
Syntax:
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the linked list
struct Node {
int data;
struct Node* next;

};
// Function to insert a new node at the beginning of the linked list
void insertAtBeginning(struct Node** head, int newData) {
// Allocate memory for new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Check if memory allocation was successful
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
// Assign data to the new node
newNode->data = newData;
// Link the new node to the current head
newNode->next = *head;
// Update the head to point to the new node
*head = newNode;
}
// Function to print elements of the linked list in reverse order
void printReverse(struct Node* head) {
if (head == NULL) // Base case: empty list

return;
printReverse(head->next); // Recursively call printReverse for the
next node
printf("%d -> ", head->data); // Print the data of the current node

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
12 | P a g e Data Structure And Algorithm using C

}
int main() {
// Initialize an empty linked list
struct Node* head = NULL;
// Insert some elements at the beginning of the list
insertAtBeginning(&head, 10);
insertAtBeginning(&head, 20);
insertAtBeginning(&head, 30);
// Display the original list
printf("Original linked list: ");
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
// Print the list in reverse order
printf("Reversed linked list: ");
printReverse(head);
printf("NULL\n");
return 0;
}

Output:

Original linked list: 30 -> 20 -> 10 -> NULL

Reversed linked list: 10 -> 20 -> 30 -> NULL

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
13 | P a g e Data Structure And Algorithm using C

E7. Write a program to implement bubble sort.

Syntax:
#include <stdio.h>
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;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubbleSort(arr, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
14 | P a g e Data Structure And Algorithm using C

Output:-
Original array: 64 34 25 12 22 11 90

Sorted array: 11 12 22 25 34 64 90

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
15 | P a g e Data Structure And Algorithm using C

E8. Write a program to add two polynomials using linked lists.


Syntax:
#include <stdio.h>

#include <stdlib.h>

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


polynomial

struct Node {

int coefficient;

int exponent;

struct Node* next;

};

// Function to insert a term into the polynomial

void insertTerm(struct Node** poly, int coefficient, int exponent) {

// Allocate memory for new node

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (newNode == NULL) {

printf("Memory allocation failed\n");

return;

// Assign data to the new node

newNode->coefficient = coefficient;

newNode->exponent = exponent;

newNode->next = NULL;

// If polynomial is empty, make newNode as the head

if (*poly == NULL) {

*poly = newNode;

} else {

// Traverse to the end of the polynomial

struct Node* temp = *poly;

while (temp->next != NULL) {

temp = temp->next;

// Link the new node to the end

temp->next = newNode;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
16 | P a g e Data Structure And Algorithm using C

// Function to add two polynomials

struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {

struct Node* result = NULL;

struct Node* temp1 = poly1;

struct Node* temp2 = poly2;

// Traverse both polynomials

while (temp1 != NULL && temp2 != NULL) {

if (temp1->exponent > temp2->exponent) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

} else if (temp1->exponent < temp2->exponent) {

insertTerm(&result, temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

} else {

// If exponents are equal, add coefficients and insert the sum

insertTerm(&result, temp1->coefficient + temp2->coefficient,


temp1->exponent);

temp1 = temp1->next;

temp2 = temp2->next;

// Add remaining terms of polynomial 1

while (temp1 != NULL) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

// Add remaining terms of polynomial 2

while (temp2 != NULL) {

insertTerm(&result, temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
17 | P a g e Data Structure And Algorithm using C

return result;

// Function to display polynomial

void displayPolynomial(struct Node* poly) {

while (poly != NULL) {

printf("%dx^%d ", poly->coefficient, poly->exponent);

if (poly->next != NULL) {

printf("+ ");

poly = poly->next;

printf("\n");

int main() {

// Initialize polynomial 1: 3x^2 + 2x^1 + 1x^0

struct Node* poly1 = NULL;

insertTerm(&poly1, 3, 2);

insertTerm(&poly1, 2, 1);

insertTerm(&poly1, 1, 0);

printf("Polynomial 1: ");

displayPolynomial(poly1);

// Initialize polynomial 2: 4x^3 + 2x^1 + 1x^0

struct Node* poly2 = NULL;

insertTerm(&poly2, 4, 3);

insertTerm(&poly2, 2, 1);

insertTerm(&poly2, 1, 0);

printf("Polynomial 2: ");

displayPolynomial(poly2);

// Add polynomials

struct Node* result = addPolynomials(poly1, poly2);

printf("Resultant Polynomial: ");

displayPolynomial(result)

return 0;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
18 | P a g e Data Structure And Algorithm using C

Output:

Polynomial 1: 3x^2 + 2x^1 + 1x^0

Polynomial 2: 4x^3 + 2x^1 + 1x^0

Resultant Polynomial: 4x^3 + 3x^2 + 4x^1 + 2x^0

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
19 | P a g e Data Structure And Algorithm using C

E9.Write a program to implement a doubly linked list including insertion,


deletion and searching in the linked list.

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

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


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

// Function to create a new node


struct Node* createNode(int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
newNode->data = newData;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

// Function to insert a new node at the beginning of the list


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

// Function to delete a node with given key from the list


void deleteNode(struct Node** head, int key) {
if (*head == NULL) {
printf("List is empty, deletion failed\n");
return;
}
struct Node* temp = *head;
// If the key is found at the head
if (temp->data == key) {
*head = temp->next;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
20 | P a g e Data Structure And Algorithm using C

if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
return;
}
// Traverse the list to find the key
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) {
printf("Key not found in the list\n");
return;
}
// If key is found, unlink the node from the list
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
}

// Function to search for a node with given key in the list


struct Node* searchNode(struct Node* head, int key) {
while (head != NULL && head->data != key) {
head = head->next;
}
return head;
}

// Function to display the list in forward direction


void displayForward(struct Node* head) {
printf("List (Forward): ");
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}

// Function to display the list in reverse direction


void displayBackward(struct Node* head) {
printf("List (Backward): ");
while (head->next != NULL) {
head = head->next;
}

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
21 | P a g e Data Structure And Algorithm using C

while (head != NULL) {


printf("%d -> ", head->data);
head = head->prev;
}
printf("NULL\n");
}

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

// Insert some elements at the beginning of the list


insertAtBeginning(&head, 10);
insertAtBeginning(&head, 20);
insertAtBeginning(&head, 30);

// Display the list in forward and backward directions


displayForward(head);
displayBackward(head);

// Search for a node with key 20


int key = 20;
struct Node* searchResult = searchNode(head, key);
if (searchResult != NULL) {
printf("Node with key %d found\n", key);
} else {
printf("Node with key %d not found\n", key);
}

// Delete a node with key 20


deleteNode(&head, 20);
displayForward(head);

return 0;
}

Output:

List (Forward): 30 -> 20 -> 10 -> NULL


List (Backward): 10 -> 20 -> 30 -> NULL
Node with key 20 found
List (Forward): 30 -> 10 -> NULL

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
22 | P a g e Data Structure And Algorithm using C

E10. Write a program to implement a stack opera on Push, Pop using an array and linked
list

Syntax:

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

#define MAX_SIZE 100

// Define a structure for stack


struct ArrayStack {
int top;
int capacity;
int* array;
};

// Function to create a stack


struct ArrayStack* createArrayStack(int capacity) {
struct ArrayStack* stack = (struct ArrayStack*)malloc(sizeof(struct
ArrayStack));
if (stack == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
if (stack->array == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return stack;
}

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
23 | P a g e Data Structure And Algorithm using C

// Function to check if the stack is full


int isFull(struct ArrayStack* stack) {
return stack->top == stack->capacity - 1;
}

// Function to check if the stack is empty


int isEmpty(struct ArrayStack* stack) {
return stack->top == -1;
}

// Function to push an element onto the stack


void push(struct ArrayStack* stack, int item) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}

// Function to pop an element from the stack


int pop(struct ArrayStack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
return stack->array[stack->top--];
}

int main() {
struct ArrayStack* stack = createArrayStack(MAX_SIZE);

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
24 | P a g e Data Structure And Algorithm using C

// Push elements onto the stack


push(stack, 10);
push(stack, 20);
push(stack, 30);

// Pop elements from the stack


printf("%d popped from stack\n", pop(stack));
printf("%d popped from stack\n", pop(stack));

// Push one more element onto the stack


push(stack, 40);

return 0;
}

Output:

10 pushed to stack

20 pushed to stack

30 pushed to stack

30 popped from stack

20 popped from stack

40 pushed to stack

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
25 | P a g e Data Structure And Algorithm using C

E11. Write a program to implement quick sort

Syntax:

#include <stdio.h>

// Function to swap two elements in an array


void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to partition the array and return the index of the pivot
element
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Select the last element as the pivot
int i = low - 1; // Index of the smaller element

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]); // Place the pivot element in its
correct position
return i + 1; // Return the index of the pivot element
}

// Function to implement quick sort


void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high); // Partition the array

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
26 | P a g e Data Structure And Algorithm using C

quickSort(arr, low, pi - 1); // Sort the left sub-array


quickSort(arr, pi + 1, high); // Sort the right sub-array
}
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


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

quickSort(arr, 0, n - 1);

printf("Sorted array: ");


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

return 0;
}

Output:

Original array: 10 7 8 9 1 5

Sorted array: 1 5 7 8 9 10

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
27 | P a g e Data Structure And Algorithm using C

E12. Write a program to implement a circular queue using an array


Syntax:

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

#define MAX_SIZE 5

// Define a structure for the circular queue


struct CircularQueue {
int* array;
int front;
int rear;
int size;
};

// Function to create a circular queue


struct CircularQueue* createCircularQueue() {
struct CircularQueue* queue = (struct
CircularQueue*)malloc(sizeof(struct CircularQueue));
if (queue == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
queue->array = (int*)malloc(MAX_SIZE * sizeof(int));
if (queue->array == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
queue->front = -1;
queue->rear = -1;
queue->size = 0;
return queue;

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
28 | P a g e Data Structure And Algorithm using C

// Function to check if the circular queue is empty


int isEmpty(struct CircularQueue* queue) {
return queue->size == 0;
}

// Function to check if the circular queue is full


int isFull(struct CircularQueue* queue) {
return queue->size == MAX_SIZE;
}

// Function to enqueue an element into the circular queue


void enqueue(struct CircularQueue* queue, int data) {
if (isFull(queue)) {
printf("Queue is full, cannot enqueue\n");
return;
}
if (isEmpty(queue)) {
queue->front = 0; // Set front to 0 if queue is empty
}
queue->rear = (queue->rear + 1) % MAX_SIZE; // Increment rear
circularly
queue->array[queue->rear] = data; // Insert data at rear
queue->size++;
printf("%d enqueued to the queue\n", data);
}

// Function to dequeue an element from the circular queue


int dequeue(struct CircularQueue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty, cannot dequeue\n");

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
29 | P a g e Data Structure And Algorithm using C

exit(EXIT_FAILURE);
}

int dequeued = queue->array[queue->front]; // Store the dequeued


element
if (queue->front == queue->rear) {
queue->front = -1;
queue->rear = -1; // Reset front and rear if queue becomes empty
after dequeue
} else {
queue->front = (queue->front + 1) % MAX_SIZE; // Increment front
circularly
}
queue->size--;
return dequeued;
}

int main() {
struct CircularQueue* queue = createCircularQueue();

// Enqueue elements into the circular queue


enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);

// Dequeue elements from the circular queue


printf("%d dequeued from the queue\n", dequeue(queue));
printf("%d dequeued from the queue\n", dequeue(queue));

// Enqueue one more element into the circular queue


enqueue(queue, 40);

return 0;
}

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
30 | P a g e Data Structure And Algorithm using C

Output:

10 enqueued to the queue

20 enqueued to the queue

30 enqueued to the queue

10 dequeued from the queue

20 dequeued from the queue

40 enqueued to the queue

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
31 | P a g e Data Structure And Algorithm using C

E13. Write a program that evaluate the given pos ix expression

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

// Define a structure for stack


struct Stack {
int top;
int capacity;
int* array;
};

// Function to create a stack


struct Stack* createStack(int capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
if (stack == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
if (stack->array == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return stack;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* stack) {

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
32 | P a g e Data Structure And Algorithm using C

return stack->top == -1;


}

// Function to push an element onto the stack


void push(struct Stack* stack, int item) {
if (stack->top == stack->capacity - 1) {
printf("Stack Overflow\n");
return;
}
stack->array[++stack->top] = item;
}

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
return stack->array[stack->top--];
}

// Function to evaluate a postfix expression


int evaluatePostfix(char* exp) {
struct Stack* stack = createStack(strlen(exp));
int i;

for (i = 0; exp[i]; ++i) {


if (isdigit(exp[i])) {
push(stack, exp[i] - '0');
} else {
int val1 = pop(stack);
int val2 = pop(stack);

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas
33 | P a g e Data Structure And Algorithm using C

switch (exp[i]) {
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2 / val1); break;
}
}
}
return pop(stack);
}

int main() {
char exp[] = "231*+9-"; // Postfix expression: 2 + (3 * 1) - 9
printf("Postfix expression: %s\n", exp);
printf("Result: %d\n", evaluatePostfix(exp));
return 0;
}

Output:

Pos ix expression: 231*+9-

Result: 2

Submi ed by:- Safal Malhotra(3rd Sem) Submi ed to:- Rishi Raj Vyas

You might also like