## DEV Community

Maniruzzaman Akash

Posted on

# Queue Data Structure Detailed Examples

## Queue Data Structure

A queue is a fundamental data structure in computer science that follows the First-In-First-Out (FIFO) principle. The element that enters the queue first is the first to be removed and the element enters last is the last to be removed.

## Practical Queue Example in C Programming

``````#include <stdio.h>

#define MAX_SIZE 100

struct Queue {
int arr[MAX_SIZE];
int front, rear;
};

// Function to initialize the queue
void initQueue(struct Queue* q) {
q->front = q->rear = -1;
}

// Enqueue Operation
void enqueue(struct Queue* q, int item) {
if (q->rear == MAX_SIZE - 1) {
printf("Queue Overflow: Cannot enqueue more elements.\n");
return;
}

if (q->front == -1) {
q->front = q->rear = 0;
} else {
q->rear++;
}

q->arr[q->rear] = item;
printf("%d enqueued to the queue.\n", item);
}

// Dequeue Operation
void dequeue(struct Queue* q) {
if (q->front == -1) {
printf("Queue Underflow: Cannot dequeue from an empty queue.\n");
return;
}

int dequeuedItem = q->arr[q->front];

if (q->front == q->rear) {
q->front = q->rear = -1; // Reset the queue when the last element is dequeued
} else {
q->front++;
}

printf("%d dequeued from the queue.\n", dequeuedItem);
}

// Peek (or Front) Operation
void peek(struct Queue* q) {
if (q->front == -1) {
printf("Queue is empty.\n");
} else {
printf("Front element: %d\n", q->arr[q->front]);
}
}

// Size Operation
int size(struct Queue* q) {
if (q->front == -1) {
return 0;
}
return q->rear - q->front + 1;
}

// Search Operation
int search(struct Queue* q, int item) {
for (int i = q->front; i <= q->rear; i++) {
if (q->arr[i] == item) {
printf("%d found in the queue.\n", item);
return 1;
}
}
return 0;
}

// Check if the queue is empty
int isEmpty(struct Queue* q) {
return q->front == -1;
}

int main() {
struct Queue myQueue;
initQueue(&myQueue);

enqueue(&myQueue, 10);
enqueue(&myQueue, 20);
enqueue(&myQueue, 30);

peek(&myQueue);

dequeue(&myQueue);
peek(&myQueue);

printf("Queue Size: %d\n", size(&myQueue));

search(&myQueue, 20);
search(&myQueue, 40);

return 0;
}
``````

Get Queue examples with practical detail in depth knowledge - https://devsenv.com/tutorials/queue