Skip to content
StudyFame

Circular Queue in C

In the last lesson, a simple array queue said "full" even though slots at the beginning were empty. A circular queue fixes this by treating the array as a ring: when rear reaches the last index, the next element goes back to index 0, if it is free.

In this lesson you will learn how the modulo operator makes indexes wrap around, the exact full and empty conditions, a complete circular queue program, and the "count" method that many textbooks and interviewers ask about.

What You Will Learn

  • What a circular queue is and why it is needed.
  • How (index + 1) % SIZE wraps around.
  • The conditions for an empty and a full circular queue.
  • How to write enqueue, dequeue and display.
  • The "keep a count" version of the circular queue.
  • Where circular buffers are used (keyboards, audio, networks).

Circular Queue in C Explained

Exam definition: A circular queue is a linear queue implemented in an array in which the last position is connected back to the first position, forming a circle. The front and rear indexes are advanced with (index + 1) % SIZE, so free positions at the beginning of the array are reused. It is also called a ring buffer. With the front/rear method, the queue is empty when front == -1 and full when (rear + 1) % SIZE == front.

Memory trick: A circular queue is a clock face. After 12 comes 1 again, never 13. The modulo operator is the clock: (11 + 1) % 12 = 0. Two hands go round: rear (where the next person sits) and front (who leaves next). When rear is just one step behind front, every seat is taken.

SIZE = 5, after enqueue 10..50, dequeue x2, enqueue 60:

          [0]                        index: 0    1    2    3    4
       ┌──60──┐                            60   ---  30   40   50
  [4] 50      --- [1]                       ▲         ▲
       │      │                            rear     front
  [3] 40 ─── 30 [2]
                                     next enqueue goes to (0 + 1) % 5 = 1

Syntax: The Key Formulas

#define SIZE 5
int q[SIZE];
int front = -1, rear = -1;

rear  = (rear + 1) % SIZE;            /* move rear forward with wrap-around  */
front = (front + 1) % SIZE;           /* move front forward with wrap-around */

empty: front == -1
full : (rear + 1) % SIZE == front
count: (rear - front + SIZE) % SIZE + 1      /* when not empty */
rear(rear + 1) % 5
01
34
40 (wraps to the start)

Example 1: Circular Queue Using an Array

#include <stdio.h>

#define SIZE 5

int q[SIZE];
int front = -1, rear = -1;

int is_empty(void) { return front == -1; }
int is_full(void)  { return (rear + 1) % SIZE == front; }

void enqueue(int x)
{
    if (is_full())
    {
        printf("Queue full! cannot add %d\n", x);
        return;
    }
    if (is_empty())
        front = 0;
    rear = (rear + 1) % SIZE;
    q[rear] = x;
}

int dequeue(void)
{
    int x;
    if (is_empty())
    {
        printf("Queue empty!\n");
        return -1;
    }
    x = q[front];
    if (front == rear)               /* it was the only element */
        front = rear = -1;
    else
        front = (front + 1) % SIZE;
    return x;
}

void display(void)
{
    int i;
    if (is_empty())
    {
        printf("Queue: (empty)\n");
        return;
    }
    printf("Queue: ");
    for (i = front; ; i = (i + 1) % SIZE)
    {
        printf("%d ", q[i]);
        if (i == rear)
            break;
    }
    printf("  (front=%d, rear=%d)\n", front, rear);
}

int main(void)
{
    int i;

    for (i = 1; i <= 5; i++)
        enqueue(i * 10);             /* 10 20 30 40 50 */
    display();
    enqueue(60);                     /* full */

    printf("Dequeued %d\n", dequeue());
    printf("Dequeued %d\n", dequeue());
    enqueue(60);                     /* goes to index 0 */
    enqueue(70);                     /* goes to index 1 */
    display();
    enqueue(80);                     /* full again */

    while (!is_empty())
        printf("Dequeued %d\n", dequeue());
    display();
    return 0;
}

Output

Queue: 10 20 30 40 50   (front=0, rear=4)
Queue full! cannot add 60
Dequeued 10
Dequeued 20
Queue: 30 40 50 60 70   (front=2, rear=1)
Queue full! cannot add 80
Dequeued 30
Dequeued 40
Dequeued 50
Dequeued 60
Dequeued 70
Queue: (empty)

