Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

stack in c++

#include <iostream>

using namespace std;
#define M 100 //defined the size of the stack ;

//stack class for controlling

class STACK
{
    int ara[M]; // declared an array for storing the stack elemenst
    int top; // finding the top value
public:
    //function for pushing values into the stack
    STACK() // constructor for initializing
    {
        top = 0;
    }
    void push(int n)
    {
        if(top == M) // checking if the stack is full or not
        {
            cout << "Stack is full
";
            return;
        }else // if the stack is not full, push the element
        {
            ara[top] = n;
            top++;
        }
    }
    //function for poping out elements from the stack or getting the elements
    int pop()
    {
        if(top == 0)
        {
            cout << "Stack is empty
";
            return 0;
        }else
        {
            top--;
            return ara[top];
        }
    }
    
};


int main()
{
    STACK stk1, stk2; //making two objects of type STACK
    
    //pushing elements
    for(int i = 0; i < 5; i++)
    {
        stk1.push(i);
        stk2.push(i+1);
    }
    
    //poping elements
    for(int i = 0; i < 5; i++)
    {
        cout << stk1.pop() << " ";
    }
    
    cout << "
";
    
    for(int i = 0; i < 5; i++)
    {
        cout << stk2.pop() << " ";
    }
    cout << "
";
    return 0;
}
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #stack
ADD COMMENT
Topic
Name
9+4 =