All About C++

Get Pure Concepts of C++

Monday 8 February 2016

definition and explanation of stack with example of code

stack of books
Definition  of  Stack :
                                                    Stack is an abstract data type that serves as a collection of elements. Stack works with two principal operations which are push and pop.



What are push and pop in stack:
                                                   Push adds an element to the stack and Pop removes the most recently added element from the stack.

push and pop in stack
Principle of stack:
                                           LIFO is the principle of stack whose means “last in first out”. that is anything which we add first in stack can be remove/return at the last and anything which we add at the last in stack can be remove/return at first.
Examples of stack:
  • Stack of books
  • Car parking in a building

An example of stack with code using visual studio

#include<iostream>
using namespace std;
class stack
{
private:
     int top;
     int data;
     int array[5];
public:
     stack()
     {
           top = -1;
     }
     void getdata()
     {
cout<<"enter data to push in stack" << endl;
           cin >> data;
}
     void push()
     {
           if (top == 5)
                cout << "stack is full" << endl;
           else
           {
                top++;
                array[top] = data;
           }
     }
     void pop()
     {
           if (top == -1)
                cout << "stack is empty" << endl;
           else
           {
                array[top] = NULL;

                top--;
           }
     }
     void disply()
     {
           for (int i = 0; i <= top; i++)
           {
                cout << array[i] << endl;
           }
           cout << endl;
     }
};
void main()
{
     stack a;
     start:
     int r;
     char ch;
     do
     {
           cout << "integer array" << endl;
           cout << "press 1 to push element in stack & press 2 to pop it" << endl;
           cout << " press 3 to display stack" << endl;
           cin >> r;
           switch (r)
           {
           case 1:
                a.getdata();
                a.push();
                break;
           case 2:
                a.pop();
                break;
           case 3:
                a.disply();
                break;
           default:
                cout << "bad input" << endl;
                break;
           }
           cout << "do you want to process more, press y/n" << endl;
           cin >> ch;
     } while (ch != 'n');
     {
           goto start;
     }

 system("pause");

}