0% found this document useful (0 votes)
30 views51 pages

Tanvir Ahmed - Cse - Pca1-2-52

The document provides code examples for basic data structures in C, specifically arrays and linked lists. It includes programs for inserting and deleting elements in an array, performing linear and binary searches, rearranging arrays, and implementing a singly linked list with various operations. Each section contains code snippets along with explanations for user interaction and functionality.

Uploaded by

subho0573
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)
30 views51 pages

Tanvir Ahmed - Cse - Pca1-2-52

The document provides code examples for basic data structures in C, specifically arrays and linked lists. It includes programs for inserting and deleting elements in an array, performing linear and binary searches, rearranging arrays, and implementing a singly linked list with various operations. Each section contains code snippets along with explanations for user interaction and functionality.

Uploaded by

subho0573
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

Module 1: Basic Data Structures

Array:
1. Write a program to insert an element at a specific position in an array.

#include <stdio.h>

int main() {
int arr[100], n, element, position;

// Input: size of array


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

// Input: elements of the array


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

// Input: element to be inserted and position


printf("Enter the element to insert: ");
scanf("%d", &element);
printf("Enter the position (1 to %d) where the element should be inserted: ",
n + 1);
scanf("%d", &position);

// Adjust position to match array indexing (0-based)


position--;

// Shift elements to the right to make space


for (int i = n; i > position; i--) {
arr[i] = arr[i - 1];
}

// Insert the new element


arr[position] = element;

// Increase array size


n++;

// Output: updated array


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

return 0;
}
2. Write a program to delete an element from an array at a given position.
#include <stdio.h>

int main() {
int arr[100], n, position;

// Input: size of array


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

// Input: elements of the array


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

// Input: position of the element to delete


printf("Enter the position (1 to %d) of the element to delete: ", n);
scanf("%d", &position);

// Validate position
if (position < 1 || position > n) {
printf("Invalid position!\n");
return 1;
}

// Adjust position to match array indexing (0-based)


position--;

// Shift elements to the left to overwrite the deleted element


for (int i = position; i < n - 1; i++) {
arr[i] = arr[i + 1];
}

// Decrease array size


n--;

// Output: updated array


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

return 0;
}

3. Implement linear search to find the index of an element in the array.


#include <stdio.h>

int main() {
int arr[100], n, element, found = 0;

// Input: size of array


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

// Input: elements of the array


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

// Input: element to search for


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

// Linear search
for (int i = 0; i < n; i++) {
if (arr[i] == element) {
printf("Element %d found at index %d (position %d).\n",
element, i, i + 1);
found = 1;
break;
}
}

// If element is not found


if (!found) {
printf("Element %d not found in the array.\n", element);
}

return 0;
}

4. Implement binary search to find an element in a sorted array.


#include <stdio.h>

int main() {
int arr[100], n, element, low, high, mid, found = 0;

// Input: size of array


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

// Input: sorted elements of the array


printf("Enter %d sorted elements in ascending order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input: element to search for


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

// Binary search
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;

if (arr[mid] == element) {
printf("Element %d found at index %d (position %d).\n", element, mid,
mid + 1);
found = 1;
break;
} else if (arr[mid] < element) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}

// If element is not found


if (!found) {
printf("Element %d not found in the array.\n", element);
}

return 0;
}

5. Rearrange an array such that all negative numbers appear before positive
numbers without changing their relative order.
#include <stdio.h>

void rearrangeArray(int arr[], int n) {


int temp[n], index = 0;

// Copy negative numbers to temp array


for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
temp[index++] = arr[i];
}
}

// Copy positive numbers to temp array


for (int i = 0; i < n; i++) {
if (arr[i] >= 0) {
temp[index++] = arr[i];
}
}

// Copy temp array back to the original array


for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}

int main() {
int arr[100], n;
// Input: size of array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

// Input: elements of the array


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

// Rearrange the array


rearrangeArray(arr, n);

// Output: rearranged array


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

return 0;
}
Linked List:
1. Write a program to implement a singly linked list with the following operations:
Insert at the beginning, Insert at the end, Delete from the beginning, Delete from the
end, Display the list.

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

// Define a node
struct Node {
int data;
struct Node* next;
};

// Function to insert at the beginning


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

// Function to insert at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
return;
}

struct Node* temp = *head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// Function to delete from the beginning


void deleteFromBeginning(struct Node** head) {
if (*head == NULL) {
printf("The list is empty. Nothing to delete.\n");
return;
}

struct Node* temp = *head;


*head = (*head)->next;
free(temp);
printf("Deleted from the beginning.\n");
}

