stack code!

Category: Education By shahruhban01 on 19 Oct 2024


#include <stdio.h>


#define MAX_SIZE 100

// Global variable to represent the top of the stack
int top = -1;

// Function to check if the stack is empty
int isEmpty() {
    return top == -1;
}

// Function to check if the stack is full
int isFull() {
    return top == MAX_SIZE - 1;
}

// Function to push an element onto the stack
void push(int value, int stk[]) {
    if (isFull()) {
        printf("Stack is full. Cannot push %d.\n", value);
        return;
    }
    stk[++top] = value;
    printf("%d pushed onto the stack.\n", value);
}

// Function to pop an element from the stack
int pop(int stk[]) {
    if (isEmpty()) {
        printf("Stack is empty. Cannot pop.\n");
        return -1;
    }
    int value = stk[top--];
    printf("%d popped from the stack.\n", value);
    return value;
}

// Function to print the stack
void printStack(int stk[]) {
    if (isEmpty()) {
        printf("Stack is empty.\n");
        return;
    }
    printf("Stack: ");
    for (int i = 0; i <= top; i++) {
        printf("%d ", stk[i]);
    }
    printf("\n");
}

int main() {
    int stk[MAX_SIZE]; // Local stack array

    push(10, stk);
    push(20, stk);
    push(30, stk);
    printStack(stk);

    pop(stk);
    printStack(stk);

    return 0;
}