Stack in C: solved exercise
If you searched for stack in C solved exercise, this implementation covers core operations with safety checks.
Problem statement
Implement an integer stack with:
push,pop,peek,- state-check helpers.
C solution
#include <stdio.h>
#define CAP 5
typedef struct {
int data[CAP];
int top;
} Stack;
void init(Stack *s) { s->top = -1; }
int is_empty(Stack *s) { return s->top < 0; }
int is_full(Stack *s) { return s->top == CAP - 1; }
int push(Stack *s, int x) {
if (is_full(s)) return 0;
s->data[++s->top] = x;
return 1;
}
int pop(Stack *s, int *out) {
if (is_empty(s)) return 0;
*out = s->data[s->top--];
return 1;
}
int peek(Stack *s, int *out) {
if (is_empty(s)) return 0;
*out = s->data[s->top];
return 1;
}
int main(void) {
Stack s;
int v;
init(&s);
push(&s, 10);
push(&s, 20);
push(&s, 30);
peek(&s, &v); printf("Top: %d\n", v);
pop(&s, &v); printf("Pop: %d\n", v);
peek(&s, &v); printf("Top: %d\n", v);
return 0;
}Expected output
Top: 30
Pop: 30
Top: 20Recommended edge case
Test these two scenarios in one run:
- call
popon an empty stack (underflow), - call
pushwhentop == CAP - 1(overflow).
This confirms error paths return 0 without corrupting stack state.
Common mistakes
- Not checking overflow on
push. - Not checking underflow on
pop. - Forgetting to initialize
topto-1. - Updating
topin the wrong order and reading out of bounds.
Time and space complexity
push,pop, andpeek: O(1).- Total space: O(n) for the fixed-capacity
CAParray.
Practical use
Stacks appear in parsing, undo/redo systems, and expression evaluation.
Recommended next exercise
- Queue in C: solved exercise with circular array
- Singly linked list in C: solved exercise with insert and delete
- Binary search in C: solved exercise on sorted arrays
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.