Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to create a queue, then enqueue and dequeue elements in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define MAX 128 // Maximum size of the queue

// Queue structure
typedef struct Queue {
    int items[MAX];
    int first;
    int last;
} Queue;

// Function to initialize the queue
void initializeQueue(Queue *q) {
    q->first = -1;
    q->last = -1;
}

// Function to check if the queue is empty
int isEmpty(Queue *q) {
    return q->first == -1;
}

// Function to check if the queue is full
int isFull(Queue *q) {
    return q->last == MAX - 1;
}

// Function to add an element to the queue (enqueue)
void enqueue(Queue *q, int value) {
    if (isFull(q)) {
        printf("Queue is full! Cannot enqueue %d.\n", value);
        return;
    }
    if (isEmpty(q)) {
        q->first = 0; // Set first to 0 if the queue was empty
    }
    q->last++;
    q->items[q->last] = value;
    printf("Enqueued: %d\n", value);
}

// Function to remove an element from the queue (dequeue)
int dequeue(Queue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty! Cannot dequeue.\n");
        return -1; // Return -1 to indicate an error
    }
    int value = q->items[q->first];
    if (q->first == q->last) {
        // If the queue becomes empty after this operation
        q->first = q->last = -1;
    } else {
        q->first++;
    }
    printf("Dequeued: %d\n", value);
    
    return value;
}

// Function to display the elements of the queue
void display(Queue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty!\n");
        return;
    }
    printf("Queue elements: ");
    for (int i = q->first; i <= q->last; i++) {
        printf("%d ", q->items[i]);
    }
    printf("\n");
}

// Main function to demonstrate the queue operations
int main() {
    Queue q;
    initializeQueue(&q);

    // Example operations
    enqueue(&q, 10);
    enqueue(&q, 20);
    enqueue(&q, 30);

    display(&q);
    printf("\n");

    dequeue(&q);
    display(&q);
    printf("\n");

    enqueue(&q, 40);
    display(&q);

    return 0;
}



/*
run:

Enqueued: 10
Enqueued: 20
Enqueued: 30
Queue elements: 10 20 30 

Dequeued: 10
Queue elements: 20 30 

Enqueued: 40
Queue elements: 20 30 40 

*/


 



answered Aug 22, 2025 by avibootz
...