Enqueue and Dequeue Operation

Enqueue Operation

Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
  • Step 1 − Check if the queue is full.
  • Step 2 − If the queue is full, produce overflow error and exit.
  • Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
  • Step 4 − Add data element to the queue location, where the rear is pointing.
  • Step 5 − return success
   Algorithm
   if queue is full
      return overflow
   endif
   
   rear ← rear + 1
   queue[rear] ← data
   return true
   stop
 
 
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation −
  • Step 1 − Check if the queue is empty.
  • Step 2 − If the queue is empty, produce underflow error and exit.
  • Step 3 − If the queue is not empty, access the data where front is pointing.
  • Step 4 − Increment front pointer to point to the next available data element.
  • Step 5 − Return success.
Algorithm 
 if queue is empty
      return underflow
   end if

   data = queue[front]
   front  front + 1
   return true 
   stop. 
 
Source Code: #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define size 20
int rear=-1,front=-1,j=0;
int Queue[size];
void enqueue()
{
 int num,i;
 if(rear>=(size-1))
 {
 printf("Queue is full and exit");
 exit(0);
 }
 else
 {
 //printf("\nHow many number u want to insert on queue:");
 //scanf("%d",&num);
 printf("Enter single number to insert on queue:");
 scanf("%d",&num);
 if(front==-1)
 {
  rear=rear+1;
  front=front+1;
  Queue[rear]=num;
 }
 else
 {
 rear=rear+1;
 Queue[rear]=num;
 }
 printf("At %d position %d is written",rear,Queue[rear]);
 }
 
}
void dequeue()
{ 
int queue_item;
if(front!=-1)
{
 if(front==rear)
 {
  Queue[front]='\0';
  front=0;
  }
  else
  {
   Queue[front]='\0';
  }
    queue_item=Queue[front];
    printf("Deleted element from queue is %d Position\n",j);
 front=front+1;
 j++;
}
else
{
 printf("Queue is underflow and exit\n");
 exit(0); 
} 
}
void display()
{
int i;
    if(rear!=-1)
    {
 for(i=0;i<=rear;i++)
 {
  printf("%d -position : %d\n",i,Queue[i]);
 }
}
else
{
 printf("There is no more element on Queue\n");
}
}
int main()
{
int option;
a:
printf("\nEnter as following instrucrion:\n");
printf("1 : Enqueue opertion\n");
printf("2 : Dequeue operation\n");
printf("3 : Display \n");
printf("4 : Exit\n ");
scanf("%d",&option);
switch(option)
{
 case 1:
  enqueue();
  goto a;
  break;
  
 case 2:
     dequeue();
     goto a;
  break;
 case 3:
     display();
     goto a;
  break;
 case 4:
     exit(0);
  break;
 default:
 printf("Invalid input");
 break; 
} 
}