Skip to main content
Engineering LibreTexts

9.3: Stack code

  • Page ID
    34685
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)

    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; 
    } 
    

    9.3: Stack code is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?