C++ program for Queue
Queue
A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle.
An excellent example of a queue is a line of students in the food court.
New additions to a line made to the back of the queue, while removal (or serving) happens in the front.
In the queue only two operations are allowed insertion and deletion.
Insertion means to insert an item into the back of the queue.
Deletion means removing the front item.
The picture demonstrates the FIFO access.
The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
Program:
#include<iostream>
#include<stdlib.h>
using namespace std;
int siz,front=0,rear=0;
void insert(int q[],int n)
{
if(rear==siz)
{cout<<"Overflow ";exit(0);}
else if(rear==0)
{
rear=front=1;
q[rear]=n;
}
else
{rear++;
q[rear]=n;
}
}
void del(int q[])
{int rak;
if(front==0)
{cout<<"Underflow ";exit(0);}
rak=q[front];
if(front==rear)
{
front=rear=0;
cout<<"Queue is EMPTY";exit(0);
}
else front++;
cout<<"\nDeleted element is "<<del;
}
void display(int q[])
{
for(int r=front;r<rear;r++)
cout<<q[r]<<"<-";
cout<<q[rear];
}
main()
{
int raks,c;
char ch;
cout<<"Enter size of queue ";
cin>>siz;
int q[siz];
do
{
cout<<"Enter data to create a queue ";
cin>>raks;
insert(q,raks);
cout<<"The queue is ";
display(q);
cout<<"\nWant to insert more elements ";
cin>>ch;
}while(ch=='y'||ch=='Y');
cout<<"Enter choice \n1.Insertion \n2.Deletion ";
cin>>c;
switch(c)
{
case 1:do
{
cout<<"Enter data to insert ";
cin>>raks;
insert(q,raks);
cout<<"\nThe queue is ";
display(q);
cout<<"\nWant to insert more elements ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;
case 2:
cout<<"\n-----Deletion-----";
do{
del(q);
cout<<"\nThe queue is ";
display(q);
cout<<"\nWant to delete more ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;
default:cout<<"\nWrong choice ";
}
cout<<"\nThe queue is ";
display(q);
}
Output of the program:

very good !!!!!
ReplyDeleteThanks for your feedback!!
DeletePlz subscribe!!