// Function to delete from the end


void deleteFromEnd(struct Node** head) {
if (*head == NULL) {
printf("The list is empty. Nothing to delete.\n");
return;
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
printf("Deleted from the end.\n");
return;
}

struct Node* temp = *head;


while (temp->next->next != NULL) {
temp = temp->next;
}

free(temp->next);
temp->next = NULL;
printf("Deleted from the end.\n");
}

// Function to display the list


void displayList(struct Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("List elements: ");


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

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

// Display menu once


printf("Menu:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Delete from the beginning\n");
printf("4. Delete from the end\n");
printf("5. Display the list\n");
printf("6. Exit\n");

// Run operations based on user input


do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
deleteFromBeginning(&head);
break;
case 4:
deleteFromEnd(&head);
break;
case 5:
displayList(head);
break;
case 6:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 6);

return 0;
}
2. Write a program to search for an element in a singly linked list.
#include <stdio.h>
#include <stdlib.h>

// Define a node
struct Node {
int data;
struct Node* next;
};

// Function to insert at the beginning


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

// Function to insert at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
return;
}

struct Node* temp = *head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// Function to search for an element in the list


void searchElement(struct Node* head, int element) {
struct Node* temp = head;
int position = 1;
int found = 0;

while (temp != NULL) {


if (temp->data == element) {
printf("Element %d found at position %d.\n", element, position);
found = 1;
break;
}
temp = temp->next;
position++;
}

if (!found) {
printf("Element %d not found in the list.\n", element);
}
}

// Function to display the list


void displayList(struct Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("List elements: ");


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

int main() {
struct Node* head = NULL;
int choice, data, element;

// Display the menu once


printf("Menu:\n");
printf("1. Insert element at the beginning\n");
printf("2. Insert element at the end\n");
printf("3. Search for an element\n");
printf("4. Display the list\n");
printf("5. Exit\n");

// Loop for user input


do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter element to search for: ");
scanf("%d", &element);
searchElement(head, element);
break;
case 4:
displayList(head);
break;
case 5:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);

return 0;
}
3. Write a program to count the total number of nodes in a linked list.
#include <stdio.h>
#include <stdlib.h>

// Define a node
struct Node {
int data;
struct Node* next;
};

// Function to insert at the beginning


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

// Function to insert at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}

struct Node* temp = *head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// Function to count the number of nodes in the list


int countNodes(struct Node* head) {
int count = 0;
struct Node* temp = head;

while (temp != NULL) {


count++;
temp = temp->next;
}

return count;
}

// Function to display the list


void displayList(struct Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("List elements: ");


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

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

// Display the menu once


printf("Menu:\n");
printf("1. Insert element at the beginning\n");
printf("2. Insert element at the end\n");
printf("3. Display the list\n");
printf("4. Count the total number of nodes\n");
printf("5. Exit\n");

// Loop for user input


do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
displayList(head);
break;
case 4:
printf("Total number of nodes: %d\n", countNodes(head));
break;
case 5:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);

return 0;
}

4. Write a program to find the middle node of a singly linked list in one traversal.
#include <stdio.h>
#include <stdlib.h>

// Define a node
struct Node {
int data;
struct Node* next;
};

// Function to insert at the end


void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
return;
}

struct Node* temp = *head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// Function to find the middle node of the list


void findMiddle(struct Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

struct Node* slow = head;


struct Node* fast = head;

while (fast != NULL && fast->next != NULL) {


slow = slow->next;
fast = fast->next->next;
}

printf("The middle node is: %d\n", slow->data);


}

// Function to display the list


