C++ Program to implement a Queue using array

C++ Program to implement a Queue using array.

/**************************************************************	
	Author: Arun Vishnu M V
	Web: www.arunmvishnu.com
	Description: C++ Program to implement a Queue using array.
***************************************************************/
#include<conio.h>   	
#include<iostream.h> 
#include<process.h>  
 
# define MAX_SIZE 150
 
class queues
{
	int front,rear;
	int queue[MAX_SIZE];
	public:
      queues()	// Constructor
		{
			front=(-1);
			rear=(-1);
		}
		void insert_rear(int);
		void delete_front();
		void display();
};
 
void queues::insert_rear(int item)
{
	if((front==0 && rear==MAX_SIZE) || (front==(rear+1)))
	{
		cout<<"Queue is full!\nOverflow";
		getch();
		exit(0);
	}
	else
	{
		if(front==(-1) && rear==(-1))
		{
			rear=0;
			front=0;
		}
		else if(front!=0 && rear==MAX_SIZE)
			rear=0;
		else
			rear=rear+1;
		queue[rear]=item;
	}
}
 
void queues::delete_front()
{
	if(front==(-1) && rear==(-1))
	{
		cout<<"Queue is empty!\nUnderflow";
		return;
	}
	else
	{
		if(front==rear)
			front=rear=(-1);
		else if(front==MAX_SIZE && rear==MAX_SIZE)
				front=0;
		else
			front=front+1;
	}
	cout<<"\nItem deleted.";
   getch();
}
 
void queues:: display()
{
	int ptr;
	if(front==0 && rear==0)
	{
		cout<<"Queue is empty";
		getch();
		return;
	}
	cout<<"\nThe queue is\n";
	if(front<=MAX_SIZE && rear<=front)
	{
		for(ptr=front;ptr<MAX_SIZE;ptr++)
			cout<<queue[ptr]<<"\n";
		for(ptr=0;ptr<=rear;ptr++)
			cout<<queue[ptr]<<"\n";
	}
	else
		for(ptr=front;ptr<=rear;ptr++)
					cout<<queue[ptr]<<"    ";
}
 
 
int main()
{
	clrscr();
	int length,i,element,choice;
	queues q1;
	while(1)
	{
		clrscr();
		cout<<"1: Insert an item.\n2: Delete an item.";
		cout<<"\n3: Display elements\n4: Exit";
		cout<<"\nEnter your choice: ";
		cin>>choice;
		switch(choice)
		{
			case 1:
				cout<<"How many elements are in the queue: ";
				cin>>length;
				cout<<"Enter "<<length<<" elements: ";
				for(i=0;i<length;i++)
				{
					cin>>element;
					q1.insert_rear(element);
				}
				q1.display();
				getch();
				break;
			case 2:
				q1.delete_front();
				q1.display();
				getch();
				break;
			case 3:
				q1.display();
				getch();
				break;
			case 4:
				exit(0);
				break;
			default:
				cout<<"Please re-enter tour choice.";
				getch();
				break;
		 }
	}
	getch();
	return(0);
}
 
//---------------------- END--------------------

You may also like...

3 Responses

  1. armaan roy says:

    u helped me a lot bro..

  2. Nitesh says:

    When you are giving a always true condition to while loop by writing while(1) why does it gives a warning unreachable code…

  3. Muntaj says:

    tQ so much bro……

Leave a Reply

Your email address will not be published. Required fields are marked *