w1coding.comAll tutorials

C Stack

C lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Operators
  5. Condition
  6. Loops
  7. Functions
  8. Arrays
  9. Pointers
  10. Strings
  11. Struct
  12. File
  13. Memory
  14. Recursions
  15. Bitwise
  16. Directives
  17. Commandline
  18. Switch
  19. Enum
  20. Structp
  21. Arraysofstr
  22. Macros
  23. Pointer Arrays
  24. Linked
  25. Stack
  26. Queue
  27. Graph

C Stack Implementation

A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. In C, we can implement stacks using arrays or linked lists.

Stack Using Array

#include 
#include 

#define MAX 5

int stack[MAX];
int top = -1;

void push(int value) {
    if (top < MAX - 1) {
        stack[++top] = value;
        printf("%d pushed to stack\n", value);
    } else {
        printf("Stack overflow\n");
    }
}

void pop() {
    if (top >= 0) {
        printf("%d popped from stack\n", stack[top--]);
    } else {
        printf("Stack underflow\n");
    }
}

void peek() {
    if (top >= 0) {
        printf("Top element is %d\n", stack[top]);
    } else {
        printf("Stack is empty\n");
    }
}

int main() {
    push(10);
    push(20);
    push(30);
    peek();
    pop();
    peek();

    return 0;
}
    

This program demonstrates a stack implementation using an array. It includes functions to push, pop, and peek the stack.