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:
All courses
Certifications
More
By Rahul Singh
Updated on Jul 04, 2026 | 10 min read | 3.93K+ views
Share:
Table of Contents
TL;DR
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.
Popular Data Science Programs
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.
Before you start, you should be comfortable with:
You need two things to declare a stack using an array:
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.
Here is the general algorithm behind every implementation of stack using array:
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]
Every stack program is built around five basic operations. These operations define how elements are inserted, removed, and accessed.
Push inserts a new element at the top of the stack.
Example:
Push(10)
Stack
10
Next,
Push(20)
Stack becomes
20
10
Time Complexity: O(1)
Pop removes the top element.
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
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)
The stack is empty when:
top == -1
Example: top = -1
Output
True
Otherwise
False
This check prevents stack underflow.
Time Complexity: O(1)
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
Display prints stack elements from top to bottom.
Example
Stack
40
30
20
10
Output
40
30
20
10
Time Complexity: O(n)
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 |
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
The implementation of stack using array follows the same logic in every programming language. The syntax changes, but the algorithm remains the same.
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]
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.
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.
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.
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.
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 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
Like every data structure, the implementation of stack using array has strengths and weaknesses. Understanding both helps determine whether it fits a particular application.
Feature |
Fixed Stack |
Dynamic Stack |
| Size | Fixed | Grows when needed |
| Memory | Preallocated | Allocated dynamically |
| Overflow | Possible | Less common |
| Performance | Slightly faster | Slight resizing overhead |
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
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 |
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.
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
The implementation of stack using array appears in many real software systems.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources