c code for stack using array

  • cstackarray_stack
  • implement stack using array

    Write a menu-driven program to perform the following operations of a stack using an array by using suitable user-defined functions for each case. a) Check if the stack is empty b) Display the contents of the stack c) Push d) Pop

    Code

    #include <stdio.h> #include <stdlib.h> struct stack { int size; int top; int *arr; }; int isEmpty(struct stack *ptr) { if (ptr->top == -1) { return 1; } else { return 0; } } int isFull(struct stack *ptr) { if (ptr->top == ptr->size - 1) { return 1; } else { return 0; } } void push(struct stack *ptr, int val) { if (isFull(ptr)) { printf("Stack Overflow! Cannot push %d to the stack\n", val); } else { ptr->top++; ptr->arr[ptr->top] = val; } } int pop(struct stack *ptr) { if (isEmpty(ptr)) { printf("Stack Underflow! Cannot pop from the stack\n"); return -1; } else { int val = ptr->arr[ptr->top]; ptr->top--; return val; } } void display(struct stack *ptr) { printf("elements : "); int k = ptr->top; while (k != -1) { printf("%d ", ptr->arr[k]); k--; } } int main() { int c, p; struct stack *sp = (struct stack *)malloc(sizeof(struct stack)); printf("enter the size of stack : "); scanf("%d",&p); sp->size = p; sp->top = -1; sp->arr = (int *)malloc(sp->size * sizeof(int)); printf("Stack has been created successfully\n"); options: printf("\n\n1) Check if the stack is empty \n2) Display the contents of stack \n3) Push \n4) Pop\n5) exit\n"); printf("enter your choice : "); scanf("%d", &c); switch (c) { case 1: printf("Empty([1/0]-->[yes/no]): %d\n", isEmpty(sp)); goto options; break; case 2: display(sp); goto options; break; case 3: printf("enter the value to push : "); scanf("%d", &p); push(sp, p); goto options; break; case 4: printf("Popped %d from the stack\n", pop(sp)); goto options; break; case 5: exit(0); break; default: printf("invalid input\n"); goto options; break; } return 0; }