Skip to main content
Engineering LibreTexts

9.3: Stack code

  • Page ID
    34685
  • Below is the code for implementing a stack using an array.

    /* C++ program to implement basic stack operations using an array */
    #include <bits/stdc++.h> 
    using namespace std; 
    #define MAX 1000 
    
    class Stack { 
           int top; 
        public: 
           int myArr[MAX]; // Maximum size of Stack 
           Stack() { top = -1; } 
           bool push(int inVal); 
           int pop(); 
           int peek(); 
           bool isEmpty(); 
    }; 
    
    // This is the push method for the Stack class
    bool Stack::push(int inVal) 
    { 
        if (top >= (MAX - 1)) { 
            cout << "Stack Overflow"; 
            return false; 
        } 
        else { 
            myArr[++top] = inVal; 
            cout << inVal << " pushed into stack\n"; 
            return true; 
        } 
    } 
    
    // This is the pop method for the Stack class
    int Stack::pop() 
    { 
        if (top < 0) { 
            cout << "Stack Underflow"; 
            return 0; 
        } 
        else { 
            int temp = myArr[top--]; 
            return temp; 
        } 
    } 
    
    // This is the peek method for the Stack class
    int Stack::peek() 
    { 
        if (isEmpty) { 
            cout << "Stack is Empty"; 
            return 0; 
        } 
        else { 
            int temp = myArr[top]; 
            return temp; 
        } 
    } 
    
    bool Stack::isEmpty() 
    { 
        return (top < 0); 
    } 
    
    // Driver program to test above functions 
    int main() 
    { 
        class Stack myStack; 
        myStack.push(10); 
        myStack.push(20); 
        myStack.push(30); 
        cout << myStack.pop() << " Popped from stack\n"; 
        return 0; 
    }