Code Explanation

  1. After five enqueues, rear = 4 and (4 + 1) % 5 = 0 = front, so the queue is full and 60 is refused.
  2. Two dequeues move front to 2. Indexes 0 and 1 are now free.
  3. Enqueue 60: rear = (4 + 1) % 5 = 0. Enqueue 70: rear = 1. The free slots are reused, which the linear queue couldn't do.
  4. Now (1 + 1) % 5 = 2 = front, so it is full again: 5 elements in 5 slots, nothing wasted.
  5. display walks from front to rear with wrap-around: indexes 2, 3, 4, 0, 1. The output order 30 40 50 60 70 is still FIFO.
  6. When the last element is dequeued (front == rear), both are reset to −1 so the queue is empty again.

How Full and Empty Are Detected

The tricky part: if we let rear catch up with front completely, "full" and "empty" would look the same (front == rear). Two common solutions:

MethodEmpty whenFull when
front = −1 for empty (this lesson)front == -1(rear + 1) % SIZE == front
Keep a count of elementscount == 0count == SIZE
Leave one slot always emptyfront == rear(rear + 1) % SIZE == front (holds only SIZE − 1)

Where ring buffers are used

  • Keyboard buffer: key presses wait in a circular buffer until the program reads them.
  • Audio and video streaming: data arrives continuously and is played in order.
  • Network packets and serial ports in embedded systems.
  • Traffic light and round-robin systems that repeat in a cycle.

Example 2: Circular Queue with a Count (Struct Version)

#include <stdio.h>

#define SIZE 4

struct cqueue
{
    int items[SIZE];
    int front;     /* index of the first element */
    int count;     /* number of elements stored  */
};

int enqueue(struct cqueue *q, int x)
{
    if (q->count == SIZE)
        return 0;
    q->items[(q->front + q->count) % SIZE] = x;   /* rear is computed */
    q->count++;
    return 1;
}

int dequeue(struct cqueue *q, int *x)
{
    if (q->count == 0)
        return 0;
    *x = q->items[q->front];
    q->front = (q->front + 1) % SIZE;
    q->count--;
    return 1;
}

int main(void)
{
    struct cqueue q = {{0}, 0, 0};
    int x, round;

    for (round = 1; round <= 3; round++)
    {
        enqueue(&q, round * 10);
        enqueue(&q, round * 10 + 1);
        enqueue(&q, round * 10 + 2);
        printf("Round %d: count=%d, served:", round, q.count);
        dequeue(&q, &x); printf(" %d", x);
        dequeue(&q, &x); printf(" %d", x);
        printf(", front index now %d\n", q.front);
    }
    printf("Left in queue:");
    while (dequeue(&q, &x))
        printf(" %d", x);
    printf("\n");
    return 0;
}

Output

Round 1: count=3, served: 10 11, front index now 2
Round 2: count=4, served: 12 20, front index now 0
Round 3: count=4, served: 21 22, front index now 2
Left in queue: 30 31
  • This version stores front and count; the rear position is (front + count) % SIZE. Full and empty are simply count == SIZE and count == 0, with no special −1 case.
  • In round 3, only 30 and 31 fit: the queue already held 21 and 22, so after two enqueues it is full and enqueue(&q, 32) returns 0. A real program would check that return value.
  • The queue keeps cycling through indexes 0 to 3 for ever, which is why it's ideal for streams of data.

Important Points to Remember

  • A circular queue connects the last index back to index 0; also called a ring buffer.
  • Move indexes with (i + 1) % SIZE.
  • Empty: front == -1 (or count == 0). Full: (rear + 1) % SIZE == front (or count == SIZE).
  • When the last element is removed, reset front = rear = -1.
  • It reuses freed slots, solving the wasted-space problem of the linear queue.
  • All operations are still O(1).

Common Mistakes Beginners Make

MistakeWhat happensFix
rear++ without moduloIndex goes past the arrayrear = (rear + 1) % SIZE;
Checking full with rear == SIZE - 1Same wasted-space problem as before(rear + 1) % SIZE == front
Not resetting after the last dequeueEmpty queue looks full or holds stale dataIf front == rear, set both to −1
Display loop for (i = front; i <= rear; i++)Prints nothing when rear < frontWalk with modulo until you reach rear
Using front == rear as the empty test with no extra ruleCan't tell full from emptyUse −1, a count, or leave one slot empty

