Priority queue in C: solved exercise

Priority queue in C: solved exercise

This exercise is scheduled for daily publication and follows the standard site structure: statement, solution, and expected output.

Problem statement

Solve the practical case and verify the console output.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

#define MAX 10
int q[MAX], n = 0;

void push(int x) {
    int i = n - 1;
    while (i >= 0 && q[i] < x) { q[i + 1] = q[i]; i--; }
    q[i + 1] = x;
    n++;
}

int pop(void) { return q[--n]; }

int main(void) {
    push(3); push(10); push(5);
    printf("%d %d %d\n", pop(), pop(), pop());
    return 0;
}

Expected output

1
3 5 10

Common mistakes

  • Not validating standard-function return values.
  • Ignoring edge cases for indices, pointers, or buffers.
  • Skipping example-based test runs before publishing.

Practical use

Priority queues are the foundation of algorithms like Dijkstra, task schedulers, and event management systems.

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.