MODULE 4.4: CIRCULAR QUEUE — WRAPPING AROUND WITH MODULO

A student-friendly guide to Circular Queues (Ring Buffers)—how wrapping around with % reuses empty spots at the front and keeps fixed-size lines moving smoothly.

💡 Summary: Reusing Empty Front Slots Instead of Hitting a Dead End

In a plain array queue, once the back pointer (rear) reaches the end of the array, you can't add new items—even if you already removed items from the front and left empty spaces behind! That annoying trap is called false overflow. A Circular Queue (often called a ring buffer) fixes this by wrapping the end of the array back around to index 0 using the remainder (modulo) operator: (index + 1) % capacity.

Because it reuses spaces in a neat loop without shifting elements around, a circular queue is great for taking turns in a cycle, buffering audio or network data, and keeping recent readings in a fixed space.

1. How a Ring Buffer Works & Wrapping Indices with %
Instead of walking off the end of an array of size N, a circular queue wraps back to 0 after index N - 1:
  • Using a count (Size) Variable: Keep track of how many items are currently inside (count from 0 to capacity), and update positions with rear = (rear + 1) % capacity and front = (front + 1) % capacity. That makes checking isEmpty() (count == 0) and isFull() (count == capacity) super clear.
  • One-Slot-Reserved Trick (Without a Counter): Some implementations leave one slot empty and say the queue is full when (rear + 1) % capacity == front.
What You Are Comparing Plain Array Queue Circular Queue
Moving Forward rear + 1 or front + 1 (rear + 1) % N or (front + 1) % N
Freed Front Slots Sit unused until the queue resets Get reused right away as rear wraps around
enqueue & dequeue O(1) until the back hits the end O(1) even across many wrap-around cycles
C++ (circular_queue_ring_buffer.cpp)
#include 
using namespace std;

class CircularQueue {
private:
    int* buffer;
    int capacity;
    int front;
    int rear;
    int count;

public:
    CircularQueue(int cap) {
        capacity = cap;
        buffer = new int[capacity];
        front = 0;
        rear = -1;
        count = 0;
    }

    ~CircularQueue() {
        delete[] buffer;
    }

    bool isEmpty() const { return count == 0; }
    bool isFull() const  { return count == capacity; }

    void enqueue(int val) {
        if (isFull()) {
            cout << "Ring Buffer Full! Cannot enqueue " << val << "\n";
            return;
        }
        rear = (rear + 1) % capacity;
        buffer[rear] = val;
        count++;
        cout << "Enqueued " << val << " at index " << rear << " (size=" << count << ")\n";
    }

    int dequeue() {
        if (isEmpty()) {
            cout << "Ring Buffer Empty!\n";
            return -1;
        }
        int item = buffer[front];
        front = (front + 1) % capacity;
        count--;
        return item;
    }

    int peek() const {
        return isEmpty() ? -1 : buffer[front];
    }
};

int main() {
    CircularQueue cq(3);
    cq.enqueue(10);
    cq.enqueue(20);
    cq.enqueue(30);

    cout << "Dequeued front: " << cq.dequeue() << "\n"; // Frees index 0
    cq.enqueue(40); // Wraps around to index 0!
    cout << "Current front: " << cq.peek() << "\n";
    return 0;
}
Output: Enqueued 10 at index 0 (size=1) Enqueued 20 at index 1 (size=2) Enqueued 30 at index 2 (size=3) Dequeued front: 10 Enqueued 40 at index 0 (size=3) Current front: 20
2. Circular Linked Queue & Overwriting Oldest Items
Two extra ways students and programmers see circular queues in action:
  • Circular Linked Queue: In a circular linked list, keeping just a rear pointer lets you reach the front right away via rear->next, making front removal and back insertion easy without a fixed array size.
  • Overwriting Ring Buffer: When recording live sensor values or recent logs in a fixed space, if the buffer is full and a new reading arrives, you can overwrite the oldest item at head and move head forward so you always keep the newest N items.
Python (circular_linked_and_telemetry_ring.py)
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class CircularLinkedQueue:
    def __init__(self):
        self.rear = None

    def enqueue(self, val):
        node = Node(val)
        if self.rear is None:
            node.next = node
            self.rear = node
        else:
            node.next = self.rear.next  # Link new node to the front
            self.rear.next = node       # Old rear points to new node
            self.rear = node            # Move rear to the new node

    def dequeue(self):
        if self.rear is None:
            raise IndexError("Circular queue is empty")
        front = self.rear.next
        if front == self.rear:
            self.rear = None
        else:
            self.rear.next = front.next
        return front.data

cq = CircularLinkedQueue()
for task in ["Task_1", "Task_2", "Task_3"]:
    cq.enqueue(task)

