C++ Program to Implement Stack Using Arrays

1. Introduction

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means the last element added to the stack is the first to be removed. In this post, we will implement a stack using arrays in C++.

In this blog post, we will learn how to implement a Stack data structure using C++ programming.

2. Program Overview

Our stack implementation will have the following operations:

1. push: Adds an item to the top of the stack.

2. pop: Removes the top item from the stack.

3. peek: Returns the top item from the stack without removing it.

4. isEmpty: Checks if the stack is empty.

5. isFull: Checks if the stack is full.

3. Code Program

#include <iostream>
#define MAX 1000

class Stack {
    int top;
public:
    int a[MAX];

    Stack() { top = -1; }
    bool push(int x);
    int pop();
    int peek();
    bool isEmpty();
    bool isFull();
};

bool Stack::push(int x) {
    if (top >= (MAX - 1)) {
        std::cout << "Stack Overflow";
        return false;
    }
    else {
        a[++top] = x;
        return true;
    }
}

int Stack::pop() {
    if (top < 0) {
        std::cout << "Stack Underflow";
        return 0;
    }
    else {
        int x = a[top--];
        return x;
    }
}

int Stack::peek() {
    if (top < 0) {
        std::cout << "Stack is Empty";
        return 0;
    }
    else {
        int x = a[top];
        return x;
    }
}

bool Stack::isEmpty() {
    return (top < 0);
}

bool Stack::isFull() {
    return (top == (MAX - 1));
}

int main() {
    class Stack s;
    s.push(10);
    s.push(20);
    s.push(30);
    std::cout << "Top element is " << s.peek() << std::endl;
    std::cout << "Popped element from stack is " << s.pop() << std::endl;
    return 0;
}

Output:

Top element is 30
Popped element from stack is 30

4. Step By Step Explanation

The Stack class encapsulates all the functions required for a basic stack operation. An array a of size MAX is used to store stack elements, and an integer top keeps track of the topmost element in the stack.

1. The push function adds an element to the top of the stack.

2. The pop function removes and returns the topmost element.

3. The peek function returns the topmost element without removing it.

4. The isEmpty function returns true if the stack is empty and false otherwise.

5. The isFull function returns true if the stack is full and false otherwise.

In the main function, we demonstrate the use of these functions by pushing three elements onto the stack, displaying the top element, and then popping one element from the stack.

Comments