kebria

Implementing Stack in C. Using Array

Jun 23rd, 2021
720
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Implementing Stack in C. Using Array */
  2. #include <stdio.h>
  3. #define CAPACITY 3
  4. int stack[CAPACITY];
  5. int top = -1;
  6.  
  7. void push(int x)
  8. {
  9.     if (top < CAPACITY)
  10.     {
  11.         top = top + 1;
  12.         stack[top] = x;
  13.         printf("Successfully added item: %d\n", x);
  14.     }
  15.     else
  16.         printf("No space for %d\n", x);
  17. }
  18.  
  19. int pop()
  20. {
  21.     if (top >= 0)
  22.     {
  23.         int val = stack[top];
  24.         top = top - 1;
  25.         return val;
  26.     }
  27.     else
  28.         printf("Stack is empty. \n");
  29.     return -1;
  30. }
  31.  
  32. int peek()
  33. {
  34.     if (top >= 0)
  35.         return stack[top];
  36.     else
  37.         printf("Empty stack\n");
  38.     return -1;
  39. }
  40.  
  41. int main()
  42. {
  43.     printf("*_* Implementing my stack in C *_*\n\n");
  44.     push(10);
  45.     push(20);
  46.     push(30);
  47.     printf("Pop item is : %d\n", pop());
  48.     push(40);
  49.     push(50);
  50.     printf("Top of stack: %d\n", peek());
  51.     return 0;
  52. }
  53.  
  54. /*
  55. Output:
  56. *_* Implementing my stack in C* _*
  57.  
  58. Successfully added item : 10
  59. Successfully added item : 20
  60. Successfully added item : 30
  61. Pop item is : 30
  62. Successfully added item : 40
  63. Successfully added item : 50
  64. Top of stack : 50
  65. */
RAW Paste Data