#include <iostream>
using namespace std;
#define MAX 100 // Maximum size of the stack
// Structure to represent a stack
struct Stack {
int arr[MAX];
int top;
// Initialize stack
Stack() {
top = -1; // Stack is empty when top is -1
// Check if the stack is full
bool isFull() {
return top >= MAX - 1;
// Check if the stack is empty
bool isEmpty() {
return top < 0;
// Push an item onto the stack
void push(int item) {
if (isFull()) {
cout << "Stack Overflow! Cannot push " << item << endl;
return;
}
arr[++top] = item;
cout << "Pushed " << item << " onto the stack." << endl;
// Pop an item from the stack
int pop() {
if (isEmpty()) {
cout << "Stack Underflow! Cannot pop." << endl;
return -1; // Return -1 to indicate stack is empty
return arr[top--];
// Peek the top item of the stack
int peek() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return -1; // Return -1 to indicate stack is empty
return arr[top];
// Display the stack contents
void display() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return;
cout << "Stack elements are: ";
for (int i = 0; i <= top; i++) {
cout << arr[i] << " ";
}
cout << endl;
};
int main() {
Stack stack;
// Push items onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Display stack contents
stack.display();
// Peek the top item
cout << "Top item is: " << stack.peek() << endl;
// Pop items from the stack
cout << "Popped item: " << stack.pop() << endl;
cout << "Popped item: " << stack.pop() << endl;
// Display stack contents
stack.display();
// Try to pop from an empty stack
stack.pop();
stack.pop(); // This will show stack underflow
return 0;
}
Output
Pushed 10 onto the stack.
Pushed 20 onto the stack.
Pushed 30 onto the stack.
Stack elements are: 10 20 30
Top item is: 30
Popped item: 30
Popped item: 20
Stack elements are: 10
Stack Underflow! Cannot pop.