C Examples

Queue in C



A queue is a linear dynamic data structure that follows First-In/First-Out (FIFO) principle. In a queue, addition of a new element and deletion of an element occurs at different end which implies that the element which is added first in the queue will be the first to be removed from the queue.

Features of queue

  • It is a dynamic data structure.
  • It has dynamic size.
  • It uses dynamic memory allocation.

Operations of a queue

  • isEmpty(): Checks whether the queue is empty or not.
  • size(): Returns the size of the queue.
  • frontElement(): Returns the front element of the queue. It is the element which will be dequeued next.
  • rearElement(): Returns the rear element of the queue. It is the element behind which next element will be enqueued.
  • EnQueue(x): Adds a new element ‘x’ from the rear side of the queue. Consequently, size of the queue increases by 1.
    Queue EnQueue
  • DeQueue(): Deletes the front element of the queue. Consequently, size of the queue decreases by 1.
    Queue DeQueue

Implementation of queue

#include <stdio.h>

#define MAX 100 

//define structure of a queue
struct queue {
  int array[MAX];
  int front;
  int rear;
};

typedef struct queue qu;

void CreateQueue(qu *q) {
  q->front = -1;
  q->rear = -1;
}

// create a function to check whether 
// the queue is empty or not  
void isEmpty(qu *q) {
  if(q->rear == q->front) {
    printf("Queue is empty.\n");
  } else {
    printf("Queue is not empty.\n");
  }
}

//create a function to return size of the queue 
int size(qu *q) {
   return (q->rear - q->front);
} 

//create a function to add new element       
void EnQueue(qu *q, int x){
  if(q->rear == (MAX - 1)){
    printf("Queue size limit reached.\n");
  } else {
    q->array[++q->rear] = x;
    printf("%i is added into the queue.\n", x);
  }
}

//create a function to delete front element       
void DeQueue(qu *q){
  if(q->rear == q->front){
    printf("Queue is empty.\n");
  } else {
    int x = q->array[++q->front];
    printf("%i is deleted from the queue.\n", x);
  }
}  

//create a function to get rear element       
int rearElement(qu *q) {
  if(q->rear == q->front) {
    printf("Queue is empty.\n");
    return 0;
  } else {
    return q->array[q->rear];
  }
}

//create a function to get front element       
int frontElement(qu *q) {
  if(q->rear == q->front) {
    printf("Queue is empty.\n");
    return 0;
  } else {
    return q->array[q->front + 1];
  }
}


// test the code 
int main() {
  qu s;
  qu *MyQueue;
  MyQueue = &s;
  CreateQueue(MyQueue);
  EnQueue(MyQueue, 10);
  EnQueue(MyQueue, 20);
  EnQueue(MyQueue, 30);
  EnQueue(MyQueue, 40);

  DeQueue(MyQueue);
  isEmpty(MyQueue);
  return 0; 
}

The above code will give the following output:

10 is added into the queue.
20 is added into the queue.
30 is added into the queue.
40 is added into the queue.
10 is deleted from the queue.
Queue is not empty.