Course contentsShow
← C
Lesson 1018 of 1,21914. Data Structures in CFree lesson

Circular array implementation

Circular array implementation

What you'll learn: How to wrap an array around itself to prevent wasting memory in a queue.

The problem with linear queues

In a standard array-based queue, we use a front and rear index. As we add items, rear moves forward. As we remove items, front moves forward. Eventually, rear hits the end of the array. Even if the front of the array is empty because we’ve removed items, we can’t add anything new because the computer thinks the queue is "full."

Imagine a row of five chairs. People sit down starting from chair 0. As they leave, chair 0 and 1 become empty. But if the "entrance" is strictly at chair 4, once that's filled, you can't let anyone else in, even though seats 0 and 1 are empty.

The "Modulo" trick

A circular array solves this by treating the end of the array as if it connects back to the beginning. Instead of stopping at the last index, we use the modulo operator (%) to "wrap" the index back to zero.

If your array size is 5 and your rear is at index 4, the next position isn't 5 (which is out of bounds); it’s (4 + 1) % 5, which equals 0. This turns your straight line into a continuous loop.

The code implementation

Here is how you handle the movement of the rear index in a circular queue:

#include <stdio.h>

#define SIZE 5

int main() {
    int queue[SIZE];
    int front = -1, rear = -1;
    int data = 100;

    // To add (enqueue) an element:
    // 1. Move rear forward in a circle
    // 2. If the queue isn't full, place the data
    
    // Logic for circular increment:
    rear = (rear + 1) % SIZE;
    queue[rear] = data;

    printf("Rear is now at index: %d\n", rear);
    
    // If we do this 5 more times, rear will wrap 
    // from 4 back to 0 automatically.
    
    return 0;
}

Managing the flow

In a circular queue, you are "full" when the next spot for rear is exactly where front is currently sitting. This indicates the circle has met itself. By using the modulo operator, you ensure that every single slot in your array is reusable, making your data structure memory-efficient and infinitely looping as long as you keep processing items.

Key takeaway

Circular arrays use the modulo operator (index % size) to connect the end of the array back to the start, allowing for continuous reuse of empty memory slots.