Queue in C: solved exercise with circular array

Queue in C: solved exercise

If you searched for queue in C solved exercise, this page shows a FIFO queue implementation with a circular buffer.

Problem statement

Implement a queue with:

  • enqueue,
  • dequeue,
  • full/empty checks.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>

#define CAP 5

typedef struct {
    int data[CAP];
    int front, rear, size;
} Queue;

void init(Queue *q) { q->front = 0; q->rear = -1; q->size = 0; }
int is_empty(Queue *q) { return q->size == 0; }
int is_full(Queue *q) { return q->size == CAP; }

int enqueue(Queue *q, int x) {
    if (is_full(q)) return 0;
    q->rear = (q->rear + 1) % CAP;
    q->data[q->rear] = x;
    q->size++;
    return 1;
}

int dequeue(Queue *q, int *out) {
    if (is_empty(q)) return 0;
    *out = q->data[q->front];
    q->front = (q->front + 1) % CAP;
    q->size--;
    return 1;
}

int main(void) {
    Queue q;
    int v;

    init(&q);
    enqueue(&q, 7);
    enqueue(&q, 8);
    enqueue(&q, 9);

    dequeue(&q, &v); printf("Out: %d\n", v);
    dequeue(&q, &v); printf("Out: %d\n", v);

    return 0;
}

Expected output

1
2
Out: 7
Out: 8

Common mistakes

  • Forgetting modulo % CAP wraparound.
  • Using only front == rear without tracking size.
  • Missing underflow check on dequeue.

Practical use

FIFO queues are core in message systems, pipelines, and async job processing.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.