C in 100 Seconds: Queue
Video: C in 100 Seconds: Queue — Enqueue, Dequeue, Circular Array | Episode 47 by Taught by Celeste AI - AI Coding Coach
Watch full page →Queue — Enqueue, Dequeue, Circular Array
A queue is first in, first out (FIFO). The first item added is the first one removed. We build a circular queue using an array and modulo arithmetic.
The Queue Struct
typedef struct {
int items[MAX];
int front;
int rear;
int count;
} Queue;
front is where we dequeue from, rear is where we enqueue to, count tracks how many items are in the queue.
Enqueue — Add to Rear
void enqueue(Queue *q, int value) {
if (is_full(q)) { printf("Queue full!\n"); return; }
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = value;
q->count++;
}
The % MAX makes it circular — when rear reaches the end of the array, it wraps back to zero.
Dequeue — Remove from Front
int dequeue(Queue *q) {
if (is_empty(q)) { printf("Queue empty!\n"); return -1; }
int value = q->items[q->front];
q->front = (q->front + 1) % MAX;
q->count--;
return value;
}
Read from front, advance front circularly, decrement count.
Circular Wrap
After dequeuing items from the front, those array slots are free. When we enqueue again, rear wraps around and reuses them. No wasted space.
Student Code
Try it yourself: episode47/queue.c