WikiGalaxy

Personalize

Stack Underflow and Overflow

Introduction:

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. It supports two primary operations: push (inserting an element) and pop (removing an element). Stack overflow occurs when there is an attempt to push an element onto a full stack, while stack underflow happens when there is an attempt to pop an element from an empty stack.


    // Step by step diagram of stack operations

    // Stack Overflow Example:
    // Initial Stack: [1, 2, 3]
    // Operation: Push(4)
    // Stack after operation: [1, 2, 3, 4]
    // Attempting: Push(5)
    // Error: Stack Overflow (Stack is full)

    // Stack Underflow Example:
    // Initial Stack: []
    // Attempting: Pop()
    // Error: Stack Underflow (Stack is empty)

    // Code for Stack Operations
    class Stack {
      int[] stack;
      int top;
      int capacity;

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

      void push(int x) {
        if (isFull()) {
          System.out.println("Stack Overflow");
          return;
        }
        stack[++top] = x;
      }

      int pop() {
        if (isEmpty()) {
          System.out.println("Stack Underflow");
          return -1;
        }
        return stack[top--];
      }

      boolean isFull() {
        return top == capacity - 1;
      }

      boolean isEmpty() {
        return top == -1;
      }
    }
    

Example 1: Stack Overflow

In this example, we attempt to push an element onto a full stack, which triggers a stack overflow error. The stack has a capacity of 3, and after pushing three elements, any further push operation will result in an overflow.

Example 2: Stack Underflow

Here, we try to pop an element from an empty stack, leading to a stack underflow error. The stack is initialized but no elements are added, so any pop operation will result in underflow.

Example 3: Proper Stack Operations

A stack with a size of 3 is used to demonstrate normal operations. Elements are pushed until the stack is full, and then popped until empty, showcasing typical stack behavior without errors.

Example 4: Handling Overflow Gracefully

In this scenario, the stack is managed to prevent overflow by checking if the stack is full before each push operation. This ensures that no overflow error occurs.

Example 5: Handling Underflow Gracefully

This example demonstrates how to avoid stack underflow by verifying if the stack is empty before attempting to pop an element, ensuring no underflow error occurs.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025