Write a program to implement operation on stack.

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<iomanip.h>
const max=4;
class stack
{
   protected:
       int stk[max];
       int top;
   public:
       stack()
       {
      top=-1;
       }
       void push()
       {
     int item;
     if(top==max-1)
     {
        cout<<"\nStack full or Over flow"<<endl;
        return;
     }
     top++;
     cout<<"\nEnter item to insert:";
     cin>>item;
     stk[top]=item;
     cout<<"\n"<<item<<"inserted."<<endl;
       }
       void pop()
       {
     int item;
     if(top==-1)
     {
       cout<<"\nStack empty or Overflow";
       return;
     }
     item = stk[top];
     top--;
     cout<<"\n"<<item<<"popped."<<endl;
     return;
       }
       void show();
};

void stack:: show()
{
   if(top==-1)
   cout<<"\nStack is empty ";
   else
     {
       cout<<"\nStack Elements:";
       for(int i=top;i>0;i++)
       cout<<setw(4)<<stk[i];
     }
}
void main()
{
    int choice;
    stack s;
    clrscr();
    do
    {
       cout<<"\n---------Stack Operations----------\n";
       cout<<"\n1.Push";
       cout<<"\n2.Pop";
       cout<<"\n3.Display";
       cout<<"\n4.Exit";
       cout<<"\nEnter your choice:";
       cin>>choice;
       switch(choice)
       {
       case 1: s.push();
          break;
       case 2: s.pop();
          break;
       case 3: s.show();
          break;
       case 4: exit(0);
       default: cout<<"Wrong Choice!!";
       }
    }while(choice!=4);

  getch();
}

No comments:

Post a Comment