fork download
  1. // C Program to demonstrate how to Implement a Stack
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4.  
  5. // Define the maximim capacity of the stack
  6. #define MAX_SIZE 100
  7.  
  8. // Define a structure for the stack
  9. typedef struct {
  10. int arr[MAX_SIZE];
  11. int top;
  12. } Stack;
  13.  
  14. // Function to initialize the stack
  15. void initialize(Stack *stack) {
  16. stack->top = -1;
  17. }
  18.  
  19. // Function to check if the stack is empty
  20. bool isEmpty(Stack *stack) {
  21. return stack->top == -1;
  22. }
  23.  
  24. // Function to check if the stack is full
  25. bool isFull(Stack *stack) {
  26. return stack->top >= MAX_SIZE - 1;
  27. }
  28.  
  29. // Function to push an element onto the stack
  30. void push(Stack *stack, int value) {
  31. if (isFull(stack)) {
  32. printf("Stack Overflow\n");
  33. return;
  34. }
  35. stack->arr[++stack->top] = value;
  36. printf("Pushed %d onto the stack\n", value);
  37. }
  38.  
  39. // Function to pop an element from the stack
  40. int pop(Stack *stack) {
  41. if (isEmpty(stack)) {
  42. printf("Stack Underflow\n");
  43. return -1;
  44. }
  45.  
  46. int popped = stack->arr[stack->top];
  47. stack->top--;
  48. printf("Popped %d from the stack\n", popped);
  49. return popped;
  50. }
  51.  
  52. // Function to peek the top element of the stack
  53. int peek(Stack *stack) {
  54. if (isEmpty(stack)) {
  55. printf("Stack is empty\n");
  56. return -1;
  57. }
  58. return stack->arr[stack->top];
  59. }
  60.  
  61. int main() {
  62. Stack stack;
  63. initialize(&stack);
  64.  
  65. push(&stack, 3);
  66. printf("Top element: %d\n", peek(&stack));
  67.  
  68. push(&stack, 5);
  69. printf("Top element: %d\n", peek(&stack));
  70.  
  71. push(&stack, 2);
  72. printf("Top element: %d\n", peek(&stack));
  73.  
  74. push(&stack, 8);
  75. printf("Top element: %d\n", peek(&stack));
  76.  
  77. while (!isEmpty(&stack)) {
  78. printf("Top element: %d\n", peek(&stack));
  79. printf("Popped element: %d\n", pop(&stack));
  80. }
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0s 5276KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
Pushed 3 onto the stack
Top element: 3
Pushed 5 onto the stack
Top element: 5
Pushed 2 onto the stack
Top element: 2
Pushed 8 onto the stack
Top element: 8
Top element: 8
Popped 8 from the stack
Popped element: 8
Top element: 2
Popped 2 from the stack
Popped element: 2
Top element: 5
Popped 5 from the stack
Popped element: 5
Top element: 3
Popped 3 from the stack
Popped element: 3