Wednesday, September 13, 2017

Implementation of Circular Queue in C

ENQUEUE:


 DEQUEUE:

 #include<stdio.h>
#include<conio.h>
#define MAXSIZE 10
int rear,front,queue[MAXSIZE],data;
void enqueue();
void dequeue();
void display();
int IsEmpty();

main()
{
int choice,option=1;
front=-1,rear=-1;
while(option)
{
printf("\n 1->Enqueue 2->Dequeue 3->Display");
printf("\n Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
enqueue();
break;

case 2:
dequeue();
break;

case 3:
display();
break;

default:
printf("\n Invalid Choice");
}
printf("\n 1-->Continue   2-->Exit");
scanf("%d",&option);
}
return 0;
}

void enqueue()
{
if(IsEmpty())
{
printf("\n Enter an element to ENQUEUE:");
scanf("%d",&data);
front=rear=0;
queue[rear]=data;
printf("\n Successfully Enqueued:%d",data);
}
else if ((rear+1)%MAXSIZE==front)
{
printf("\n Sorry!!! Circular Queue is FULL!!!");
}
else
{
printf("\n Enter an element to Enqueue:");
scanf("%d",&data);
rear=(rear+1)%MAXSIZE;
queue[rear]=data;
printf("\n Successfully Enqueued:%d",data);
}
return;
}
int IsEmpty()
{
if(front==-1 && rear==-1) return 1;
else return 0;
}

void display()
{
register int i;
if(IsEmpty())
{
printf("\n Queue is Empty");
}
else  if(rear>front)
{
for(i=front;i<=rear;i++)
printf("\n%d",queue[i]);
}
else
{
for(i=front;i<=rear;i++)
printf("\n%d",queue[i]);
for(i=0;i<front;i++)
printf("\n%d",queue[i]);
}
}

void dequeue()
{
if(IsEmpty())
{
printf("\n Empty Queue");
}
else if((front!=rear) && (front>-1))
{
data=queue[front];
front=(front+1)%MAXSIZE;
printf("\n Element Dequeued successfully:%d",data);
}
else if((front==rear) && (front>-1))
{
data=queue[front];
front=rear=-1;
printf("\n Element Dequeued Successfully:%d",data);
}
return;
}


______________________________________________________
Thank You