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

Circular Queue

Uploaded by

sanmitrapolley12
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)
8 views2 pages

Circular Queue

Uploaded by

sanmitrapolley12
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

#include <stdio.

h> int main() {


#define MAX 5 int choice, item;
while (1) {
int queue[MAX]; printf("\n1. Enqueue\n2. Dequeue\n3.
int front = -1, rear = -1; Display\n4. Exit\n");
printf("Enter choice: ");
void enqueue(int item) { scanf("%d", &choice);
if ((front == 0 && rear == MAX-1) || (front == rear+1)) switch (choice) {
{ case 1:
printf("Queue Overflow\n"); printf("Enter element: ");
return; scanf("%d", &item);
} enqueue(item);
if (front == -1) // First element break;
front = 0; case 2:
rear = (rear + 1) % MAX; dequeue();
queue[rear] = item; break;
printf("%d inserted\n", item); case 3:
} display();
break;
void dequeue() { case 4:
if (front == -1) { return 0;
printf("Queue Underflow\n"); default:
return; printf("Invalid choice\n");
} }
printf("Deleted: %d\n", queue[front]); }
if (front == rear) { }
// only one element
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
}

void display() {
if (front == -1) {
printf("Queue is Empty\n");
return;
}
printf("Queue elements: ");
int i = front;
while (1) {
printf("%d ", queue[i]);
if (i == rear)
break;
i = (i + 1) % MAX;
}
printf("\n");
}
Algorithm

Initialization:

1. Define an array queue[MAX].


2. Initialize two variables:
o front = -1
o rear = -1

1. Insertion (Enqueue)

1. Check if the queue is full:


o Condition: (front == 0 && rear == MAX-1) OR (front == rear+1)
o If true → Overflow, cannot insert.
2. Else:
o If front == -1 → set front = 0.
o Update rear: rear = (rear + 1) % MAX.
o Insert element at queue[rear].

2. Deletion (Dequeue)

1. Check if the queue is empty:


o Condition: front == -1.
o If true → Underflow, cannot delete.
2. Else:
o Take out the element at queue[front].
o If front == rear → Only one element left, reset:
front = rear = -1.
o Else → front = (front + 1) % MAX.

3. Display

1. If front == -1 → Queue is empty.


2. Else:
o Start from i = front.
o Print queue[i].
o Move i = (i + 1) % MAX until i != (rear+1) % MAX.

You might also like