Embedded software technical articles | embeddedSoft
HomeAbout UsContact Us

C program to implement queue data structure

By embeddedSoft
Published in Embedded C/C++
September 08, 2025
1 min read
C program to implement queue data structure

This is a simple queue implementation using array.

#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // maximum size of the queue
int queue[MAX];
int front = -1, rear = -1;
// Function to check if queue is full
int isFull() {
return (front == (rear + 1) % MAX);
}
// Function to check if queue is empty
int isEmpty() {
return (front == -1);
}
// Function to insert an element in the queue
void enqueue(int value) {
if (isFull()) {
printf("Queue Overflow! Cannot insert %d\n", value);
return;
}
if (front == -1) {
front = 0;
}
rear = (rear + 1) % MAX;
queue[rear] = value;
printf("%d enqueued into the queue.\n", value);
}
// Function to delete an element from the queue
int dequeue() {
if (isEmpty()) {
printf("Queue Underflow! No elements to dequeue.\n");
return -1;
}
int value = queue[front];
if (front == rear) {
// Queue becomes empty
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
printf("%d dequeued from the queue.\n", value);
return value;
}
// Function to display the queue
void display() {
if (isEmpty()) {
printf("Queue is empty.\n");
return;
}
printf("Queue elements: ");
int i = front;
while (1) {
printf("%d ", queue[i]);
if (i == rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\n--- Queue Menu ---\n");
printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}

Code Walkthrough

  1. Circular Queue: Uses modulo (% MAX) to reuse array space.
  2. Prevents overflow and underflow.
  3. Menu-driven (enqueue, dequeue, display, exit).
  4. Uses front and rear indices to manage the queue.

Tags

c programmingembeddedqueuedata structure

Share


Previous Article
C program to swap the rows-to-columns for any square matrix
embeddedSoft

embeddedSoft

Insightful articles on embedded systems

Related Posts

C Program to implement custom mutex_lock() and mutex_unlock()
C Program to implement custom mutex_lock() and mutex_unlock()
September 07, 2025
1 min
Embedded software technical articles | embeddedSoft
© 2025, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media