Stack Code Example C++ Programming


 
#include<iostream>
using namespace std;

int top=-1;
int stack[5];
int input, i;
bool isRunning=true;

void push(){
   if(top==4)
          cout<<"Stack is full."<<endl;
   else{
          top++;
          cout<<"Input value:";
          cin>>stack[top];
   }
}

void pop(){
   if(top==-1)
          cout<<"Stack is empty."<<endl;
   else{
          cout<<"Stack removed. Success!."<<endl;
          top--;
   }
}

void show(){
   if(top==-1)
          cout<<"Stack is empty."<<endl;
   else{
          cout<<endl<<"Stack size is "<<top+1<<endl;
          cout<<"Stack data : ";
          for(i=0;i<=top;i++)
                 cout<<stack[i]<<"\t";
          cout<<endl;
   }
}

int main(){
   do{
          cout<<endl;
          cout<<"===========Menu==========="<<endl;
          cout<<"1. Add"<<endl;
          cout<<"2. Remove"<<endl;
          cout<<"3. Show"<<endl;
          cout<<"4. Exit"<<endl;
          cout<<"Select option: ";
          cin>>input;
          switch(input){
          case 1:
                 push();
                 break;
          case 2:
                 pop();
                 break;
          case 3:
                 show();
                 break;
          case 4:
                 isRunning=false;
                 break;
          default:
                 cout<<"Invalid option."<<endl;
          }
   }while(isRunning);

   return 0;

}