Basic Stack Implementation with Push and Pop Operations in C++

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

The stack will support two main operations:
1. **Push** - Add an element to the top of the stack.
2. **Pop** - Remove the top element from the stack.

The program includes basic boundary checks to ensure you do not exceed the stack's capacity or attempt to pop from an empty stack. This example is useful to understand how stacks work internally and is a foundational concept in many computer science problems.

Group

Data Structures: Stacks, Queues in C++

Objective

1. Define a fixed-size array to act as the stack storage.
2. Use a variable to keep track of the top of the stack.
3. Implement a function to push an element onto the stack, checking for overflow.
4. Implement a function to pop an element from the stack, checking for underflow.
5. Allow the user to interact with the stack using a simple menu.

Implement a basic stack with insertion (push) and deletion (pop) operations.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include input/output stream library

using namespace std;

#define MAX 5  // Define maximum size of the stack

// Stack class definition
class Stack {
private:
    int arr[MAX];  // Array to store stack elements
    int top;       // Index of the top element

public:
    // Constructor to initialize stack
    Stack() {
        top = -1;  // Stack is empty initially
    }

    // Function to add an element to the stack
    void push(int value) {
        if (top >= MAX - 1) {
            cout << "Stack Overflow. Cannot push " << value << endl;
        } else {
            top++;  // Move top index up
            arr[top] = value;  // Store value at new top
            cout << "Pushed " << value << " onto the stack." << endl;
        }
    }

    // Function to remove an element from the stack
    void pop() {
        if (top < 0) {
            cout << "Stack Underflow. Nothing to pop." << endl;
        } else {
            cout << "Popped " << arr[top] << " from the stack." << endl;
            top--;  // Decrease top index
        }
    }

    // Function to display current stack elements
    void display() {
        if (top < 0) {
            cout << "Stack is empty." << endl;
        } else {
            cout << "Stack contents: ";
            for (int i = 0; i <= top; i++) {
                cout << arr[i] << " ";
            }
            cout << endl;
        }
    }
};

int main() {
    Stack s;  // Create a Stack object
    int choice, value;

    // Loop to show menu and perform stack operations
    do {
        cout << "\nStack Operations Menu:\n";
        cout << "1. Push\n";
        cout << "2. Pop\n";
        cout << "3. Display Stack\n";
        cout << "4. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                cout << "Enter value to push: ";
                cin >> value;
                s.push(value);  // Call push function
                break;
            case 2:
                s.pop();  // Call pop function
                break;
            case 3:
                s.display();  // Call display function
                break;
            case 4:
                cout << "Exiting program." << endl;
                break;
            default:
                cout << "Invalid choice. Please try again." << endl;
        }
    } while (choice != 4);  // Continue until user chooses to exit

    return 0;  // End of program
}

 Output

Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 1
Enter value to push: 10
Pushed 10 onto the stack.

Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 1
Enter value to push: 20
Pushed 20 onto the stack.

Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 3
Stack contents: 10 20

Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 2
Popped 20 from the stack.

Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 4
Exiting program.

Share this C++ Exercise


More C++ Programming Exercises of Data Structures: Stacks, Queues in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.