Implement a stack using arrays in C

#include <stdio.h>

#include <stdlib.h>

#define MAX 100


// Array-based stack

int stack[MAX];

int top = -1;


// Push operation

void pushArray(int value) {

    if (top == MAX - 1) {

        printf("Stack Overflow (Array)\n");

        return;

    }

    stack[++top] = value;

}


// Pop operation

int popArray() {

    if (top == -1) {

        printf("Stack Underflow (Array)\n");

        return -1;

    }

    return stack[top--];

}


// Peek operation

int peekArray() {

    if (top == -1) return -1;

    return stack[top];

}


// Display stack

void displayArrayStack() {

    printf("Array Stack: ");

    for (int i = top; i >= 0; i--) {

        printf("%d ", stack[i]);

    }

    printf("\n");

}

Output:


Comments