print("Dequeued:", cq.dequeue())
cq.enqueue("Task_4")
print("Next Dequeued:", cq.dequeue())
print("Next Dequeued:", cq.dequeue())
print("Next Dequeued:", cq.dequeue())
Output: Dequeued: Task_1 Next Dequeued: Task_2 Next Dequeued: Task_3 Next Dequeued: Task_4
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Here are five real-world places where circular queues help software keep running smoothly:
  • 1. Taking Turns on a CPU (Round-Robin): Tasks each get a short turn on the CPU; if a task isn't finished yet, it goes to the back of the loop to wait for its next turn.
  • 2. Buffering Audio or Video Streams: Media players fill a buffer with incoming data while playing smoothly from the front.
  • 3. Incoming & Outgoing Network Data: Network cards and drivers often use ring-shaped buffers to pass packets without pausing or reallocating memory every millisecond.
  • 4. Hardware & Microcontroller Input Buffers: Devices with limited memory use fixed-size circular buffers to store incoming signals safely.
  • 5. Traffic Signal Cycles: Light phases repeat in a set order around a loop.
Python (realtime_circular_apps_1_to_5.py)
from collections import deque

# 1. Taking turns across tasks with a fixed time slice (quantum)
def round_robin_scheduler(processes, quantum):
    rq = deque(processes)  # Each item: [pid, remaining_time]
    time = 0
    timeline = []

    while rq:
        pid, burst = rq.popleft()
        run_time = min(burst, quantum)
        time += run_time
        burst -= run_time
        timeline.append(f"{pid}@{time}ms")
        if burst > 0:
            rq.append([pid, burst])  # Put back at the end to take another turn later

    return " -> ".join(timeline)

tasks = [["P1", 10], ["P2", 4], ["P3", 7]]
print("1. Round-Robin Execution (quantum=4ms):")
print("  ", round_robin_scheduler(tasks, quantum=4))
Output: 1. Round-Robin Execution (quantum=4ms): P1@4ms -> P2@8ms -> P3@12ms -> P1@16ms -> P3@19ms -> P1@21ms
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world examples of circular buffers and rotating queues:
  • 6. Keeping the Last N Sensor Readings: A weather or IoT device can keep just the latest few readings in a fixed space without growing forever.
  • 7. Rotating Turns in Multiplayer Games: Turns move from one player to the next and wrap back to the first player.
  • 8. Reusing a Pool of Connections or Workers: When a worker finishes a job, it can go back into a pool to be reused.
  • 9. Keeping Recent Logs in Memory: Apps sometimes keep only the last few hundred log messages in a rolling buffer for quick viewing.
  • 10. Items Moving on a Loop / Carousel: Positions around a loop map naturally to remainder (modulo) math.
Python (realtime_circular_apps_6_to_10.py)
# 6. Keeping only the latest 4 temperature readings in a fixed-size ring
class SensorRingBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.buf = [None] * capacity
        self.head = 0
        self.size = 0

    def record(self, reading):
        idx = (self.head + self.size) % self.capacity
        if self.size == self.capacity:
            self.buf[self.head] = reading
            self.head = (self.head + 1) % self.capacity
        else:
            self.buf[idx] = reading
            self.size += 1

    def latest_readings(self):
        return [self.buf[(self.head + i) % self.capacity] for i in range(self.size)]

sensor = SensorRingBuffer(4)
for temp in [28.1, 28.4, 29.0, 29.5, 30.2, 30.8]:
    sensor.record(temp)

print("6. Latest 4 Sensor Readings:", sensor.latest_readings())
Output: 6. Latest 4 Sensor Readings: [29.0, 29.5, 30.2, 30.8]
5. Exam & Study Tips for Students
Keep these three reminders in mind when tracing circular queues on paper or writing lab programs:
  • Don't forget % capacity: When moving front or rear forward, always wrap with % capacity so it loops back to 0 instead of going out of bounds.
  • Watch out for the "Full vs. Empty" confusion: If you don't track count (or reserve one slot), front == rear can look the same when empty and when full.
  • Know why it exists: A circular queue is the go-to fix when you want a fixed-size array queue that reuses freed front slots without false overflow.
Python (circular_queue_checklist.py)
checkpoints = [
    "Wrap Around with %: next_idx = (idx + 1) % capacity keeps indices inside bounds.",
    "No False Overflow: Empty slots at the front get reused as rear wraps around.",
    "Track Size Clearly: Using a count variable makes empty and full checks easy to read."
]

for item in checkpoints:
    print("*", item)
Output: * Wrap Around with %: next_idx = (idx + 1) % capacity keeps indices inside bounds. * No False Overflow: Empty slots at the front get reused as rear wraps around. * Track Size Clearly: Using a count variable makes empty and full checks easy to read.