About Me

My photo
Posting here few basic programs. I prefer using C++. Trying to keep it error free. Feel free to point any of them. Thanks for visiting. You can copy paste code directly from here.
Showing posts with label Stack implemented through Array. Show all posts
Showing posts with label Stack implemented through Array. Show all posts

Thursday, 22 September 2011

// Stack through array


Program to implement Pop and Push operations in Stack (stack is implemented using Array)

#include<iostream.h>
#include<conio.h>
#include<process.h>                          // to use exit() function

# define size 20                                 //for array size

int stack[size], top=-1, data;

void push()
{
     if(top < size-1)
     {
        cout<<"\n Enter data for push operation... : ";
        cin>>data;
        top+=1;                                   //same as top = top + 1
        stack[top] = data;
     }
     else
     cout<<"\n\tStack full....\n\tTry emptying values from stack...";
}

void pop()
{
    if(top = = -1)
    cout<<"\n\t Stack underflow...\n\t Try pushing elements...";
    else
    {
    data = stack[top];
    cout<<"\n\t Popped data : "<<data;
    top-=1;
    }
}

void display()
{
     for(int i=0; i<= top; ++i)
     cout<<stack[i]<<" --> ";
    
     cout<<"\n\n   Press enter to continue";
     getch();
}

int main()
{

    int choice;

    do
    {
    clrscr();
    cout<<"\n\n\n\t Welcome to Stack menu";
    cout<<"\n  Press 1 to push elements in stack";
    cout<<"\n  Press 2 to pop elements from stack";
    cout<<"\n  Press 3 to exit";
    cout<<"\n    Stack current status...: "<<top+1<<" elements present\n\n";
    cout<<"\n\n  Enter your choice (1-3)  : ";
    cin>>choice;

    switch(choice)
    {
                       case 1:
                            push();
                            display();
                          break;
                         
                       case 2:
                            pop();
                            display();
                          break;
                          
                       case 3:
                             cout<<"\n   Preparing to exit...";
                             cout<<"\n   Press enter...";
                             getch();
                             exit(0);
                          break; 
                         
                       default:
                             cout<<"\n\t Wrong selection!!! Remember (1-3)";
                          break;   
        }
     }while(choice != 3);
     getch();
    
     return 0;

}





Sample Output of the program: