Stack Implementation in C Using an Array

Written: August 15, 2026

An array-backed stack is the classic first data-structure lab: fixed capacity, a top index, and clear overflow rules.

This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.

What you will build

You will keep an integer array, a top index starting at -1, and functions for push, pop, and peek with bounds checks.

  • Define MAX size and an int stack[MAX]
  • Maintain top starting at -1
  • push: if not full, ++top and store value
  • pop/peek: if not empty, read stack[top] (and –top on pop)

Working C example

include <stdio.h>
define MAX 100

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

void push(int x) {
    if (top >= MAX - 1) {
        printf("Overflow\n");
        return;
    }
    stack[++top] = x;
}

int pop(void) {
    if (top < 0) {
        printf("Underflow\n");
        return -1;
    }
    return stack[top--];
}

int peek(void) {
    if (top < 0) {
        printf("Stack empty\n");
        return -1;
    }
    return stack[top];
}

int main(void) {
    push(10);
    push(20);
    printf("Peek = %d\n", peek());
    printf("Pop = %d\n", pop());
    printf("Pop = %d\n", pop());
    return 0;
}

Advertisement

How the logic works

Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.

If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.

Draw the array and top after each call. Most bugs are an off-by-one on the full/empty tests.

Advertisement

Keep learning

If this walkthrough on Stack Implementation in C Using an Array helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.

Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.

Advertisement

Previous Article

Git Pull vs Git Fetch: What’s the Difference?

Next Article

Delete a Character from a Given String in C

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