You are here

C program to implement stack data structure

Stack program in C: C program to implement stack using array.

C programming code

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int stack[100];
  5. void push();
  6. int pop();
  7. void traverse();
  8. int is_empty();
  9. int top_element();
  10. int top = 0;
  11.  
  12. int main()
  13. {
  14.   int element, choice;
  15.  
  16.   for (;;)
  17.   {
  18.     printf("Stack Operations.\n");
  19.     printf("1. Insert into stack (Push operation).\n");
  20.     printf("2. Delete from stack (Pop operation).\n");
  21.     printf("3. Print top element of stack.\n");
  22.     printf("4. Check if stack is empty.\n");
  23.     printf("5. Traverse stack.\n");
  24.     printf("6. Exit.\n");
  25.     printf("Enter your choice.\n");
  26.     scanf("%d",&choice);
  27.  
  28.     switch (choice)
  29.     {
  30.       case 1:
  31.         if (top == 5)
  32.           printf("Error: Overflow\n\n");
  33.         else {
  34.           printf("Enter a value to insert.\n");
  35.           scanf("%d", &element);
  36.           push(element);
  37.         }
  38.         break;
  39.  
  40.       case 2:
  41.         if (top == 0)
  42.           printf("Error: Underflow.\n\n");
  43.         else {
  44.           element = pop();
  45.           printf("Element removed from the stack is %d.\n", element);
  46.         }
  47.         break;
  48.  
  49.       case 3:
  50.         if (!is_empty()) {
  51.           element = top_element();
  52.           printf("Element at the top of the stack is %d\n\n", element);
  53.         }
  54.         else
  55.           printf("The stack is empty.\n\n");
  56.         break;
  57.  
  58.       case 4:
  59.         if (is_empty())
  60.           printf("The stack is empty.\n\n");
  61.         else
  62.           printf("The stack isn't empty.\n\n");
  63.         break;
  64.  
  65.       case 5:
  66.         traverse();
  67.         break;
  68.  
  69.       case 6:
  70.         exit(0);
  71.     }
  72.   }
  73. }
  74.  
  75. void push(int value) {
  76.   stack[top] = value;
  77.   top++;
  78. }
  79.  
  80. int pop() {
  81.   top--;
  82.   return stack[top];
  83. }
  84.  
  85. void traverse() {
  86.   int d;
  87.  
  88.   if (top == 0) {
  89.     printf("The stack is empty.\n\n");
  90.     return;
  91.   }
  92.  
  93.   printf("There are %d elements in the stack.\n", top);
  94.  
  95.   for (d = top - 1; d >= 0; d--)
  96.     printf("%d\n", stack[d]);
  97.   printf("\n");
  98. }
  99.  
  100. int is_empty() {
  101.   if (top == 0)
  102.     return 1;
  103.   else
  104.     return 0;
  105. }
  106.  
  107. int top_element() {
  108.   return stack[top-1];
  109. }