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 overflown”);
else
{
if(front==-1)
front=0;
printf(“Enter a elementn”);
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 underflown”);
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 elementn”);
printf(“2. delete elementn”);
printf(“3. display elementn”);
printf(“4. exitn”);
while(1)
{
printf(“enter your choicen”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default : printf(“Wrong keyn”);
}
}
return 0;
}

Output:-


Leave a Reply

Your email address will not be published.