Circular Queue Practice Questions

  1. What is a circular queue? What problem does it solve?
  2. Write the conditions for an empty and a full circular queue.
  3. What is (4 + 1) % 5, and why does it matter?
  4. How can you count the elements of a circular queue from front and rear?
  5. Give three applications of circular buffers.
Show answers
  1. A queue in an array whose last position connects to the first; it reuses freed slots, solving the wasted space of a linear queue.
  2. Empty: front == −1. Full: (rear + 1) % SIZE == front.
  3. 0; it makes the index wrap from the last position back to the first.
  4. count = (rear − front + SIZE) % SIZE + 1 (when the queue is not empty).
  5. Keyboard buffers, audio/video streaming, network packet buffers (also CPU round-robin scheduling).

Coding Exercise

Using the front/rear circular queue of size 5, write int size(void) that returns the number of elements with the formula (rear - front + SIZE) % SIZE + 1. Enqueue 1 to 5, dequeue 3, enqueue 6 and 7, and print the size and the front element after each step.

Show solution
#include <stdio.h>

#define SIZE 5

int q[SIZE];
int front = -1, rear = -1;

int size(void)
{
    return front == -1 ? 0 : (rear - front + SIZE) % SIZE + 1;
}

void enqueue(int x)
{
    if ((rear + 1) % SIZE == front)
        return;
    if (front == -1)
        front = 0;
    rear = (rear + 1) % SIZE;
    q[rear] = x;
}

void dequeue(void)
{
    if (front == -1)
        return;
    if (front == rear)
        front = rear = -1;
    else
        front = (front + 1) % SIZE;
}

void report(const char *step)
{
    printf("%-14s size=%d front=%d\n", step, size(), front == -1 ? -1 : q[front]);
}

int main(void)
{
    int i;
    for (i = 1; i <= 5; i++)
        enqueue(i);
    report("enqueue 1-5");
    for (i = 0; i < 3; i++)
        dequeue();
    report("dequeue x3");
    enqueue(6);
    enqueue(7);
    report("enqueue 6,7");
    return 0;
}
enqueue 1-5    size=5 front=1
dequeue x3     size=2 front=4
enqueue 6,7    size=4 front=4

After "enqueue 6,7", rear has wrapped to index 1 while front is at index 3: (1 − 3 + 5) % 5 + 1 = 4.

Quick Quiz: Circular Queue (MCQ)

  1. In a circular queue of SIZE 6, rear = 5. The next rear is:

    A) 6   B) 0   C) 1   D) 5

  2. The full condition (front/rear method) is:

    A) rear == SIZE - 1   B) front == -1   C) (rear + 1) % SIZE == front   D) rear == 0

  3. A circular queue is also called a:

    A) Ring buffer   B) Heap   C) Stack   D) Deque only

  4. Which operator makes the index wrap around?

    A) /   B) %   C) &&   D) ^

  5. Main advantage of a circular queue over a linear array queue:

    A) Faster sorting   B) Reuses empty slots   C) Uses no memory   D) LIFO order

Show answers
  1. B: 0.
  2. C: (rear + 1) % SIZE == front.
  3. A: a ring buffer.
  4. B: %.
  5. B: it reuses empty slots.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Circular queueArray queue whose end wraps to index 0
Other nameRing buffer
Next index(i + 1) % SIZE
Emptyfront == −1
Full(rear + 1) % SIZE == front
Count(rear − front + SIZE) % SIZE + 1
SolvesWasted space of a linear queue

Frequently asked questions

What is a circular queue?
A queue in an array where the last position connects to the first, so freed slots are reused.
What is the condition for a circular queue to be full?
(rear + 1) % SIZE == front (when empty is marked by front = −1).
Where are circular queues used?
In keyboard buffers, streaming, network buffers and round-robin scheduling.

Remember

  • Circular queue = clock face: after the last comes the first.
  • Every index step uses % SIZE.

Next Topic

Next lesson: Binary Tree in C. You will build your first non-linear structure: a binary tree with left and right children.