Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Implement Stack using Array
Next article icon

Implement Stack using Array

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Stack is a linear data structure which follows LIFO principle. To implement a stack using an array, initialize an array and treat its end as the stack’s top. Implement push (add to end), pop (remove from end), and peek (check end) operations, handling cases for an empty or full stack.

Step-by-step approach:

  1. Initialize an array to represent the stack.
  2. Use the end of the array to represent the top of the stack.
  3. Implement push (add to end), pop (remove from the end), and peek (check end) operations, ensuring to handle empty and full stack conditions.

Here are the following operations of implement stack using array:

Push Operation in Stack:

Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.

  • Before pushing the element to the stack, we check if the stack is full .
  • If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element to the stack.
  • Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at top position .
  • The elements can be pushed into the stack till we reach the capacity of the stack.

Pop Operation in Stack:

Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.

  • Before popping the element from the stack, we check if the stack is empty .
  • If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element from the stack.
  • Otherwise, we store the value at top, decrement the value of top by 1 (top = top – 1) and return the stored top value.


Top or Peek Operation in Stack:

Returns the top element of the stack.

  • Before returning the top element from the stack, we check if the stack is empty.
  • If the stack is empty (top == -1), we simply print “Stack is empty”.
  • Otherwise, we return the element stored at index = top .

isEmpty Operation in Stack:

Returns true if the stack is empty, else false.=

  • Check for the value of top in stack.
  • If (top == -1) , then the stack is empty so return true .
  • Otherwise, the stack is not empty so return false .

isFull Operation in Stack :

Returns true if the stack is full, else false.

  • Check for the value of top in stack.
  • If (top == capacity-1), then the stack is full so return true .
  • Otherwise, the stack is not full so return false.

Implementation using Fixed Sized Array

In this implementation, we use a fixed sized array. We take capacity as argument when we create a stack. We create an array with size equal to given capacity. If number of elements go beyond capacity, we throw an overflow error.

C++
// C++ program to create a stack with // given capacity #include <bits/stdc++.h> using namespace std;   class Stack {      int top, cap;      int *a;   public:      Stack(int cap) {          this->cap = cap;          top = -1;          a = new int[cap];      }       ~Stack() {          delete[] a;      }       bool push(int x) {          if (top >= cap - 1) {              cout << "Stack Overflow\n";              return false;          }          a[++top] = x;          return true;      }       int pop() {          if (top < 0) {              cout << "Stack Underflow\n";              return 0;          }          return a[top--];      }       int peek() {          if (top < 0) {              cout << "Stack is Empty\n";              return 0;          }          return a[top];      }       bool isEmpty() {          return top < 0;      }  };   int main() {      Stack s(5);      s.push(10);      s.push(20);      s.push(30);      cout << s.pop() << " popped from stack\n";       cout << "Top element is: " << s.peek() << endl;       cout << "Elements present in stack: ";      while (!s.isEmpty()) {          cout << s.peek() << " ";          s.pop();      }       return 0;  } 
C
// C program to create a stack with given capacity #include <stdio.h> #include <stdlib.h>  struct Stack {     int top, cap;     int *a; };  struct Stack* createStack(int cap) {     struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));     stack->cap = cap;     stack->top = -1;     stack->a = (int*)malloc(cap * sizeof(int));     return stack; }  void deleteStack(struct Stack* stack) {     free(stack->a);     free(stack); }  int isFull(struct Stack* stack) {     return stack->top >= stack->cap - 1; }  int isEmpty(struct Stack* stack) {     return stack->top < 0; }  int push(struct Stack* stack, int x) {     if (isFull(stack)) {         printf("Stack Overflow\n");         return 0;     }     stack->a[++stack->top] = x;     return 1; }  int pop(struct Stack* stack) {     if (isEmpty(stack)) {         printf("Stack Underflow\n");         return 0;     }     return stack->a[stack->top--]; }  int peek(struct Stack* stack) {     if (isEmpty(stack)) {         printf("Stack is Empty\n");         return 0;     }     return stack->a[stack->top]; }  int main() {     struct Stack* s = createStack(5);     push(s, 10);     push(s, 20);     push(s, 30);     printf("%d popped from stack\n", pop(s));      printf("Top element is: %d\n", peek(s));      printf("Elements present in stack: ");     while (!isEmpty(s)) {         printf("%d ", peek(s));         pop(s);     }      deleteStack(s);     return 0; } 
Java
// Java program to create a stack with given capacity class Stack {      int top, cap;      int[] a;       public Stack(int cap) {          this.cap = cap;          top = -1;          a = new int[cap];      }       public boolean push(int x) {          if (top >= cap - 1) {              System.out.println("Stack Overflow");              return false;          }          a[++top] = x;          return true;      }       public int pop() {          if (top < 0) {              System.out.println("Stack Underflow");              return 0;          }          return a[top--];      }       public int peek() {          if (top < 0) {              System.out.println("Stack is Empty");              return 0;          }          return a[top];      }       public boolean isEmpty() {          return top < 0;      }  }   public class Main {      public static void main(String[] args) {          Stack s = new Stack(5);          s.push(10);          s.push(20);          s.push(30);          System.out.println(s.pop() + " popped from stack");           System.out.println("Top element is: " + s.peek());           System.out.print("Elements present in stack: ");          while (!s.isEmpty()) {              System.out.print(s.peek() + " ");              s.pop();          }      }  } 
Python
# Create a stack with given capacity class Stack:     def __init__(self, cap):         self.cap = cap         self.top = -1         self.a = [0] * cap      def push(self, x):         if self.top >= self.cap - 1:             print("Stack Overflow")             return False         self.top += 1         self.a[self.top] = x         return True      def pop(self):         if self.top < 0:             print("Stack Underflow")             return 0         popped = self.a[self.top]         self.top -= 1         return popped      def peek(self):         if self.top < 0:             print("Stack is Empty")             return 0         return self.a[self.top]      def is_empty(self):         return self.top < 0  s = Stack(5) s.push(10) s.push(20) s.push(30) print(s.pop(), "popped from stack")  print("Top element is:", s.peek())  print("Elements present in stack:", end=" ") while not s.is_empty():     print(s.peek(), end=" ")     s.pop() 
C#
// Create a stack with given capacity using System;  class Stack {     private int top, cap;     private int[] a;      public Stack(int cap) {         this.cap = cap;         top = -1;         a = new int[cap];     }      public bool Push(int x) {         if (top >= cap - 1) {             Console.WriteLine("Stack Overflow");             return false;         }         a[++top] = x;         return true;     }      public int Pop() {         if (top < 0) {             Console.WriteLine("Stack Underflow");             return 0;         }         return a[top--];     }      public int Peek() {         if (top < 0) {             Console.WriteLine("Stack is Empty");             return 0;         }         return a[top];     }      public bool IsEmpty() {         return top < 0;     } }  class Program {     static void Main() {         Stack s = new Stack(5);         s.Push(10);         s.Push(20);         s.Push(30);         Console.WriteLine(s.Pop() + " popped from stack");          Console.WriteLine("Top element is: " + s.Peek());          Console.Write("Elements present in stack: ");         while (!s.IsEmpty()) {             Console.Write(s.Peek() + " ");             s.Pop();         }     } } 
JavaScript
// Create a stack with given capacity class Stack {     constructor(cap) {         this.cap = cap;         this.top = -1;         this.a = new Array(cap);     }      push(x) {         if (this.top >= this.cap - 1) {             console.log("Stack Overflow");             return false;         }         this.a[++this.top] = x;         return true;     }      pop() {         if (this.top < 0) {             console.log("Stack Underflow");             return 0;         }         return this.a[this.top--];     }      peek() {         if (this.top < 0) {             console.log("Stack is Empty");             return 0;         }         return this.a[this.top];     }      isEmpty() {         return this.top < 0;     } }  let s = new Stack(5); s.push(10); s.push(20); s.push(30); console.log(s.pop() + " popped from stack");  console.log("Top element is:", s.peek());  console.log("Elements present in stack:"); while (!s.isEmpty()) {     console.log(s.peek() + " ");     s.pop(); } 

Output
30 popped from stack Top element is: 20 Elements present in stack: 20 10 

Implementation using Dynamic Sized Array

In this implementation, we use a dynamic sized array like vector in C++, ArrayList in Java, List in Python and Array in JavaScript. This is a simpler implementation but less efficient compared to the previous one if we know capacity in advance.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<int> s;      // Push elements     s.push_back(10);     s.push_back(20);     s.push_back(30);      // Pop and print the top element     cout << s.back() << " popped from stack\n";     s.pop_back();      // Peek at the top element     cout << "Top element is: " << s.back() << endl;      // Print all elements in the stack     cout << "Elements present in stack: ";     while (!s.empty()) {         cout << s.back() << " ";         s.pop_back();     }      return 0; } 
Java
import java.util.ArrayList;  public class Main {     public static void main(String[] args) {         ArrayList<Integer> s = new ArrayList<>();          // Push elements         s.add(10);         s.add(20);         s.add(30);          // Pop and print the top element         System.out.println(s.get(s.size() - 1) + " popped from stack");         s.remove(s.size() - 1);          // Peek at the top element         System.out.println("Top element is: " + s.get(s.size() - 1));          // Print all elements in the stack         System.out.print("Elements present in stack: ");         while (!s.isEmpty()) {             System.out.print(s.get(s.size() - 1) + " ");             s.remove(s.size() - 1);         }     } } 
Python
s = []  # Push elements s.append(10) s.append(20) s.append(30)  # Pop and print the top element print(f'{s[-1]} popped from stack') s.pop()  # Peek at the top element print(f'Top element is: {s[-1]}')  # Print all elements in the stack print('Elements present in stack: ', end='') while s:     print(s.pop(), end=' ') 
C#
using System; using System.Collections.Generic;  class GfG {     static void Main() {         Stack<int> s = new Stack<int>();          // Push elements         s.Push(10);         s.Push(20);         s.Push(30);          // Pop and print the top element         Console.WriteLine(s.Peek() + " popped from stack");         s.Pop();          // Peek at the top element         Console.WriteLine("Top element is: " + s.Peek());          // Print all elements in the stack         Console.WriteLine("Elements present in stack: ");         while (s.Count > 0) {             Console.Write(s.Pop() + " ");         }     } } 
JavaScript
// Using an array to simulate stack behavior let s = [];  // Push elements s.push(10); s.push(20); s.push(30);  // Pop and print the top element console.log(s[s.length - 1] + " popped from stack"); s.pop();  // Peek at the top element console.log("Top element is: " + s[s.length - 1]);  // Print all elements in the stack console.log("Elements present in stack: "); while (s.length > 0) {     console.log(s[s.length - 1] + " ");     s.pop(); } 


Comparison of the two Implementations

  • The first implementation should be preferred if we know capacity or have a close upper bound on number of elements.
  • The second one is simple and has amortized (average over n operations) time complexities as O(1) for push and pop. However it can have a particular push and pop very costly.

Complexity Analysis:

  • Time Complexity:
    • push: O(1)
    • pop: O(1)
    • peek: O(1)
    • is_empty: O(1)
    • is_full: O(1)
  • Auxiliary Space: O(n), where n is the number of items in the stack.

Advantages of Array Implementation:

  • Easy to implement.
  • Memory is saved as pointers are not involved.

Disadvantages of Array Implementation:

  • It is not dynamic i.e., it doesn’t grow and shrink depending on needs at runtime. [But in case of dynamic sized arrays like vector in C++, list in Python, ArrayList in Java, stacks can grow and shrink with array implementation as well]. But with dynamic sized arrays, we get amortized time complexity as O(1), not the worst case. If we use linked list, we get worst case time complexities as O(1).
  • The total size of the stack must be defined beforehand.

Next Article
Implement Stack using Array

C

code_r
Improve
Article Tags :
  • Stack
  • DSA
  • Data Structures-Stack
Practice Tags :
  • Stack

Similar Reads

    Implement Arrays in different Programming Languages
    Arrays are one of the basic data structures that should be learnt by every programmer. Arrays stores a collection of elements, each identified by an index or a key. They provide a way to organize and access a fixed-size sequential collection of elements of the same type. In this article, we will lea
    5 min read
    One Dimensional Arrays in C
    In C, an array is a collection of elements of the same type stored in contiguous memory locations. This organization allows efficient access to elements using their index. Arrays can also be of different types depending upon the direction/dimension they can store the elements. It can be 1D, 2D, 3D,
    5 min read
    Arrays and Strings in C++
    Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection
    5 min read
    One Dimensional Arrays in C++
    One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its posi
    6 min read
    Practice questions on Arrays
    In this article, we will discuss some important concepts related to arrays and problems based on that. Before understanding this, you should have basic idea about Arrays.Type 1. Based on array declaration - These are few key points on array declaration: A single dimensional array can be declared as
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences