What Is Queue in Data Structure in C?

//

Heather Bennett

What Is Queue in Data Structure in C?

A queue is a commonly used data structure in computer science that follows the FIFO (First-In-First-Out) principle. It represents a collection of elements in which an element is inserted at one end (rear) and removed from the other end (front). In simpler terms, it works like a queue of people waiting in line, where the person who arrives first gets served first.

Basic Operations on a Queue:

A queue typically supports the following operations:

  • Enqueue: This operation adds an element to the rear of the queue.
  • Dequeue: This operation removes an element from the front of the queue.
  • IsEmpty: This operation checks if the queue is empty or not.
  • IsFull: This operation checks if the queue is full or not (in case of a fixed-size implementation).
  • Peek/Front: This operation retrieves the front element without removing it.

An Example Scenario:

To better understand queues, let’s consider an example scenario. Imagine you are building a program that simulates a printing job queue.

Each print job arrives at different times and needs to be processed in order. The first job that arrives should be printed first, followed by subsequent jobs.

Coding a Queue in C:

In C, we can implement a queue using arrays or linked lists. Here’s an example implementation using arrays:

#include <stdio.h>
#define MAX_SIZE 100

int queue[MAX_SIZE];
int front = -1;
int rear = -1;

void enqueue(int element) {
    if (rear == MAX_SIZE - 1) {
        printf("Queue Overflow\n");
    } else {
        if (front == -1) {
            front = 0;
        }
        rear++;
        queue[rear] = element;
    }
}

void dequeue() {
    if (front == -1 || front > rear) {
        printf("Queue Underflow\n");
    } else {
        printf("Dequeued: %d\n", queue[front]);
        front++;
    }
}

int isEmpty() {
    return (front == -1 || front > rear);
}

int isFull() {
    return (rear == MAX_SIZE - 1);
}

int peek() {
    if (isEmpty()) {
        printf("Queue is Empty\n");
        return -1;
    } else {
        return queue[front];
    }
}

int main() {
    enqueue(10);
    enqueue(20);
    enqueue(30);

    dequeue();
    
    printf("Front element: %d\n", peek());
    
    return 0;
}

Conclusion:

Queues are an essential concept in data structures and are widely used in various scenarios. Understanding queues and their operations is crucial for efficient programming and problem-solving. In this article, we explored the concept of queues, their basic operations, and even implemented a simple queue using arrays in C.

Now that you have a good understanding of queues, you can apply this knowledge to solve real-world problems that involve managing data in a sequential manner.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy