Enqueue operation logic
What you'll learn: How to add new elements to the back of a queue while maintaining the "First-In, First-Out" rule.
The "Back of the Line" Concept
Think of a queue like a physical line at a coffee shop. When you arrive, you don’t cut to the front; you join the very end. In programming, this process of joining the back of the line is called Enqueue.
Because a queue is a First-In, First-Out (FIFO) structure, the "Front" pointer stays where it is (so we know who to serve next), but the "Rear" pointer must move to accommodate the newcomer.
How the Logic Works
To successfully enqueue an item in a fixed-size array, the computer follows three logical steps:
- Check for Overflow: Before adding anything, you must check if the queue is already full. If the "Rear" has reached the maximum capacity, you can't add more data.
- Move the Rear: If there is space, we increment our
rearindex. This points the "back door" of our queue to the next empty slot. - Insert the Data: We place the new value into the array at the position indicated by the new
rear.
If the queue was completely empty before this operation, we also have to point the front at this first element, as they are now both the first and last person in line.
Enqueue in Code
Here is how we translate that logic into a C function using a simple structure:
#include <stdio.h>
#define SIZE 5
int queue[SIZE];
int front = -1;
int rear = -1;
void enqueue(int value) {
// 1. Check if the queue is full
if (rear == SIZE - 1) {
printf("Queue is full! Cannot add %d\n", value);
} else {
// 2. If the queue is empty, initialize front
if (front == -1) {
front = 0;
}
// 3. Increment rear and insert the value
rear++;
queue[rear] = value;
printf("Inserted %d\n", value);
}
}
In this snippet, notice how rear acts as a scout. It moves forward to claim a spot, and then the data is dropped into that spot. The front pointer remains stationary, patiently waiting for a "Dequeue" operation to tell it to move.
Key takeaway
Enqueueing is the act of incrementing the rear index and inserting data at that position, effectively growing the line from the back.