C Example Code2026-03-202 min read
Implement a Stack data structure in C using static arrays. Complete runnable code for push, pop, peek, isFull, and isEmpty operations.
Stack LIFO Principles
A Stack is a Last-In, First-Out (LIFO) data structure. Elements can only be added (push) or removed (pop) from the top of the stack.
C Code Implementation
c (ISO Standard)#include <stdio.h> #include <stdbool.h> #define MAX_CAPACITY 5 typedef struct { int items[MAX_CAPACITY]; int top; } Stack; void initStack(Stack *s) { s->top = -1; } bool isFull(const Stack *s) { return s->top == MAX_CAPACITY - 1; } bool isEmpty(const Stack *s) { return s->top == -1; } bool push(Stack *s, int value) { if (isFull(s)) { printf("Stack Overflow! Cannot push %d.\n", value); return false; } s->items[++(s->top)] = value; printf("Pushed %d to stack.\n", value); return true; } int pop(Stack *s) { if (isEmpty(s)) { printf("Stack Underflow! Stack is empty.\n"); return -1; } return s->items[(s->top)--]; } int peek(const Stack *s) { if (isEmpty(s)) return -1; return s->items[s->top]; } int main() { Stack myStack; initStack(&myStack); push(&myStack, 10); push(&myStack, 20); push(&myStack, 30); printf("Top element: %d\n", peek(&myStack)); printf("Popped: %d\n", pop(&myStack)); printf("Popped: %d\n", pop(&myStack)); return 0; }
Sample Output
text (ISO Standard)Pushed 10 to stack. Pushed 20 to stack. Pushed 30 to stack. Top element: 30 Popped: 30 Popped: 20
Complexity Analysis
- Push / Pop / Peek:
O(1)constant time operations. - Space Complexity:
O(MAX_CAPACITY)fixed buffer.
Related Data Structures
- Compare with dynamic node structures in Singly Linked List in C.
- Master structures in Structures in C.