void displayList(struct Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("List elements: ");


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

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

// Menu for building and finding the middle of the list


printf("Menu:\n");
printf("1. Insert element at the end\n");
printf("2. Display the list\n");
printf("3. Find the middle node\n");
printf("4. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 2:
displayList(head);
break;
case 3:
findMiddle(head);
break;
case 4:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

return 0;
}
5. Write a program to find the intersection point of two linked lists.
#include <stdio.h>
#include <stdlib.h>

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

// 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 append a node to a linked list


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

// Function to display the linked list


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

// Function to find the intersection point based on data


struct Node* findIntersectionByData(struct Node* head1, struct Node* head2) {
struct Node* temp1 = head1;
struct Node* temp2;

// Check every node of the first list against every node of the second list
while (temp1 != NULL) {
temp2 = head2;
while (temp2 != NULL) {
if (temp1->data == temp2->data) {
return temp1; // Intersection found based on matching data
}
temp2 = temp2->next;
}
temp1 = temp1->next;
}
return NULL; // No intersection
}

int main() {
struct Node *head1 = NULL, *head2 = NULL;
int n1, n2, data, i;

printf("Enter the number of nodes in the first linked list: ");


scanf("%d", &n1);
printf("Enter the nodes for the first linked list:\n");
for (i = 0; i < n1; i++) {
scanf("%d", &data);
appendNode(&head1, data);
}

printf("Enter the number of nodes in the second linked list: ");


scanf("%d", &n2);
printf("Enter the nodes for the second linked list:\n");
for (i = 0; i < n2; i++) {
scanf("%d", &data);
appendNode(&head2, data);
}

printf("\nFirst Linked List: ");


displayList(head1);
printf("Second Linked List: ");
displayList(head2);

struct Node* intersection = findIntersectionByData(head1, head2);


if (intersection) {
printf("The intersection point is at node with data: %d\n", intersection-
>data);
} else {
printf("The two linked lists do not intersect.\n");
}

return 0;
}
6. Write a program to insert a node into a sorted doubly linked list.
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a doubly linked list node


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

// Function to create a new node


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

// Function to display the doubly linked list


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

// Function to insert a node into a sorted doubly linked list


void insertIntoSortedDLL(struct Node** head, int data) {
struct Node* newNode = createNode(data);

// If the list is empty


if (*head == NULL) {
*head = newNode;
return;
}

// If the new node needs to be inserted at the beginning


if (data <= (*head)->data) {
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
return;
}

// Traverse the list to find the correct position


struct Node* temp = *head;
while (temp->next != NULL && temp->next->data < data) {
temp = temp->next;
}

// Insert the new node in the correct position


newNode->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = newNode;
}
temp->next = newNode;
newNode->prev = temp;
}

int main() {
struct Node* head = NULL;
int n, data, i;

printf("Enter the number of elements in the sorted doubly linked list: ");
scanf("%d", &n);

printf("Enter the elements:\n");


for (i = 0; i < n; i++) {
scanf("%d", &data);
insertIntoSortedDLL(&head, data);
}

printf("\nOriginal Sorted List:\n");


displayList(head);

printf("\nEnter the value to be inserted: ");


scanf("%d", &data);

insertIntoSortedDLL(&head, data);

printf("\nUpdated List After Insertion:\n");


displayList(head);

return 0;
}
Stack Implementation:
1. Write a program to implement a stack using an array with the following
operations: Push, Pop, Peek/Top. Check if the stack is empty.

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

#define MAX_SIZE 100

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

void push(int item) {


if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = item;
printf("%d pushed to stack\n", item);
}

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

int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}

int isEmpty() {
return top == -1;
}

int main() {
char choice;
int item;

printf("Enter your choice:\n");


printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek/Top\n");
printf("4. Check if empty\n");
printf("5. Exit\n");

while (1) {
printf("\nEnter your choice: ");
scanf(" %c", &choice);
switch (choice) {
case '1':
printf("Enter the item to push: ");
scanf("%d", &item);
push(item);
break;
case '2':
item = pop();
if (item != -1) {
printf("Popped item: %d\n", item);
}
break;
case '3':
item = peek();
if (item != -1) {
printf("Top element: %d\n", item);
}
break;
case '4':
if (isEmpty()) {
printf("Stack is empty\n");
} else {
printf("Stack is not empty\n");
}
break;
case '5':
printf("Exiting Program\n");
exit(0);
default:
printf("Invalid choice\n");
}
}

return 0;
}
2. Write a program to reverse a string using a stack.

#include <stdio.h>
#include <string.h>
#define MAX 100 // Maximum size of the stack

typedef struct Stack {


char arr[MAX];
int top;
} Stack;

// Function to initialize the stack


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

// Function to check if the stack is full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Function to check if the stack is empty


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

// Function to push an element onto the stack


void push(Stack *s, char ch) {
if (isFull(s)) {
printf("Stack Overflow! Cannot push '%c'.\n", ch);
return;
}
s->arr[++(s->top)] = ch;
}

// Function to pop an element from the stack


char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow! No elements to pop.\n");
return '\0'; // Return null character to indicate an error
}
return s->arr[(s->top)--];
}

// Function to reverse a string using a stack


