Write a C program for Stack Implementation.

Figure: Stack Implementation

#include <stdio.h>

int stack[4];
int top = -1;

void push(int element) {
    if (top == 4 - 1) {
        printf("Stack Overflow\n");
    } else {
        stack[++top] = element;
        printf("Pushed is: %d \n", element);
    }
}

void pop() {
    if (top == -1) {
        printf("Stack Underflow\n");
    } else {
        printf("Popped is: %d \n", stack[top--]);
    }
}

int peek() {
    if (top == -1) {
        printf("Stack is empty\n");
        return -1;
    } else {
        return stack[top];
    }
}

int main() {
    //!showArray(stack)
    push(10);
    push(20);
    push(30);
    push(40);
    push(50);
    printf("Top Element is: %d\n", peek());
    pop();
    pop();
    pop();
    pop();
    pop();
    printf("Top Element is: %d\n", peek());
    return 0;
}

Pushed is: 10 
Pushed is: 20 
Pushed is: 30 
Pushed is: 40 
Stack Overflow
Top Element is: 40
Popped is: 40 
Popped is: 30 
Popped is: 20 
Popped is: 10 
Stack Underflow
Stack is empty
Top Element is:-1

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.