C++ Programming

Program to Implement the Concept of a Stack Using Class and Object

Program to Implement the Concept of a Stack Using Class and Object

#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#define MAX 5
class stack
{
   public:
               int a[MAX],i,tos,item;
               void push()
               {
                              if(tos==MAX-1)
                                             cout<<"\n The stack is full";
                              else
                              {
                                             cout<<"\n Enter an element: ";
                                                            cin>>item;
                                             tos=tos+1;
                                             a[tos]=item;
                                             cout<<"\n The element "<<item<<" is successfully inserted.";
                              }
               }
               void pop()
               {
                              if(tos==-1)
                                             cout<<"\n The stack is empty";
                              else
                              {
                                             item=a[tos];
                                             tos=tos-1;
                                             cout<<"\n The deleted item is: "<<item;
                              }
               }
               void traverse()
               {
                              int i;
                              if(tos==-1)
                                             cout<<"\n The stack is empty";
                              else
                              {
                                             cout<<"\n The elements in the stack are:";
                                             for(i=tos;i>0;i--)
                                             cout<<"\n"<<a[i];
                             }
               }
};
stack s;
void main()
{
   int c;
   do{
               cout<<"\n\n1.PUSH 2.POP 3.TRAVERSE : ";
               cin>>c;
               switch(c)
               do{
                              case 1:
                                             s.push(); break;
                              case 2:
                                             s.pop(); break;
                              case 3:
                                             s.traverse(); break;
                              default:
                                             cout<<"\nInvalid choice.";
               }while(c!=3);
               cout<<"\nContinue? (Y/N): ";
   } while ( toupper (  getche())=='Y');
}

 

Back to top button