Header Ads Widget

Program of insert element and delete element from the circular queue.

What is circular queue:- 

Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle.

  


Why we need circular queue:-

In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we can not insert the next element even if there is a space in front of queue. So we use the circular queue to utilize the spaces.

Solution:-

#include<stdio.h>
#include<conio.h>
#define max 5
int cir_queue[max];
int rear=-1;
int front=-1;

// function for insert element into circular cir_queue

void insert()
{
int element;
if(front==(rear+1)%max)
printf("cir_queue is overflow\n");
else
{
if(front==-1)
front=0;
printf("Enter a element\n");
scanf("%d",&element);
rear=(rear+1)%max;
cir_queue[rear]=element;
}
}

// function for delete element from the cir_queue

void delete()
{
int element;
if(front==-1)
printf("cir_queue is underflow \n");
else
{
element=cir_queue[front];
printf("%d is deleted \n",element);
if(front==rear)
{
front=-1;
rear=-1;
}
else
front=(front+1)%max;
}
}

// function for display the element of the cir_queue

void display()
{
int i;
if(front==-1)
printf("cir_queue is underflow\n");
else
{
for(i=(front)%max;i<=rear%max;i++)
printf("%d ",cir_queue[i]);
}
if(front>rear)
{
for(i=0;i<=rear;i++)
printf("%d ",cir_queue[i]);
for(i=front;i<max;i++)
printf("%d ",cir_queue[i]);
}
printf("\n");
}

// Driver function

int main()
{
int ch;
printf("1. insert element\n");
printf("2. delete element\n");
printf("3. display element\n");
printf("4. exit\n");
while(1)
{
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default : printf("Wrong key\n");
}
}
return 0;
}


Output:-