Stack in C: solved exercise with push, pop, and peek

  2 minutes

If you searched for stack in C solved exercise, this implementation covers core operations with safety checks.

Implement an integer stack with:

  • push,
  • pop,
  • peek,
  • state-check helpers.
#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;
}
Top: 30
Pop: 30
Top: 20

Test these two scenarios in one run:

  1. call pop on an empty stack (underflow),
  2. call push when top == CAP - 1 (overflow).

This confirms error paths return 0 without corrupting stack state.

  • Not checking overflow on push.
  • Not checking underflow on pop.
  • Forgetting to initialize top to -1.
  • Updating top in the wrong order and reading out of bounds.
  • push, pop, and peek: O(1).
  • Total space: O(n) for the fixed-capacity CAP array.

Stacks appear in parsing, undo/redo systems, and expression evaluation.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.