C++ Programs
C++ Programs (Algorithms)

Implementation of Circular Queue using Array

#include<iostream.h>
#include<conio.h>
#define size 5				//Maximum Size of Queue

int Queue[size];
int rear=-1,front=-1,item;		//rear=-1, front=-1 means Queue is Empty.
					//First Element will be stored at Zero Location.
					//(rear=0, front=0)
void main()
{
clrscr();
int choice;

void Insert();
void Delete();
void Display();

for(;;)					//Infinite Loop.
{
cout<<"\n\n\n\n---------- CIRCULAR QUEUE ---------- \n";
cout<<"\nMain Menu\n\n1. Insert\n2. Delete\n3. Display\n4. Exit\n\nEnter your choice : ";
cin>>choice;

switch(choice)
{
case 1:
Insert();
break;

case 2:
Delete();
break;

case 3:
Display();
break;

case 4:
return;					//Exit

default:
cout<<"\nWrong Input";
    }
  }
}

void Display()				//Display's the Element of Queue.
{
   int i;
   if(front==-1)
   cout<<"\nQueue is Empty\n";

   else if(front>rear)
   {
   for(i=0;i<=rear;i++)
   cout<<endl<<"Queue["<<i<<"]="<<Queue[i];
   for(i=front;i<=size-1;i++)
   cout<<endl<<"Queue["<<i<<"]="<<Queue[i];
   }

   else
   for(i=front;i<=rear;i++)
   cout<<endl<<"Queue["<<i<<"]="<<Queue[i];

   cout<<"\n\nFront : "<<front;
   cout<<"\nRear : "<<rear<<endl;
}


void Insert()				//Insert a New Element in Queue.
{
   if((front==0 && rear==size-1) || (front==rear+1))
   cout<<"\nOverflow\n";

   else
   {
      if(rear==-1 && front==-1)		//First Element in Queue.
      rear=0,front=0;

      else if(rear==size-1)		//If rear reached at End then set rear to Beginning.
      rear=0;

      else
      rear++;

   cout<<"\nEnter the Element you want to Insert : ";
   cin>>item;
   Queue[rear]=item;
   cout<<endl<<item<<" is Inserted.\n";
   Display();
   }
}


void Delete()				//Delete Element from Queue.
{
   if(front==-1)
   cout<<"\nUnderflow\n";

   else
   {
   item=Queue[front];

     if(front==rear)			//In case of Single Element in the Queue.
     front=-1,rear=-1;

     else if(front==size-1)		//If front reached at End then set front to Beginning.
     front=0;

     else
     front=front+1;

   cout<<endl<<item<<" is Deleted.\n";
   Display();
   }
}


Output :-

Circular Queue




Powered by Blog - Widget
Face Upward - Widget