Trivial C, C++ Programs.

Queues Using Arrays (Static) in C++



It does what it says. A first-in first-out structure, implement in the simplest possible way. Again, no bound checks. Sanitize your inputs please.

#include <iostream.h>
 
int *Queue, front, rear, maxSize;
 
void createQueue();
void push();
void pop();
void dispQueue();
 
int main()
{
  int choice;
  while(choice != 5)
    {
      cout<<"\n\n Enter your choice :"
	  <<"\n 1. Create an empty Queue."
	  <<"\n 2. Push an element into Queue."
	  <<"\n 3. Pop an element from Queue."
	  <<"\n 4. Display the Queue."
	  <<"\n 5. Exit the program.\n\n";
      cin>>choice;
 
      switch (choice)
	{
	case 1:
	  createQueue();
	  break;
	case 2:
	  push();
	  break;
	case 3:
	  pop();
	  break;
	case 4:
	  dispQueue();
	  break;
	case 5:
	  break;
	case 6:
	  cout<<"\n Invalid choice.";
	  break;
	}
    }
  std::cin.get();
}
 
void createQueue()
{
  cout<<"\n Enter the maximum size of Queue : ";
  cin>>maxSize;
  Queue = new int[maxSize];
  front=-1;
  rear=-1;
}
 
void push()
{
  if (rear == (maxSize-1))
    {
      cout<<"\n Overflow! No space left in Queue. Cannot push.";
 
    }
  else
    {
      rear++;
      cout<<"\n Enter the element to be pushed in Queue : ";
      cin>>Queue[rear];	
    }
}
 
void pop()
{
  if (front == rear)
    {
      cout<<"\n Underflow! Cannot pop any items because Queue is empty.";
    }
  else
    {
      cout<<"\n The element that was popped was : "<<Queue[++front];
    }
}
 
void dispQueue()
{
  if (front == rear)
    {
      cout<<"\n Queue is empty, no element to display";
    }
  else
    {
      for(int i = (front+1); i<=rear; i++)
	{
	  cout<<Queue[i];
	  if (i != rear)
	    {
	      cout<<"<--";
	    }
	}
    }
}

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">