Implementation of Stack Using Array: Algorithm, Operations, Code, and Examples

By Rahul Singh

Updated on Jul 04, 2026 | 10 min read | 3.93K+ views

Share:

TL;DR

  • A stack follows the Last In, First Out (LIFO) principle, where the last inserted element is removed first. 
  • Array-based stack implementation stores elements in contiguous memory, making Push, Pop, and Peek operations simple and fast. 
  • Core stack operations execute in O(1) time, making array stacks suitable for many performance-critical applications. 
  • Array-based stacks are widely used in expression evaluation, browser history, undo/redo features, function calls, and backtracking algorithms. 
  • Choosing an array-based stack works best when the maximum stack size is known and fast, predictable performance is required.

This blog explains the implementation of stack using array, including how stacks work, why arrays are commonly used to implement them, how core stack operations are performed, and how to build stack programs in C, C++, Java, and Python.

Strengthen your understanding of data structures, algorithms, and programming with upGrad's Data Science Course. Build practical skills in Python, machine learning, AI, and data analytics through hands-on projects and industry-relevant learning.

How To Implement Stack Using Array

The implementation of stack using array is straightforward because an array stores elements in contiguous memory locations. The only additional variable required is top, which keeps track of the last inserted element.

Prerequisites

Before you start, you should be comfortable with:

Stack Declaration

You need two things to declare a stack using an array:

  • An array with a fixed maximum size, often called capacity
  • A top variable initialized to -1

Initialization

At the start, the stack is empty, so top = -1. This single value tells your program everything it needs to know about the current state of the stack. If top is -1, there is nothing to pop or peek.

Step By Step Algorithm

Here is the general algorithm behind every implementation of stack using array:

  1. Create an array of fixed size and set top = -1.
  2. To push, check if the array is full. If not, increase top and store the value.
  3. To pop, check if the stack is empty. If not, read the value at top and decrease top.
  4. To peek, simply return the value at top without changing it.
  5. Repeat push and pop as needed based on your program logic.

Pseudocode

function push(value):
    if top == capacity - 1:
        print "Stack Overflow"
    else:
        top = top + 1
        array[top] = value

function pop():
    if top == -1:
        print "Stack Underflow"
    else:
        value = array[top]
        top = top - 1
        return value

function peek():
    if top == -1:
        print "Stack is empty"
    else:
        return array[top]

Flowchart

Stack Operations Using Array

Every stack program is built around five basic operations. These operations define how elements are inserted, removed, and accessed.

1. Push Operation in Stack Using Array

Push inserts a new element at the top of the stack.

Algorithm

  1. Check whether the stack is full.
  2. Increment top.
  3. Insert the element.

Example:

Push(10)
Stack
10

Next,

Push(20)

Stack becomes

20
10

Time Complexity: O(1)

2. Pop Operation in Stack Using Array

Pop removes the top element.

Algorithm

  1. Check whether the stack is empty.
  2. Store the top element.
  3. Decrement top.
  4. Return the removed value.

Example:

Before Pop

30
20
10

After Pop

20
10

Time Complexity: O(1)

Also Read: Time and Space Complexity in Data Structures: A Detailed Guide

3. Peek Operation in Stack Using Array

Peek returns the top element without removing it.

Example:

Stack
40
30
20
10

Peek returns

40

The stack remains unchanged.

Time Complexity: O(1)

4. isEmpty() Operation in Stack Using Array

The stack is empty when:

top == -1

Example: top = -1

Output
True

Otherwise

False

This check prevents stack underflow.

Time Complexity: O(1)

5. isFull() Operation in Stack Using Array

The stack is full when

top == MAX - 1

Example:

MAX = 5
top = 4

Output

True

Checking this condition prevents stack overflow.

Time Complexity: O(1)

Also Read: Stack in C: Concept, Operations, and Code Implementation

6. Display Operation

Display prints stack elements from top to bottom.

Example

Stack
40
30
20
10

Output

40
30
20
10

Time Complexity: O(n)

Dry Run Example

Consider the following sequence.

Push(10)
Push(20)
Push(30)
Peek()
Pop()
Push(40)

Execution:

Step

Stack

Top

Initial Empty

-1

Push 10 10

0

Push 20 20,10

1

Push 30 30,20,10

2

Peek 30

2

Pop 20,10

1

Push 40 40,20,10

2

Stack Operations Summary

Operation

Algorithm

Time Complexity

Push Insert at top

O(1)

Pop Remove top element

O(1)

Peek Return top element

O(1)

isEmpty() Check top == -1

O(1)

isFull() Check top == MAX-1

O(1)

Display Print all elements

O(n)

These operations form the foundation of every implementation of stack using array. Once you understand them, writing programs in C, C++, Java, and Python becomes much easier.

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree18 Months

Placement Assistance

Certification6 Months

Stack Implementation Using Array in Different Programming Languages

The implementation of stack using array follows the same logic in every programming language. The syntax changes, but the algorithm remains the same.

1. Stack Implementation Using Array In C

A C program to implement stack using array uses a simple struct or global array along with a top variable.

#include <stdio.h>
#define MAX 5

int stack[MAX];
int top = -1;

void push(int value) {
    if (top == MAX - 1) {
        printf("Stack Overflow\n");
        return;
    }
    top++;
    stack[top] = value;
}

void pop() {
    if (top == -1) {
        printf("Stack Underflow\n");
        return;
    }
    printf("Popped: %d\n", stack[top]);
    top--;
}

void peek() {
    if (top == -1) {
        printf("Stack is empty\n");
        return;
    }
    printf("Top element: %d\n", stack[top]);
}

int main() {
    push(10);
    push(20);
    push(30);
    peek();
    pop();
    peek();
    return 0;
}

Output:

Top element: 30
Popped: 30
Top element: 20

This C program to implement stack using array uses global variables for simplicity, but you can also wrap the logic in a struct if you prefer a cleaner approach. This is one of the most common ways students learn stack implementation using array in C during their first data structures course.

Also Read: Top C Language Courses in India to Master Programming Fundamentals [2026]

2. Stack Implementation Using Array in C++

Implement stack using array in C++ is very similar to C, but you get the option to use classes for a cleaner design.

#include <iostream>
using namespace std;
#define MAX 5

class Stack {
    int arr[MAX];
    int top;

public:
    Stack() { top = -1; }

    void push(int value) {
        if (top == MAX - 1) {
            cout << "Stack Overflow" << endl;
            return;
        }
        arr[++top] = value;
    }

    void pop() {
        if (top == -1) {
            cout << "Stack Underflow" << endl;
            return;
        }
        cout << "Popped: " << arr[top--] << endl;
    }

    void peek() {
        if (top == -1) {
            cout << "Stack is empty" << endl;
            return;
        }
        cout << "Top element: " << arr[top] << endl;
    }
};

int main() {
    Stack s;
    s.push(10);
    s.push(20);
    s.push(30);
    s.peek();
    s.pop();
    s.peek();
    return 0;
}

Output:

Top element: 30
Popped: 30
Top element: 20

Using a class to implement stack using array in C++ keeps your data and functions together, which makes the code easier to reuse across bigger projects. Many students prefer this version because it teaches you how to implement stack using array in C++ with proper encapsulation instead of loose global variables.

3. Stack Implementation in Java Using Array

Stack implementation in java using array usually wraps the array and top variable inside a class, similar to C++.

class Stack {
    int[] arr;
    int top;
    int capacity;

    Stack(int size) {
        arr = new int[size];
        capacity = size;
        top = -1;
    }

    void push(int value) {
        if (top == capacity - 1) {
           System.out.println("Stack Overflow");
            return;
        }
        arr[++top] = value;
    }

    void pop() {
        if (top == -1) {
           System.out.println("Stack Underflow");
            return;
        }
        System.out.println("Popped: " + arr[top--]);
    }

    void peek() {
        if (top == -1) {
           System.out.println("Stack is empty");
            return;
        }
        System.out.println("Top element: " + arr[top]);
    }
}

public class Main {
    public static void main(String[] args) {
        Stack s = new Stack(5);
        s.push(10);
        s.push(20);
        s.push(30);
        s.peek();
        s.pop();
        s.peek();
    }
}

Output:

Top element: 30
Popped: 30
Top element: 20

This approach to stack implementation in java using array works well because Java arrays already come with a fixed size, which fits naturally with how array based stacks are supposed to work. If you are building a larger project, stack implementation in java using array can also be adapted with generics so it works with any data type, not just integers.

4. Stack Implementation Using Array in Python

Python does not require you to declare an array size upfront, but you can still simulate a fixed capacity for learning purposes.

class Stack:
    def __init__(self, capacity):
        self.arr = []
        self.capacity = capacity

    def push(self, value):
        if len(self.arr) == self.capacity:
            print("Stack Overflow")
            return
        self.arr.append(value)

    def pop(self):
        if not self.arr:
            print("Stack Underflow")
            return
        print("Popped:", self.arr.pop())

    def peek(self):
        if not self.arr:
            print("Stack is empty")
            return
        print("Top element:", self.arr[-1])

s = Stack(5)
s.push(10)
s.push(20)
s.push(30)
s.peek()
s.pop()
s.peek()

Output:

Top element: 30
Popped: 30
Top element: 20

Python lists already behave like dynamic arrays, so this version of stack implementation using array in python is a bit more forgiving than C or Java, since you do not have to worry about a hard size limit unless you add one yourself.

Build a strong foundation in data structures, algorithms, machine learning, and AI with upGrad's Executive Diploma in Data Science & Artificial Intelligence from IIITB. Learn through hands-on projects, industry-focused coursework, and practical applications to prepare for today's data-driven roles.

Time and Space Complexity of Stack Implementation Using Array

The implementation of stack using array is known for its constant-time operations. Since every operation occurs at one end of the array, no element shifting is required.

Time Complexity of Stack Implementation Using Array

Every core operation in an array based stack runs in constant time. This is one of the biggest reasons the implementation of stack using array is preferred when performance matters and the maximum size is known ahead of time.

Operation

Best

Average

Worst

Push O(1) O(1) O(1)
Pop O(1) O(1) O(1)
Peek O(1) O(1) O(1)
isEmpty O(1) O(1) O(1)
isFull O(1) O(1) O(1)

Space Complexity of Stack Implementation Using Array

Space complexity for a stack implementation using array is O(n), where n is the maximum capacity you declared. This holds true even if you never fill the array completely, since the memory is reserved upfront.

Why Operations Are O(1)

Every operation only touches the top index and the element at that index. There is no loop, no shifting, and no searching involved. That is exactly why push, pop, and peek all run in constant time, regardless of how many elements are currently in the stack.

Also Read: Time and Space Complexity of Binary Search Explained

Advantages and Limitations of Stack Implementation Using Array

Like every data structure, the implementation of stack using array has strengths and weaknesses. Understanding both helps determine whether it fits a particular application.

Advantages

  • Simple to understand and quick to code
  • Fast access using direct indexing
  • No extra memory needed for pointers
  • Good cache performance due to contiguous memory

Limitations

  • Fixed size means you need to know the upper limit in advance
  • Resizing a full array can be expensive
  • Wasted memory if the array is declared larger than needed
  • Not ideal for applications where the size changes unpredictably

Fixed Size Vs Dynamic Array Stack

Feature

Fixed Stack

Dynamic Stack

Size Fixed Grows when needed
Memory Preallocated Allocated dynamically
Overflow Possible Less common
Performance Slightly faster Slight resizing overhead 

When Arrays Are the Right Choice

Arrays work best when you already know or can reasonably estimate the maximum number of elements your stack will hold, such as in expression evaluation or fixed depth recursion tracking.

Advantage

Limitation

Recommendation

Fast indexing Fixed size Use when max size is known
Low memory overhead Wasted space if oversized Estimate size carefully
Simple code Costly resizing Prefer dynamic arrays if size varies
Good cache performance No easy shrink Use for short lived stacks

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Stack Implementation Using Array Vs Linked List

Both arrays and linked lists can be used to implement stacks. The right choice depends on your application's memory requirements, flexibility, and performance expectations.

The implementation of stack using array is simple and offers fast access because elements are stored in contiguous memory. A linked list stack, on the other hand, grows dynamically and does not require a predefined size.

Feature

Array Stack

Linked List Stack

Memory allocation Upfront, contiguous Node by node, scattered
Resizing Manual or costly Automatic
Cache performance Better Weaker
Extra memory for pointers No Yes
Best use case Known size, performance critical Unknown or changing size

Common Errors and Troubleshooting

While the implementation of stack using array is simple, beginners often encounter a few common mistakes.

1. Stack Overflow

This happens when you try to push onto a stack that is already full. Always check isFull() before pushing to avoid this.

