0% found this document useful (0 votes)
8 views2 pages

Circular Queue

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

Circular Queue

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

#include <stdio.

h>
#include <stdlib.h>
#define MAX 4 // size of circular queue

int queue[MAX];
int front = -1, rear = -1;

// Function to insert an element


void enqueue(int item) {
if ((front == 0 && rear == MAX - 1) || (front == rear + 1)) {
printf("Queue Overflow!\n");
return;
}
if (front == -1) { // first element
front = rear = 0;
}
else if (rear == MAX - 1) { // wrap around
rear = 0;
}
else {
rear++;
}
queue[rear] = item;
printf("%d inserted.\n", item);
printf("\nfront = %d", front);
printf("\nrear = %d", rear);
}

// Function to delete an element


void dequeue() {
if (front == -1) {
printf("Queue Underflow!\n");
return;
}
int item = queue[front];
if (front == rear) { // only one element
front = rear = -1;
}
else if (front == MAX - 1) {
front = 0;
}
else {
front++;
}
printf("%d deleted.\n", item);
printf("\nfront = %d", front);
printf("\nrear = %d", rear);
}

// Function to display queue


void display() {
int i;
if (front == -1) {
printf("Queue is empty!\n");
return;
}
printf("Queue elements: ");
if (front <= rear) {
for (i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
} else {
for (i = front; i < MAX; i++) {
printf("%d ", queue[i]);
}
for ( i = 0; i <= rear; i++) {
printf("%d ", queue[i]);
}
}
printf("\n");
}

// Main function
int main() {
int choice, item;
while (1) {
printf("\n--- Circular Queue Menu ---\n");
printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &item);
enqueue(item);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice!\n");
}
}
return 0;
}

You might also like