Implementing a Stack using an Array in C++

 

This C++ program demonstrates how to implement a stack using an array. A stack is a LIFO (Last In First Out) data structure used in various programming scenarios.

Program Code

#include <iostream>

class Stack {
private:
    int top;
    int capacity;
    int* array;

public:
    Stack(int size) : capacity(size), top(-1) {
        array = new int[capacity];
    }

    ~Stack() {
        delete[] array;
    }

    void push(int value) {
        if (top == capacity - 1) {
            std::cout << "Stack Overflow" << std::endl;
            return;
        }
        array[++top] = value;
        std::cout << "Pushed " << value << " to stack" << std::endl;
    }

    int pop() {
        if (top == -1) {
            std::cout << "Stack Underflow" << std::endl;
            return -1;
        }
        return array[top--];
    }

    int peek() {
        if (top == -1) {
            std::cout << "Stack is empty" << std::endl;
            return -1;
        }
        return array[top];
    }

    void display() {
        if (top == -1) {
            std::cout << "Stack is empty" << std::endl;
            return;
        }
        std::cout << "Stack elements are: ";
        for (int i = top; i >= 0; i--) {
            std::cout << array[i] << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    Stack stack(5);
    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.display();

    std::cout << "Top element is: " << stack.peek() << std::endl;
    std::cout << "Popped element: " << stack.pop() << std::endl;
    stack.display();
    return 0;
}

Class and Function Documentation

  • Constructor Stack(int size): Initializes a new stack with a specified size.
  • void push(int value): Adds a value to the top of the stack. Prints an error message if the stack is full.
  • int pop(): Removes the top element of the stack and returns it. Prints an error message if the stack is empty.
  • int peek(): Returns the top element without removing it from the stack. Prints an error message if the stack is empty.
  • void display(): Displays all elements in the stack from top to bottom.

Example Usage

    Stack stack(5);
    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.display(); // Outputs the contents of the stack
    std::cout << "Top element is: " << stack.peek() << std::endl; // Outputs the top element
    std::cout << "Popped element: " << stack.pop() << std::endl; // Outputs the popped element
    stack.display(); // Outputs the remaining contents of the stack

 

Leave a Reply

Your email address will not be published. Required fields are marked *