Tuesday, July 10, 2018

Program 19


         
ARRAY IMPLEMENTATION OF STACK



Write a program to implement an ARRAY STACK.

#include < iostream . h >
#include < process . h >
#include < stdio . h >
#include < conio . h >
class Stack
 {
           int top ;
           int arr[ 10 ] ;
    public  :
           Stack ( )
            {
                    top = -1 ; //denotes stack is empty
            }
           int isFull ( )
            {
                   if( top == 9 )
                    {
                      cout << "\nStack is Full!" ;
                      getch ( ) ;
                      return 1 ;
                    }
                   else
                      return 0 ;
            }
           int isEmpty ( )
            {
                   if ( top == -1 )
                     {
                             cout << "\nStack is empty !" ;

                             getch ( ) ;
                             return 1 ;
                     }
                   else
                             return 0 ;
            }
           void Push ( int a )
            {
                   if  ( ! isFull  (  )  )
                     {
                             arr [ ++ top ] =  a ;
                             cout << "\nElement Pushed" ;
                     }
            }
           void Pop ( )
            {
                   if (  ! isEmpty  ( )  )
                             cout  << "Popped element is ::" << arr [ top -- ]  ;
            }
           void display ( )
            {

                if ( ! isEmpty ( ) )
                 {
                   cout << "\n Stack contents are ...." ;
                   for ( int i = top ;  i >= 0 ; -- i )
                    cout <<  arr [ i ] << "  " ;
                 }
            }
 } ;
void main ( )
 {
          clrscr ( ) ;
          Stack S ;
          int ch  , n ;
          while ( 1 )
           {
                   cout << "\n1.        Push an element" ;
                   cout << "\n2.        Pop an element" ;
                   cout << "\n3.        Display the stack" ;
                   cout << "\n4.        Exit" ;
                   cin   >>  ch ;
                   switch ( ch )
                    {
                             case  1  :
                                      cout << "\nEnter the element to be pushed::" ;
                                      cin  >>n ;
                                      S . Push ( n ) ;
                                      break ;
                             case  2  :      S . Pop ( ) ;           break ;
                             case  3  :       S . display ( ) ;     break ;
                             case  4  :      exit ( 0 ) ;
                    }
                   getch ( ) ;
           }
 }



No comments:

Post a Comment