void reverseString(char *str) {
Stack s;
initialize(&s);

// Push all characters of the string onto the stack


for (int i = 0; str[i] != '\0'; i++) {
push(&s, str[i]);
}

// Pop all characters from the stack to reverse the string


for (int i = 0; !isEmpty(&s); i++) {
str[i] = pop(&s);
}
}

int main() {
char str[MAX];

printf("Enter a string: ");


fgets(str, MAX, stdin);

// Remove the newline character from fgets input if present


size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}

printf("Original string: %s\n", str);

reverseString(str);

printf("Reversed string: %s\n", str);

return 0;
}

3. Write a program to implement a stack using a linked list.

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

// Define a node for the linked list


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

// Function to push an element onto the stack


void push(Node** top, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Stack Overflow! Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = *top;
*top = newNode;
printf("Pushed %d onto the stack.\n", value);
}

// Function to pop an element from the stack


int pop(Node** top) {
if (*top == NULL) {
printf("Stack Underflow! No elements to pop.\n");
return -1; // Return -1 to indicate an error
}
Node* temp = *top;
int poppedValue = temp->data;
*top = temp->next;
free(temp);
return poppedValue;
}

// Function to peek at the top element of the stack


int peek(Node* top) {
if (top == NULL) {
printf("Stack is empty! No top element.\n");
return -1; // Return -1 to indicate an error
}
return top->data;
}

// Function to check if the stack is empty


int isEmpty(Node* top) {
return top == NULL;
}

// Function to display the stack elements


void display(Node* top) {
if (isEmpty(top)) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
while (top != NULL) {
printf("%d ", top->data);
top = top->next;
}
printf("\n");
}

int main() {
Node* stack = NULL; // Initialize the stack as empty

int choice, value;

// Display the menu once


printf("Stack Operations Menu:\n");
printf("1. Push\n2. Pop\n3. Peek/Top\n4. Check if Empty\n5. Display Stack\n6.
Exit\n");

while (1) {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to push: ");
scanf("%d", &value);
push(&stack, value);
break;
case 2:
value = pop(&stack);
if (value != -1)
printf("Popped value: %d\n", value);
break;
case 3:
value = peek(stack);
if (value != -1)
printf("Top value: %d\n", value);
break;
case 4:
if (isEmpty(stack))
printf("Stack is empty.\n");
else
printf("Stack is not empty.\n");
break;
case 5:
display(stack);
break;
case 6:
printf("Exiting program.\n");
// Free memory used by the stack
while (!isEmpty(stack)) {
pop(&stack);
}
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}
4. Write a program to evaluate a postfix expression using a stack.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100 // Maximum size of the stack

typedef struct Stack {


int arr[MAX];
int top;
} Stack;

// Function to initialize the stack


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

// Function to check if the stack is empty


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

// Function to check if the stack is full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Function to push an element onto the stack


void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack Overflow! Cannot push %d.\n", value);
return;
}
s->arr[++(s->top)] = value;
}

// Function to pop an element from the stack


int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow! No elements to pop.\n");
return -1; // Return -1 to indicate an error
}
return s->arr[(s->top)--];
}

// Function to evaluate a postfix expression


int evaluatePostfix(char *expression) {
Stack s;
initialize(&s);

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


if (isspace(expression[i])) {
continue; // Skip whitespace
}

// If the character is a digit, push it onto the stack


if (isdigit(expression[i])) {
int num = 0;
while (isdigit(expression[i])) {
num = num * 10 + (expression[i] - '0');
i++;
}
i--; // Adjust for the extra increment in the inner loop
push(&s, num);
}
// If the character is an operator, pop two operands and apply the
operation
else {
int b = pop(&s);
int a = pop(&s);

switch (expression[i]) {
case '+':
push(&s, a + b);
break;
case '-':
push(&s, a - b);
break;
case '*':
push(&s, a * b);
break;
case '/':
if (b == 0) {
printf("Division by zero error!\n");
return -1;
}
push(&s, a / b);
break;
default:
printf("Invalid operator: %c\n", expression[i]);
return -1;
}
}
}

// The final result is at the top of the stack


return pop(&s);
}

int main() {
char expression[MAX];

printf("Enter a postfix expression: ");


fgets(expression, MAX, stdin);

int result = evaluatePostfix(expression);

if (result != -1) {
printf("The result of the postfix expression is: %d\n", result);
}

return 0;
}
5. Write a program to convert an infix expression to postfix [eg, (a+b)*c to ab+c*].

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100 // Maximum size of the stack

// Define a stack structure for characters


typedef struct Stack {
char arr[MAX];
int top;
} Stack;

// Function to initialize the stack


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

// Function to check if the stack is empty


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

// Function to check if the stack is full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Function to push an element onto the stack


void push(Stack *s, char ch) {
if (isFull(s)) {
printf("Stack Overflow! Cannot push '%c'.\n", ch);
return;
}
s->arr[++(s->top)] = ch;
}

// Function to pop an element from the stack


char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow! No elements to pop.\n");
return '\0'; // Return null character to indicate an error
}
return s->arr[(s->top)--];
}

// Function to get the top element of the stack without popping


char peek(Stack *s) {
if (isEmpty(s)) {
return '\0';
}
return s->arr[s->top];
}

// Function to check if a character is an operator


int isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}

// Function to determine the precedence of operators


int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}

// Function to convert an infix expression to a postfix expression


void infixToPostfix(char *infix, char *postfix) {
Stack s;
initialize(&s);
int i = 0, j = 0;

while (infix[i] != '\0') {


// If the character is an operand, add it to the postfix expression
if (isalnum(infix[i])) {
postfix[j++] = infix[i];
}
// If the character is '(', push it onto the stack
else if (infix[i] == '(') {
push(&s, infix[i]);
}
// If the character is ')', pop and add to postfix until '(' is encountered
else if (infix[i] == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
if (!isEmpty(&s) && peek(&s) == '(') {
pop(&s); // Pop the '('
}
}
// If the character is an operator
else if (isOperator(infix[i])) {
while (!isEmpty(&s) && precedence(peek(&s)) >= precedence(infix[i])) {
postfix[j++] = pop(&s);
}
push(&s, infix[i]);
}
i++;
}

// Pop all remaining operators from the stack


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

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


}

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

printf("Enter an infix expression: ");


fgets(infix, MAX, stdin);

// Remove newline character from input if present


size_t len = strlen(infix);
if (len > 0 && infix[len - 1] == '\n') {
infix[len - 1] = '\0';
}

infixToPostfix(infix, postfix);

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

return 0;
}

6. Write a program to check if a given string is a palindrome using a stack.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100 // Maximum size of the stack

typedef struct Stack {


char arr[MAX];
int top;
} Stack;

// Function to initialize the stack


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

// Function to check if the stack is empty


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

// Function to check if the stack is full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Function to push an element onto the stack


void push(Stack *s, char ch) {
if (isFull(s)) {
printf("Stack Overflow! Cannot push '%c'.\n", ch);
return;
}
s->arr[++(s->top)] = ch;
}

// Function to pop an element from the stack


char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow! No elements to pop.\n");
return '\0'; // Return null character to indicate an error
}
return s->arr[(s->top)--];
}

// Function to check if a string is a palindrome using a stack


int isPalindrome(char *str) {
Stack s;
initialize(&s);

int length = strlen(str);


int i;

// Push all characters of the string onto the stack


for (i = 0; i < length; i++) {
if (isalnum(str[i])) { // Consider only alphanumeric characters
push(&s, tolower(str[i]));
}
}

// Compare characters popped from the stack with the original string
for (i = 0; i < length; i++) {
if (isalnum(str[i])) { // Consider only alphanumeric characters
if (tolower(str[i]) != pop(&s)) {
return 0; // Not a palindrome
}
}
}

return 1; // String is a palindrome


}

int main() {
char str[MAX];
printf("Enter a string: ");
fgets(str, MAX, stdin);

// Remove the newline character from input if present


size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}

if (isPalindrome(str)) {
printf("The string \"%s\" is a palindrome.\n", str);
} else {
printf("The string \"%s\" is not a palindrome.\n", str);
}

return 0;
}
Queue Implementation:
1. Write a program to implement a queue using an array with the following
operations: Enqueue (insert an element), Dequeue (remove an element), Peek/Front
(view the front element), Check if the queue is empty.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

typedef struct Queue {


int arr[MAX];
int front;
int rear;
} Queue;

// Function to initialize the queue


void initializeQueue(Queue *q) {
q->front = -1;
q->rear = -1;
}

// Function to check if the queue is empty


int isEmpty(Queue *q) {
return (q->front == -1);
}

// Function to check if the queue is full


int isFull(Queue *q) {
return (q->rear == MAX - 1);
}

// Function to enqueue (insert) an element into the queue


void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (q->front == -1) { // First element
q->front = 0;
}
q->rear++;
q->arr[q->rear] = value;
printf("Enqueued %d\n", value);
}

// Function to dequeue (remove) an element from the queue


