#include <stdio.h>
#include <stdlib.h>

#define MAX 5  

int stack[MAX];
int top = -1;


void push() {
    int value;
    if (top == MAX - 1) {
        printf("Stack Overflow! Cannot push more elements.\n");
        return;
    }

    printf("Enter the value to push: ");
    if (scanf("%d", &value) != 1) {
        printf("Invalid input! Please enter an integer.\n");
        while (getchar() != '\n'); 
        return;
    }

    stack[++top] = value;
    printf("%d pushed to stack.\n", value);
}


void pop() {
    if (top == -1) {
        printf("Stack Underflow! Stack is empty.\n");
        return;
    }

    printf("%d popped from stack.\n", stack[top--]);
}


void display() {
    if (top == -1) {
        printf("Stack is empty.\n");
        return;
    }

    printf("Stack elements (top to bottom): ");
    for (int i = top; i >= 0; i--)
        printf("%d ", stack[i]);
    printf("\n");
}

int main() {
    int choice;

    printf("=== Stack Implementation in C ===\n");
    while (1) {
        printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
        printf("Enter your choice: ");

        if (scanf("%d", &choice) != 1) {
            printf("Invalid input! Please enter a number between 1-4.\n");
            while (getchar() != '\n'); 
            continue;
        }

        switch (choice) {
            case 1: push(); break;
            case 2: pop(); break;
            case 3: display(); break;
            case 4: printf("Exiting program...\n"); exit(0);
            default: printf("Invalid choice! Enter a number between 1-4.\n");
        }
    }

    return 0;
}