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

Modulo operator for circular wrap

Modulo operator for circular wrap

What you'll learn: How to use the modulo operator (%) to turn a standard array into a circular queue that never runs out of space at the end.

The problem with linear arrays

Imagine a queue as a row of five chairs. As people arrive, they sit in chairs 0, 1, 2, 3, and 4. When the first person leaves chair 0, that spot becomes empty. However, in a standard linear queue, if a sixth person arrives, you can't seat them because you've reached chair 4, even though chair 0 is wide open!

To fix this, we would have to shift every single remaining person down one seat every time someone leaves, which is slow and inefficient.

The "Round Robin" trick

The modulo operator (%) provides a mathematical way to connect the end of the array back to the beginning. It calculates the remainder of a division. For an array of size 5, look at what happens when we increment a counter and apply % 5:

  • 4 % 5 = 4 (Still at the last slot)
  • 5 % 5 = 0 (Back to the start!)
  • 6 % 5 = 1

By using (index + 1) % SIZE, we create a circular loop. When our "tail" pointer hits the end of the array, the modulo operator resets it to index 0 automatically, allowing us to reuse those empty seats at the front.

Implementing the wrap

In a circular queue, we don't move the data; we just move our "Head" (where we remove items) and "Tail" (where we add items) pointers in a circle.

#define SIZE 5

int queue[SIZE];
int head = 0;
int tail = 0;

// Adding an element (Enqueue)
void enqueue(int value) {
    // Place the value at the current tail
    queue[tail] = value;
    
    // Move tail forward, wrapping to 0 if it hits SIZE
    tail = (tail + 1) % SIZE;
}

// Removing an element (Dequeue)
int dequeue() {
    int value = queue[head];
    
    // Move head forward, wrapping to 0 if it hits SIZE
    head = (head + 1) % SIZE;
    
    return value;
}

Why this matters

Using the modulo operator turns a static array into a "conveyor belt." As long as the queue isn't completely full, you can keep adding and removing items forever without ever having to shift data or run out of index space. It makes your queue operations lightning-fast (O(1) time complexity) because you are only changing two integers.

Key takeaway

The modulo operator creates a circular index by resetting the pointer to zero whenever it reaches the array's capacity.