Skip to main content

What I Learned Today: Implementing a Stack Using an Array in C++ (DSA)

Updated 3 min readMarkdown
Part of seriesDSA

Today, I dived into Data Structures and Algorithms by implementing a Stack using a dynamic array in C++. Here is a breakdown of what I learned, how the fundamental operations work under the hood, and my key takeaways from today's practice!

What is a Stack? (LIFO Principle)

A Stack is a linear data structure following the LIFO (Last In, First Out) principle. Think of it like a stack of plates—the last plate you put on top is the first one you take off.

In an array-based implementation, we maintain a contiguous block of memory and track the topmost element using an index variable named top.

C++ Code Implementation

#include <iostream>
using namespace std;

class Stack{
    public:
    int* arr;
    int top;
    int size;
    int t;
    Stack(int s){
        size = s;
        top = -1;
        t = -1;
        arr = new int[s];
    }

    void push(int val){
        if(top == size - 1){
            cout<<"Stack Overflow"<<endl;
        }else{
            top++;
            arr[top] = val;
            t = top;
        }
    }
    void pop(){
        if(top < 0){
            cout<<"Stack Underflow"<<endl;
        }else{
            top--;
            cout<<"element has been deleted"<<endl;
            t = top;
        }
    }
    void dis(){ //to display the data
        while(t >= 0){
            cout<<arr[t]<<endl;
            t--;
        }
    }
    void topp(){ //to print Last value
        if(top < 0){
            cout<<"Stack is Empty"<<endl;
        }else{
            cout<<arr[top]<<endl;
        }
    }
};

int main(){
    Stack st(10);
    st.push(10);
    st.push(20);
    st.push(30);
    st.push(40);
    st.push(50);
    st.dis();
    st.pop();
    st.dis();
    cout<<"last element ";st.topp();
}

Method Breakdowns

Here is how each method in my implementation functions:

  • Stack(int s): Constructor that dynamically allocates memory for an array of capacity s and initializes top to -1 (signifying that the stack is currently empty).
  • push(int val): Adds a new value onto the stack. Before inserting, it checks for Stack Overflow (top == size - 1). If space is available, it increments top and stores val at arr[top].
  • pop(): Removes the top element. It first checks for Stack Underflow (top < 0). If elements exist, it decrements top to effectively delete the top element.
  • dis(): Displays all elements currently stored in the stack from top to bottom by iterating down from index t to 0.
  • topp(): Peeks at the top element (arr[top]) without removing it, or warns that the stack is empty if top < 0.

Console Output

50
40
30
20
10
element has been deleted
40
30
20
10
last element 40

Key Takeaways / Lessons Learned

  1. LIFO Concept: The last item pushed is always the first one popped, making stacks ideal for function calls, undo mechanisms, and parsing expressions.
  2. Index Tracking with top: Setting top = -1 simplifies empty-state detection and array indexing.
  3. Boundary Handling: Always checking for Stack Overflow before pushing and Stack Underflow before popping prevents out-of-bounds memory errors.
  4. Traversal & Display: Displaying elements sequentially highlights how data is ordered from top to bottom.

About the author

No comments yet. Be the first to comment.