Implement Stack Using Array with Push and Pop Operations

Code

#include <stdio.h>
#include <string.h>

#define MAX 10  // Fixed stack size

void process_stack(int n) {
    int stack[MAX];   // static array
    int top = -1;     // empty stack indicator

    char operation[20];  // buffer to read each operation
    int value;

    for (int i = 0; i < n; i++) {
        fgets(operation, sizeof(operation), stdin);
        
        if (sscanf(operation, "push %d", &value) == 1) {
            // Push operation
            if (top >= MAX - 1) {
                printf("Stack Overflow\n");
            } else {
                top++;
                stack[top] = value;
            }
        } 
        else if (strncmp(operation, "pop", 3) == 0) {
            // Pop operation
            if (top < 0) {
                printf("Stack Underflow\n");
            } else {
                printf("%d\n", stack[top]);
                top--;
            }
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    getchar(); // Consume newline after number

    process_stack(n);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow