Circular Queue using Array in C

Implementation of Circular Queues using Array in C

In this post we will learn on how we can implement circular queues purely using arrays. Circular queues are extension of linear queues where the max size of queue is always available for insertion. Unlike linear queues which faces the problem of reduction in available size for insertion with each iterative dequeue operation that happens, we will learn more about the same in this post.

Circular Queues Implementation using Arrays in C

We can make our code circular by making minor adjustment and changes in the code.

For example, our code can try to enter rear item the following ways –

`rear = (rear + 1)%size`

In this case if the queue is full, it will go to 0th position, if 0th position is empty.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Code for Circular Queues implementation using Arrays

`#include <stdio.h>#define capacity 6int queue[capacity];int front = -1, rear = -1;// Here we check if the Circular queue is full or notint checkFull(){    if ((front == rear + 1) || (front == 0 && rear == capacity - 1)){        return 1;    }    return 0;}// Here we check if the Circular queue is empty or notint checkEmpty(){    if (front == -1)     {        return 1;    }  return 0;}// Addtion in the Circular Queuevoid enqueue(int value){    if (checkFull())        printf("Overflow condition\n");        else    {        if (front == -1)             front = 0;                rear = (rear + 1) % capacity;        queue[rear] = value;        printf("%d was enqueued to circular queue\n", value);  }}// Removal from the Circular Queueint dequeue() {    int variable;    if (checkEmpty()) {        printf("Underflow condition\n");        return -1;    }     else    {        variable = queue[front];        if (front == rear) {            front = rear = -1;    }     else {      front = (front + 1) % capacity;    }    printf("%d was dequeued from circular queue\n", variable);    return 1;  }}// Display the queuevoid print(){    int i;    if (checkEmpty())        printf("Nothing to dequeue\n");    else    {        printf("\nThe queue looks like: \n");        for (i = front; i != rear; i = (i + 1) % capacity)        {            printf("%d ", queue[i]);        }    printf("%d \n\n", queue[i]);  }}int main() {  // Not possible as the Circular queue is empty  dequeue();  enqueue(15);  enqueue(20);  enqueue(25);  enqueue(30);  enqueue(35);  print();  dequeue();  dequeue();  print();  enqueue(40);  enqueue(45);  enqueue(50);  enqueue(55);//Overflow condition  print();  return 0;}`