int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
int value = q->arr[q->front];
if (q->front == q->rear) { // Queue becomes empty
q->front = q->rear = -1;
} else {
q->front++;
}
printf("Dequeued %d\n", value);
return value;
}

// Function to view the front element


int peek(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Nothing to peek\n");
return -1;
}
return q->arr[q->front];
}

int main() {
Queue q;
initializeQueue(&q);

int choice, value;

printf("Queue Operations:\n");
printf("1. Enqueue (insert an element)\n");
printf("2. Dequeue (remove an element)\n");
printf("3. Peek/Front (view the front element)\n");
printf("4. Check if queue is empty\n");
printf("5. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
dequeue(&q);
break;
case 3:
value = peek(&q);
if (value != -1) {
printf("Front element is: %d\n", value);
}
break;
case 4:
if (isEmpty(&q)) {
printf("Queue is empty\n");
} else {
printf("Queue is not empty\n");
}
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 5);

return 0;
}
2. Write a program to implement a queue using a singly linked list.

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

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

// Queue structure
typedef struct Queue {
Node *front;
Node *rear;
int size; // To keep track of the size of the queue
} Queue;

// Function to initialize the queue


void initializeQueue(Queue *q) {
q->front = NULL;
q->rear = NULL;
q->size = 0;
}
// Function to check if the queue is empty
int isEmpty(Queue *q) {
return (q->front == NULL);
}

// Function to enqueue (insert) an element


void enqueue(Queue *q, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed! Cannot enqueue %d\n", value);
return;
}
newNode->data = value;
newNode->next = NULL;

if (q->rear == NULL) { // Queue is empty


q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
q->size++;
printf("Enqueued %d\n", value);
}

// Function to dequeue (remove) an element


int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
Node *temp = q->front;
int value = temp->data;
q->front = q->front->next;

if (q->front == NULL) { // Queue becomes empty


q->rear = NULL;
}

free(temp);
q->size--;
printf("Dequeued %d\n", value);
return value;
}

// Function to view the front element


int peek(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Nothing to peek\n");
return -1;
}
return q->front->data;
}

// Function to display the elements in the queue


void displayQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
Node *temp = q->front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Main function
int main() {
Queue q;
initializeQueue(&q);

int choice, value;

printf("Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek/Front\n");
printf("4. Check if queue is empty\n");
printf("5. Show the queue\n");
printf("6. Size of the queue\n");
printf("7. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
dequeue(&q);
break;
case 3:
value = peek(&q);
if (value != -1) {
printf("Front element is: %d\n", value);
}
break;
case 4:
if (isEmpty(&q)) {
printf("Queue is empty\n");
} else {
printf("Queue is not empty\n");
}
break;
case 5:
displayQueue(&q);
break;
case 6:
printf("Queue size: %d\n", q.size);
break;
case 7:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 7);
return 0;
}

3. Write a program to reverse a queue using:


A stack, Recursion, Circular Queue Using Array.

Using Stack:
#include <stdio.h>
#include <stdlib.h>

// Node structure for the queue


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

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

// Stack structure
typedef struct Stack {
int *arr;
int top;
int capacity;
} Stack;

// Function to initialize a queue


void initializeQueue(Queue *q) {
q->front = NULL;
q->rear = NULL;
}

// Function to check if the queue is empty


int isQueueEmpty(Queue *q) {
return (q->front == NULL);
}

// Function to enqueue an element into the queue


void enqueue(Queue *q, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed! Cannot enqueue %d\n", value);
return;
}
newNode->data = value;
newNode->next = NULL;

if (q->rear == NULL) { // Queue is empty


q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}

// Function to dequeue an element from the queue


int dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
Node *temp = q->front;
int value = temp->data;
q->front = q->front->next;

if (q->front == NULL) { // Queue becomes empty


q->rear = NULL;
}

free(temp);
return value;
}

// Function to display the elements of the queue


void displayQueue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
return;
}
Node *temp = q->front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to initialize a stack


void initializeStack(Stack *s, int capacity) {
s->arr = (int *)malloc(capacity * sizeof(int));
s->top = -1;
s->capacity = capacity;
}

// Function to check if the stack is empty


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

// Function to push an element onto the stack


void push(Stack *s, int value) {
if (s->top == s->capacity - 1) {
printf("Stack overflow! Cannot push %d\n", value);
return;
}
s->arr[++s->top] = value;
}

// Function to pop an element from the stack


int pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack underflow! Cannot pop\n");
return -1;
}
return s->arr[s->top--];
}

// Function to reverse the queue using a stack


void reverseQueue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot reverse\n");
return;
}

int size = 0;
Node *temp = q->front;
while (temp != NULL) {
size++;
temp = temp->next;
}

Stack s;
initializeStack(&s, size);

// Dequeue all elements from the queue and push them onto the stack
while (!isQueueEmpty(q)) {
push(&s, dequeue(q));
}

// Pop all elements from the stack and enqueue them back into the queue
while (!isStackEmpty(&s)) {
enqueue(q, pop(&s));
}
free(s.arr); // Free stack memory
}

// Main function
int main() {
Queue q;
initializeQueue(&q);

int choice, value;

printf("Enter elements to enqueue into the queue (-1 to stop):\n");


while (1) {
scanf("%d", &value);
if (value == -1) break;
enqueue(&q, value);
}

printf("\nOriginal queue:\n");
displayQueue(&q);

reverseQueue(&q);

printf("\nReversed queue:\n");
displayQueue(&q);

return 0;
}

Using Recursion:
#include <stdio.h>
#include <stdlib.h>

// Node structure for the queue


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

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

// Function to initialize a queue


void initializeQueue(Queue *q) {
q->front = NULL;
q->rear = NULL;
}

// Function to check if the queue is empty


int isQueueEmpty(Queue *q) {
return (q->front == NULL);
}

// Function to enqueue an element into the queue


void enqueue(Queue *q, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed! Cannot enqueue %d\n", value);
return;
}
newNode->data = value;
newNode->next = NULL;

if (q->rear == NULL) { // Queue is empty


q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}

// Function to dequeue an element from the queue


int dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
Node *temp = q->front;
int value = temp->data;
q->front = q->front->next;

if (q->front == NULL) { // Queue becomes empty


q->rear = NULL;
}

free(temp);
return value;
}

// Function to display the elements of the queue


void displayQueue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
return;
}
Node *temp = q->front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Recursive function to reverse the queue


void reverseQueue(Queue *q) {
if (isQueueEmpty(q)) {
return;
}

// Step 1: Dequeue the front element


int data = dequeue(q);

// Step 2: Recursively reverse the remaining queue


reverseQueue(q);

// Step 3: Enqueue the dequeued element back to the rear


enqueue(q, data);
}

// Main function
int main() {
Queue q;
initializeQueue(&q);

int value;

printf("Enter elements to enqueue into the queue (-1 to stop):\n");


while (1) {
scanf("%d", &value);
if (value == -1) break;
enqueue(&q, value);
}

printf("\nOriginal queue:\n");
displayQueue(&q);

reverseQueue(&q);

printf("\nReversed queue:\n");
displayQueue(&q);

return 0;
}

Circular Queue Using Array:


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

#define MAX 100 // Maximum size of the circular queue


// Circular Queue structure
typedef struct CircularQueue {
int arr[MAX];
int front;
int rear;
int size;
} CircularQueue;

// Function to initialize the circular queue


void initializeQueue(CircularQueue *q) {
q->front = -1;
q->rear = -1;
q->size = 0;
}

// Function to check if the circular queue is empty


int isQueueEmpty(CircularQueue *q) {
return (q->size == 0);
}

// Function to check if the circular queue is full


int isQueueFull(CircularQueue *q) {
return (q->size == MAX);
}

// Function to enqueue an element into the circular queue


void enqueue(CircularQueue *q, int value) {
if (isQueueFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (q->front == -1) { // First element
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->arr[q->rear] = value;
q->size++;
}

// Function to dequeue an element from the circular queue


int dequeue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
int value = q->arr[q->front];
q->front = (q->front + 1) % MAX;
q->size--;
if (q->size == 0) { // Reset queue when it becomes empty
q->front = -1;
q->rear = -1;
}
return value;
}
// Function to display the elements of the circular queue
void displayQueue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (int i = 0; i < q->size; i++) {
int index = (q->front + i) % MAX;
printf("%d ", q->arr[index]);
}
printf("\n");
}
// Function to reverse the circular queue
void reverseQueue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot reverse\n");
return;
}
int temp, start = q->front, end = q->rear;
for (int i = 0; i < q->size / 2; i++) {
temp = q->arr[start];
q->arr[start] = q->arr[end];
q->arr[end] = temp;

// Move start and end indices


start = (start + 1) % MAX;
end = (end - 1 + MAX) % MAX;
}
}
// Main function
int main() {
CircularQueue q;
initializeQueue(&q);

int value;

printf("Enter elements to enqueue into the queue (-1 to stop):\n");


while (1) {
scanf("%d", &value);
if (value == -1) break;
enqueue(&q, value);
}

printf("\nOriginal queue:\n");
displayQueue(&q);
reverseQueue(&q);
printf("\nReversed queue:\n");
displayQueue(&q);

return 0;
}
4. Implement a circular queue using an array with operations for enqueue, dequeue
and checking if the queue is full or empty.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum size of the circular queue

// Circular Queue structure


typedef struct CircularQueue {
int arr[MAX];
int front;
int rear;
int size;
} CircularQueue;

// Function to initialize the circular queue


void initializeQueue(CircularQueue *q) {
q->front = -1;
q->rear = -1;
q->size = 0;
}

// Function to check if the circular queue is empty


int isQueueEmpty(CircularQueue *q) {
return (q->size == 0);
}

// Function to check if the circular queue is full


int isQueueFull(CircularQueue *q) {
return (q->size == MAX);
}

// Function to enqueue an element into the circular queue


void enqueue(CircularQueue *q, int value) {
if (isQueueFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (q->front == -1) { // First element
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->arr[q->rear] = value;
q->size++;
printf("Enqueued %d\n", value);
}

// Function to dequeue an element from the circular queue


int dequeue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
int value = q->arr[q->front];
q->front = (q->front + 1) % MAX;
q->size--;
if (q->size == 0) { // Reset queue when it becomes empty
q->front = -1;
q->rear = -1;
}
printf("Dequeued %d\n", value);
return value;
}

// Function to display the elements of the circular queue


void displayQueue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (int i = 0; i < q->size; i++) {
int index = (q->front + i) % MAX;
printf("%d ", q->arr[index]);
}
printf("\n");
}

// Main function
int main() {
CircularQueue q;
initializeQueue(&q);

int choice, value;

printf("Circular Queue Operations:\n");


printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Check if the queue is empty\n");
printf("4. Check if the queue is full\n");
printf("5. Display the queue\n");
printf("6. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
dequeue(&q);
break;
case 3:
if (isQueueEmpty(&q)) {
printf("Queue is empty\n");
} else {
printf("Queue is not empty\n");
}
break;
case 4:
if (isQueueFull(&q)) {
printf("Queue is full\n");
} else {
printf("Queue is not full\n");
}
break;
case 5:
displayQueue(&q);
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 6);

return 0;
}

5. Write a program to calculate the size of a queue at any point in time.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum size of the circular queue

// Circular Queue structure


typedef struct CircularQueue {
int arr[MAX];
int front;
int rear;
} CircularQueue;

// Function to initialize the circular queue


void initializeQueue(CircularQueue *q) {
q->front = -1;
q->rear = -1;
}
// Function to check if the circular queue is empty
int isQueueEmpty(CircularQueue *q) {
return (q->front == -1);
}

// Function to check if the circular queue is full


int isQueueFull(CircularQueue *q) {
return ((q->rear + 1) % MAX == q->front);
}

// Function to enqueue an element into the circular queue


void enqueue(CircularQueue *q, int value) {
if (isQueueFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (q->front == -1) { // First element
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->arr[q->rear] = value;
printf("Enqueued %d\n", value);
}

// Function to dequeue an element from the circular queue


int dequeue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1;
}
int value = q->arr[q->front];
if (q->front == q->rear) { // Only one element
q->front = q->rear = -1; // Reset queue
} else {
q->front = (q->front + 1) % MAX;
}
printf("Dequeued %d\n", value);
return value;
}

// Function to calculate the size of the circular queue


int getQueueSize(CircularQueue *q) {
if (isQueueEmpty(q)) {
return 0;
}
if (q->rear >= q->front) {
return q->rear - q->front + 1;
} else {
return (MAX - q->front) + q->rear + 1;
}
}

// Function to display the elements of the circular queue


void displayQueue(CircularQueue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
int i = q->front;
while (i != q->rear) {
printf("%d ", q->arr[i]);
i = (i + 1) % MAX;
}
printf("%d\n", q->arr[q->rear]);
}

// Main function
int main() {
CircularQueue q;
initializeQueue(&q);

int choice, value;

printf("Circular Queue Operations:\n");


printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Check size of the queue\n");
printf("4. Display the queue\n");
printf("5. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
dequeue(&q);
break;
case 3:
printf("Size of the queue: %d\n", getQueueSize(&q));
break;
case 4:
displayQueue(&q);
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 5);

return 0;
}

You might also like