DATA STRUCTURES PROGRAM • QUEUES & DEQUES
Implement a Circular Queue Using an Array
Learn how to implement a circular queue using an array using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Removed = 10 20 30 40
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
#define CAPACITY 5
struct Queue { int values[CAPACITY]; int front; int rear; int count; };
void enqueue(struct Queue *queue, int value)
{
if (queue->count == CAPACITY) exit(EXIT_FAILURE);
queue->values[queue->rear] = value;
queue->rear = (queue->rear + 1) % CAPACITY;
queue->count++;
}
int dequeue(struct Queue *queue)
{
if (queue->count == 0) exit(EXIT_FAILURE);
int value = queue->values[queue->front];
queue->front = (queue->front + 1) % CAPACITY;
queue->count--;
return value;
}
int main(void)
{
struct Queue queue = {{0}, 0, 0, 0};
enqueue(&queue, 10); enqueue(&queue, 20); enqueue(&queue, 30);
printf("Removed = %d\n", dequeue(&queue));
enqueue(&queue, 40);
while (queue.count > 0) printf("%d ", dequeue(&queue));
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Removed = 10 20 30 40
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Wrap front and rear with modulo so released array positions can be reused.
- Display the computed result.
Wrap front and rear with modulo so released array positions can be reused.
EFFICIENCY
Time and space complexity
Time complexity
O(1) per operation
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
