Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10
int buffer[MAX],x=0;

void push(int val){
    if(x>=MAX) printf("Stack Overflow\n");
    else {buffer[x]=val;
      x++;}
       
}
void pop(){
    if(x==0) printf("Stack Underflow\n");
    else {printf("%d\n",buffer[x-1]);
      x--;}
}

int main() {
    int n,val;
    char operation[10];
    scanf("%d", &n);
    for (int i=0;i<n;i++){
         scanf("%s",operation);
         if(strcmp(operation,"push")==0){
            scanf("%d",&val);
            push(val);}
         else if (strcmp(operation,"pop")==0){
            pop();
         }}
         
    getchar(); // Consume newline after number

   
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow