CPP Program to Implement the Operations on Circular Queue

Aim:

Write a C++ program to implement the operations on Circular Queue.

Program:

#include <iostream.h>
#define max 5
class cqueue
{
 int front,rear, cq[max];

 public:

 cqueue()
 {
 front= -1;
 rear = -1;
 }
 void insert()
 {
 int x;
 if(front==(rear+1)%max )
 {
 cout<<"Circular queue overflow "<<endl;
 return;
 }
 cout<<"enter a no \n";
 cin>>x;
 rear=(rear+1)%max;
 cq[rear]=x;
 if(front==-1) front=0;
 }
 void del()
 {
 int y;
 if(front==rear && rear==-1)
 {
 cout<<"circular queue underflow\n";
 return;
 }

 y=cq[front];
 cq[front]=0;
 if(front==rear)
 front=rear=-1;
 else
 front=(front+1)%max;
 }
void display()
{
 int i;
 if (front==rear && rear==-1)
 { 
cout<<"circular is empty \n";
 return;
 }
 cout<<"elements of circular queue are : \n";
 if(front<=rear)
 for (i = front; i <= rear; i++)
 cout<<cq[i]<<endl;
 else
 {for (i = front; i <= max-1; i++)
 cout<<cq[i]<<endl;
 for (i = 0; i <= rear; i++)
 cout<<cq[i]<<endl;
 }
 }
};
main()
{
 cqueue q;
 int ch;
 do
 {
 cout<<"\n 1:insert\n 2:del\n 3:display\n 4:exit\n choice:";
 cin>>ch;
 switch (ch)
 {
 case 1:q.insert();
 break;
 case 2:q.del();
 break;
 case 3:q.display();
 break;
 case 4:cout<<"exiting from program\n";
 break;
 default:cout<<"wrong choice\n";
 break;
 }
 }while(ch!=4);
} 

Output:

1:insert
2:del
3:display
4:exit
Choice :1
Enter a no 10
1:insert
2:del
3:display 
4:exit
Choice : 1
Enter a no 20
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 30
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 40
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 50
1:insert
2:del
3:display
4:exit
Choice : 3
Elements of circular queue are:
10
20
30
40
50
1:insert
2:del
3:display
4:exit
Choice : 1
Circular queue overflow
1:insert
2:del
3:display
4:exit 
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 3
Elements of circular queue are: 40 50
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice :2
Circular queue underflow
1:insert
2:del
3:display
4:exit
Choice :4 

Result:

Thus, implement the operations on Circular Queue was successfully executed.

Leave a Comment