# What Is Circular Queue in Data Structure in C?

//

Larry Thompson

What Is Circular Queue in Data Structure in C?

A circular queue is a type of data structure that follows the FIFO (First-In-First-Out) principle. It is similar to a regular queue, but with one key difference – the last element is connected to the first element to form a circular structure.

## Why Use Circular Queue?

• Efficient Memory Utilization: Unlike a regular queue, circular queues make optimal use of memory by reusing empty spaces.
• Efficient Insertion and Deletion: Insertion and deletion operations in a circular queue are performed in constant time, regardless of the number of elements.
• Circular Implementation: The circular structure allows continuous access to elements without needing to reset the back or front pointers.

## Circular Queue Operations

A circular queue supports the following operations:

• Enqueue: Adds an element to the rear end of the queue. If the queue is full, it throws an overflow error.
• Dequeue: Removes an element from the front end of the queue. If the queue is empty, it throws an underflow error.
• Front: Returns the value of the element at the front end without removing it.
• Rear: Returns the value of the element at the rear end without removing it.

### Circular Queue Implementation in C

Here’s a simple implementation of a circular queue in C:

``````#include <stdio.h>
#define MAX_SIZE 5

int circularQueue[MAX_SIZE];
int front = -1, rear = -1;

int isFull() {
if ((front == rear + 1) || (front == 0 && rear == MAX_SIZE - 1))
return 1;
return 0;
}

int isEmpty() {
if (front == -1)
return 1;
return 0;
}

void enqueue(int data) {
if (isFull())
printf("Queue is full. Overflow error!

");
else {
if (front == -1)
front = 0;
rear = (rear + 1) % MAX_SIZE;
circularQueue[rear] = data;
printf("%d enqueued successfully. ", data);
}
}

void dequeue() {
int data;
if (isEmpty())
printf("Queue is empty. Underflow error!");
else {
data = circularQueue[front];

if (front == rear)
front = rear = -1;
else
front = (front + 1) % MAX_SIZE;

printf("%d dequeued successfully.", data);
}
}

void display() {
int i, count = (rear + MAX_SIZE - front) % MAX_SIZE + 1;

printf("Queue: ");

for (i = 0; i < count; i++) {
int index = (front + i) % MAX_SIZE;
printf("%d ", circularQueue[index]);
}

}

int main() {

enqueue(10);
enqueue(20);
enqueue(30);
enqueue(40);

display();

dequeue();

display();

return 0;
}``````

## Conclusion

In summary, a circular queue is a data structure that offers efficient memory utilization and constant time insertion and deletion operations. It is an excellent choice when implementing a queue with limited memory or when the circular behavior fits the problem's requirements.

By understanding the concepts and implementation of circular queues in C, you can leverage this data structure to solve various real-world problems efficiently.