#include <iostream>
#include <stdexcept> // For std::out_of_range exception
class Stack {
private:
int* arr; // Array to store stack elements
int top; // Index of the top element
int capacity; // Maximum number of elements stack can hold
public:
// Constructor to initialize stack
Stack(int size) {
capacity = size;
arr = new int[capacity];
top = -1;
// Destructor to clean up memory
~Stack() {
delete[] arr;
// Push an element onto the stack
void push(int value) {
if (top >= capacity - 1) {
std::cout << "Stack overflow!" << std::endl;
return;
arr[++top] = value;
std::cout << value << " pushed onto stack." << std::endl;
}
// Pop an element from the stack
void pop() {
if (top < 0) {
std::cout << "Stack underflow!" << std::endl;
return;
std::cout << arr[top--] << " popped from stack." << std::endl;
// Traverse and display all elements in the stack
void traverse() const {
if (top < 0) {
std::cout << "Stack is empty!" << std::endl;
return;
std::cout << "Stack elements: ";
for (int i = top; i >= 0; --i) {
std::cout << arr[i] << " ";
std::cout << std::endl;
};
int main() {
Stack stack(5); // Create a stack of size 5
stack.push(10);
stack.push(20);
stack.push(30);
stack.traverse();
stack.pop();
stack.traverse();
stack.pop();
stack.pop();
stack.pop(); // This will show "Stack underflow!"
return 0;
Output
10 pushed onto stack.
20 pushed onto stack.
30 pushed onto stack.
Stack elements: 30 20 10
30 popped from stack.
Stack elements: 20 10
20 popped from stack.
10 popped from stack.
Stack underflow!