#include <stdio.h>
#include <stdlib.h>
#define SIZE 5 // Define the size of the queue
typedef struct {
int items[SIZE];
int front, rear;
} CircularQueue;
// Function to initialize the queue
void initializeQueue(CircularQueue *q) {
q->front = -1;
q->rear = -1;
}
// Check if the queue is full
int isFull(CircularQueue *q) {
return ((q->rear + 1) % SIZE == q->front);
}
// Check if the queue is empty
int isEmpty(CircularQueue *q) {
return (q->front == -1);
}
// Enqueue operation
void enqueue(CircularQueue *q, int value) {
if (isFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear = (q->rear + 1) % SIZE;
q->items[q->rear] = value;
printf("Enqueued: %d\n", value);
}
// Dequeue operation
int dequeue(CircularQueue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue.\n");
return -1;
}
int data = q->items[q->front];
if (q->front == q->rear) {
// Queue becomes empty
q->front = -1;
q->rear = -1;
} else {
q->front = (q->front + 1) % SIZE;
}
printf("Dequeued: %d\n", data);
return data;
}
// Display the queue visually
void display(CircularQueue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Circular Queue: [ ");
for (int i = 0; i < SIZE; i++) {
if ((q->front <= q->rear && (i >= q->front && i <= q->rear)) ||
(q->front > q->rear && (i >= q->front || i <= q->rear))) {
printf("%d ", q->items[i]);
} else {
printf("_ ");
}
}
printf("]\n");
}
// Menu to choose operations
void menu() {
printf("\nChoose an operation:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
}
int main() {
CircularQueue q;
initializeQueue(&q);
int choice, value;
while (1) {
menu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
display(&q);
break;
case 2:
dequeue(&q);
display(&q);
break;
case 3:
display(&q);
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
To embed this program on your website, copy the following code and paste it into your website's HTML: