0
1.8kviews
Write a program to implement a queue using an array.
1 Answer
written 8.6 years ago by |
Program:
#include<iostream>
#include<conio.h>
using namespace std;
class Queue
{
int arrQueue[10];
int rear,front;
public:
Queue()
{
rears=-1;
front=-1;
}
//This function is used to insert an element in queue
void insert(int el)
{
if(isFull())
{
cout <<"Queue is full!";
front=rear=-1;
return;
}
arrQueue[++rear]=el;
if(front==-1)
front = 0;
cout <<"Element inserted is:"<<" "<<el;
}
//This function is used to check if queue is empty or not
bool isEmpty()
{
if(front==-1)
return true;
else
return false;
}
//This function is used to check if queue is full or not
bool isFull()
{
int size=sizeof(arrQueue)/sizeof(*arrQueue);
if(rear == size-1)
{
return true;
}
else
{
return false;
}
}
//This function is used to remove an element from queue
void remove()
{
if(isEmpty())
{
cout <<"No elements in queue";
return;
}
int x=arrQueue[front];
front++;
cout <<"Deleted element is:"<<" "<<x;
}
//This function is used to display the elements of a queue
void display()
{
if(isEmpty())
{
cout <<"No elements in queue";
return;
}
for(int i=front;i<=rear;i++)
cout <<arrQueue[i]<<" ";
}
};
void main()
{
int ch;
Queue queue;
while(1)
{
cout <<"\n1.Insert 2.Remove 3.Display 4.Exit\nEnter ur choice";
cin >> ch;
switch(ch)
{
case 1: cout <<"Enter the element you want to insert";
cin >> ch;
queue.insert(ch);
break;
case 2: queue.remove();
break;
case 3: queue.display();
break;
case 4: exit(0);
}
}
}
Sample Output:
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to insert 11
Element inserted is: 11
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to insert 12
Element inserted is: 12
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to insert 12
Element inserted is: 12
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to insert 13
Element inserted is: 13
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 1
Enter the element you want to insert 14
Element inserted is: 14
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 3
11 12 12 13 14
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 2
Deleted element is: 11
1.Insert 2.Remove 3.Display 4.Exit
Enter ur choice 3
12 12 13 14
1.Insert 2.Remove 3.Display 4.Exit