2. Stack Underflow

This happens when you try to pop or peek from an empty stack. Always check isEmpty() before these operations.

Common Implementation Mistakes

  • Forgetting to initialize top to -1
  • Not checking overflow or underflow conditions
  • Using the wrong comparison in isFull, such as top == MAX instead of top == MAX - 1
  • Mixing up push and pop logic when adapting code between languages

How To Debug Stack Programs

Print the value of top after every operation while testing. This alone catches most bugs, since almost every stack error traces back to an incorrect top value.

Also Read: Understanding Singly Linked Lists: A Comprehensive Guide

Real-Life Applications of Stack Using Array

The implementation of stack using array appears in many real software systems.

Conclusion

The implementation of stack using array is one of the most fundamental building blocks in data structures, and once you understand the logic behind push, pop, peek, isEmpty, and isFull, you can apply the same pattern across any language. 

We covered the theory, the algorithm, working code in C, C++, Java, and Python, complexity analysis, common mistakes, and where stacks show up in real applications. If you are preparing for interviews or building your fundamentals, practicing this implementation by hand is one of the best ways to lock in the concept.

Want personalized guidance on Data Science and upskilling? Speak with an expert for a free 1:1 counselling session today.   

Frequently Asked Question (FAQs)

1. What is a stack implementation?

A stack implementation is the process of creating a stack data structure using another storage mechanism, such as an array or a linked list. It supports core operations like Push, Pop, and Peek while following the Last In, First Out (LIFO) principle. The implementation method depends on the application's memory and performance requirements.

2. Can stack be implemented using ArrayList?

Yes. A stack can be implemented using an ArrayList because it supports adding and removing elements from the end efficiently. In Java, this approach offers automatic resizing, making it a flexible option when the number of elements is not known in advance.

3. How do you implement two stacks using an array?

Two stacks can share a single array by growing from opposite ends. One stack starts from the beginning, while the other starts from the last index. This approach uses available memory more efficiently and delays overflow until both stacks occupy the entire array.

4. What are the advantages of using an array for a stack?

Arrays make stack operations simple because elements are stored in contiguous memory locations. Push, Pop, and Peek operations execute quickly, and the implementation is easy to understand. This makes arrays a popular choice for learning data structures and solving interview problems.

5. What is the implementation of stack using array?

The implementation of stack using array stores elements in a fixed-size array and tracks the top element using an index variable. Each Push operation increases the top index, while each Pop operation decreases it, ensuring the stack follows the Last In, First Out (LIFO) principle.

6. How can you prevent stack overflow and underflow?

Stack overflow occurs when data is inserted into a full stack, while stack underflow happens when removing data from an empty one. Both conditions can be avoided by checking the stack's status before performing Push or Pop operations and handling invalid cases properly.

7. What does addAll() do in Java?

The addAll() method copies all elements from one collection into another collection. Although it is not a stack operation, it is useful for merging or duplicating data before processing it with stack-based algorithms in Java applications.

8. Which programming language is best for learning stack implementation?

The implementation of stack using array is easiest to learn in C because it clearly demonstrates array indexing and memory management. Java, C++, and Python follow the same stack logic, making it simple to understand the concept across different programming languages.

9. Where are array-based stacks used in real-world applications?

Array-based stacks are used in browser navigation, expression evaluation, balanced parentheses checking, undo and redo features, function call management, and graph traversal algorithms. Their constant-time operations make them suitable for applications that require fast insertion and deletion.

10. When should you choose an array instead of a linked list for a stack?

The implementation of stack using array works best when the maximum number of elements is known and high performance is required. A linked list is a better option when the stack size changes frequently and dynamic memory allocation is needed.

11. How can you improve the performance of a stack program?

You can improve stack performance by selecting an appropriate stack size, validating boundary conditions, reducing unnecessary memory operations, and testing edge cases thoroughly. Organizing stack operations into reusable functions also improves readability and simplifies maintenance.

Rahul Singh

96 articles published

Rahul Singh is an Associate Content Writer at upGrad, with a strong interest in Data Science, Machine Learning, and Artificial Intelligence. He combines technical development skills with data-driven s...

Speak with Data Science Expert

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

18 Months

IIIT Bangalore logo

The International Institute of Information Technology, Bangalore

Executive Diploma in DS & AI

360° Career Support

Executive Diploma

12 Months