A queue is a linear data structure that follows the First In First Out (FIFO) principle. That means the element inserted first is removed first. This blog explains how to implement a queue in C using arrays with the operations: INSERT, DELETE, and DISPLAY.
What is a Queue?
A queue works like a line at a bank or ticket counter:
- The first person to enter the line is the first one to be served.
- New elements are inserted at the rear.
- Elements are removed from the front.
Queue Operations
Operation | Description |
---|---|
INSERT | Adds an element to the rear of the queue |
DELETE | Removes an element from the front |
DISPLAY | Shows all elements in the queue |
C Program: Queue Using Arrays
#include <stdio.h>
#define SIZE 100
int queue[SIZE];
int front = -1, rear = -1;
// INSERT operation
void insert(int value) {
if (rear == SIZE - 1) {
printf("Queue Overflow\n");
} else {
if (front == -1) front = 0;
rear++;
queue[rear] = value;
printf("%d inserted into queue\n", value);
}
}
// DELETE operation
void delete() {
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
} else {
printf("%d deleted from queue\n", queue[front]);
front++;
}
}
// DISPLAY operation
void display() {
if (front == -1 || front > rear) {
printf("Queue is empty\n");
} else {
printf("Queue elements: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}
int main() {
int choice, value;
while (1) {
printf("\n1. INSERT\n2. DELETE\n3. DISPLAY\n4. EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insert(value);
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
}
}
Sample Output
1. INSERT
2. DELETE
3. DISPLAY
4. EXIT
Enter your choice: 1
Enter value to insert: 10
10 inserted into queue
Enter your choice: 1
Enter value to insert: 20
20 inserted into queue
Enter your choice: 3
Queue elements: 10 20
Enter your choice: 2
10 deleted from queue
Enter your choice: 3
Queue elements: 20
Key Notes
- Queue follows FIFO: First In First Out.
- Overflow occurs if the array is full.
- Underflow occurs if there’s nothing left to delete.