Saturday, September 16, 2023

PUSH POP OPERATION USING C++

ARRAY REPRESENTATION OF STACK:- 

(LIFO- LAST IN FIRST OUT)

EXAMPLE:

Initially:

empty stack

top = -1

step 1: push 3

           top ++

step 2: push 5

           top++

step 3,4: push 7,9

              top + +

step 5: push 2

          stack overflow

step 6: pop

            top--

step 7,8,9: pop

                 top--

step 10: pop

             stack underflow

        

 PUSH OPERATION:

step 1: start

step 2: if (top=length-1)

            then

                print("stack overflow")

                return 

           endif

step 3: top=top+1

step 4: read n

step 5: arr[top]=n

step 6: stop

 POP OPERATION:

step 1: start

step 2: if top =-1

           then

                print("stack underflow")

                return

          endif

step 3: n=arr[top]

step 4: print n 

step 5: top=top-1

step 6: stop

  PROGRAM:

#include <iostream>
using namespace std;

#define max 30
class stack
{
    int a[max], top;

    public:
    stack()
    {
        top = -1;
    }

    void push(int n)
    {
        if(top == max-1)
        {
            cout<<"stack overflow"<<endl;
            return;
        }
        top++;
        a[top]=n;
    }

    void pop()
    {
        if(top==-1)
        {
            cout<<"stack underflow"<<endl;
            return;
        }
        int n=a[top];
        cout<<"popped element"<<a[top]<<endl;
        top--;
    }
    void display()
    {
        if(top == -1)
        {
            cout<<"empty stack"<<endl;
        }
        else
        {
            for(int i=top;i>=0;i--)
            {
                cout<<a[i]<<endl;
            }
        }
    }

    void peep()
    {
        if(top == -1)
        {
            cout<<"empty stack"<<endl;
        }
        else
        {
            cout<<a[top]<<endl;
        }
    }
};

int main()
{
    stack ob;
    while(1)
    {
        cout<<"enter 1 for push"<<endl;
        cout<<"enter 2 for pop"<<endl;
        cout<<"enter 3 for display"<<endl;
        cout<<"enter 4 for peep"<<endl;
        cout<<"enter 5 for exit"<<endl;

        int choice;
        cin>>choice;

        switch (choice)
        {
        case 1:
            cout<<"enter a value for push operation"<<endl;

             int n;

             cin>>n;

             ob.push(n);
            break;
        case 2:
            ob.pop();
            break;
        case 3:
            ob.display();
            break;
        case 4:
            ob.peep();
            break;
        case 5:
            cout<<"end of program"<<endl;
            break;
        default:
            cout<<"invalid option"<<endl;
        }
        if(choice==5)
        break;
    }
}

A physicist confesses that the electron is round and that Jesus rose from the dead. (Bengali)

একজন পদার্থবিজ্ঞানী স্বীকার করেন যে ইলেকট্রন গোলাকার এবং যিশু মৃতদের মধ্য থেকে পুনরুত্থিত হয়েছিলেন। আমার নিজের বিশ্বাস প্রমাণ দ্বারা প্রভাব...