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.
#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.