🔴 Advanced  ·  Lesson 39

Stack using C

What is a stack? (LIFO)

A stack is one of the simplest and most useful data structures. It follows one rule: LIFO — Last In, First Out. The thing you added last is the first thing you take out.

Picture a pile of plates. You add plates on top, and you take from the top too. You cannot pull a plate from the middle without lifting the ones above. That is exactly how a stack behaves in C.

The core operations

OperationWhat it does
push(x)Add item x to the top
pop()Remove and return the top item
peek()Look at the top item without removing it
isEmpty()Check if the stack has no items

All the action happens at the top. A single index variable called top keeps track of where that is.

Overflow and underflow

Two situations must always be checked:

  • Overflow — pushing when the stack is already full (top is at the last index).
  • Underflow — popping when the stack is empty (top is -1).
⚠️ Always guard

Check for full before every push and for empty before every pop. Skipping these checks leads to lost data or reading invalid memory.

Array implementation

Here is a complete stack using an array, with all the safety checks.

C Language
#include <stdio.h>
#define SIZE 5
int stack[SIZE];
int top = -1;                 // empty stack

void push(int x) {
    if (top == SIZE - 1) { printf("Overflow\n"); return; }
    stack[++top] = x;          // move up, then store
}
int pop() {
    if (top == -1) { printf("Underflow\n"); return -1; }
    return stack[top--];       // return, then move down
}
int main() {
    push(10); push(20); push(30);
    printf("Popped: %d\n", pop());   // 30 (last in)
    printf("Popped: %d\n", pop());   // 20
    printf("Top now: %d\n", stack[top]); // 10
    return 0;
}
Output:
Popped: 30
Popped: 20
Top now: 10

Notice 30 came out first even though 10 was pushed first — that is LIFO in action.

Where stacks are used

  • Function calls — the computer uses a call stack to remember where to return.
  • Undo/redo — the last action is undone first.
  • Balanced brackets — checking that every ( has a matching ).
  • Expression evaluation and backtracking algorithms.

Common mistakes

  • Forgetting to check overflow before push or underflow before pop.
  • Starting top at 0 instead of -1 for an empty stack.
  • Mixing up the order in stack[++top] vs stack[top++].
  • Trying to access elements in the middle — a stack only exposes the top.
🏋️ Practice

Add a peek() function that returns the top item without removing it, and an isEmpty() function. Use them to print the top after each push. Compare with the queue in C, which uses FIFO instead.

Summary

  • A stack follows LIFO — the last item pushed is the first popped.
  • Core operations: push, pop, peek, isEmpty.
  • Track the top with an index that starts at -1.
  • Always check overflow before push and underflow before pop.
  • Stacks power call stacks, undo, bracket matching and more.

Frequently Asked Questions

What is a stack in C?
A stack is a data structure that follows the LIFO rule — Last In, First Out. The item added most recently is the first one removed, like a pile of plates where you take the top plate first. In C it is commonly built using an array and a variable called top.
What are push and pop in a stack?
push adds a new item to the top of the stack, and pop removes and returns the item currently on top. Both operations work only at the top end, which is what makes a stack LIFO.
What is stack overflow and underflow?
Overflow happens when you try to push onto a stack that is already full — there is no room left. Underflow happens when you try to pop from an empty stack — there is nothing to remove. Good stack code checks for both before acting.
What does the top variable do in a stack?
top is an index that marks the position of the current top element. It starts at -1 for an empty stack, increases by one on each push, and decreases by one on each pop. Checking top tells you if the stack is empty or full.
Where are stacks used in real programs?
Stacks are used for function call management (the call stack), undo features in editors, checking balanced brackets, evaluating expressions, and backtracking in algorithms. Any time you need "most recent first" behaviour, a stack fits.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.