Write a C program to implement stack using an array.
#include<stdio.h> #define MAX 5 int Cur_Index = -1; void Push_Value(int*,int); int Pop_Value(int*); void Print_Values(int*); int Top_of_Stack(int*); int main() { int IntArray[5],op,val; printf("Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit\n"); scanf("%d",&op); do { switch(op) { case 1: if(Cur_Index == 4) { printf("\nStack is Full....\n"); break; } printf("\nEnter Value to Push : "); scanf("%d",&val); Push_Value(IntArray,val); break; case 2: if(Cur_Index < 0 ) { printf("\nCan not pop....\n"); break; } val = Pop_Value(IntArray); printf("\nPopped value is %d\n",val); break; case 3: val = Top_of_Stack(IntArray); printf("\nTop of Stack value is %d\n",val); break; case 4: Print_Values(IntArray); break; case 5: return 0; break; default: printf("Invalid Option....\n"); } printf("Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit\n"); scanf("%d",&op); }while(op != 5); return 0; } void Push_Value(int *p,int n) { p[++Cur_Index] = n; } int Pop_Value(int *p) { return p[Cur_Index--]; } void Print_Values(int*p) { int i; printf("\n"); for(i = 0;i <= Cur_Index;i++) { printf("%d ",p[i]); } printf("\n"); } int Top_of_Stack(int*p) { return p[Cur_Index]; }
Output
Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 1 Enter Value to Push : 10 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 1 Enter Value to Push : 20 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 3 Top of Stack value is 20 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 4 10 20 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 2 Popped value is 20 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 2 Popped value is 10 Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 2 Can not pop.... Enter Option 1] Push 2] Pop 3] Top of Stack 4] Print 5] Exit 5