Stack in C

A Stack is a linear data structure that follows the LIFO rule (Last In, First Out). The element inserted last is removed first. Stacks are widely used in memory handling, expression evaluation, recursion, and function calls.

What is a Stack?

A stack works like a pile of plates β€” the last plate placed is the first one removed. In C, stacks can be implemented using:

LIFO Rule

PUSH β†’ PUSH β†’ PUSH
POP  ← POP  ← POP

Basic Stack Operations

Stack Representation (Array)

Index: 0   1   2   3   4
Value: 5   9   3   8   -
                 ↑
                TOP

Stack Implementation (Array)

Full Code Implementation

#include <stdio.h>
#define MAX 5

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

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

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

int peek(){
    if(top == -1){
        printf("Stack Empty\n");
        return -1;
    }
    return stack[top];
}

void display(){
    if(top == -1){
        printf("Stack Empty\n");
        return;
    }
    for(int i=top;i>=0;i--)
        printf("%d ", stack[i]);
}
int main(){
    push(10);
    push(20);
    push(30);
    display();
    return 0;
}

5 Practical Stack Examples (Copy–Paste)

Example 1 β€” Push & Pop

#include <stdio.h>

int stack[10], top=-1;

void push(int x){ stack[++top]=x; }
int pop(){ return stack[top--]; }

int main(){
    push(5);
    push(9);
    printf("%d", pop());
    return 0;
}

Example 2 β€” Peek Top Element

#include <stdio.h>

int stack[5], top=-1;

int peek(){
    if(top==-1) return -1;
    return stack[top];
}

int main(){
    stack[++top] = 11;
    stack[++top] = 22;
    printf("%d", peek());
    return 0;
}

Example 3 β€” Stack Underflow

#include <stdio.h>

int pop(int stack[], int *top){
    if(*top==-1){
        printf("Underflow");
        return -1;
    }
    return stack[(*top)--];
}

int main(){
    int s[5], top=-1;
    pop(s, &top);
    return 0;
}

Example 4 β€” Display Stack

#include <stdio.h>

int main(){
    int stack[]={10,20,30}, top=2;
    for(int i=top;i>=0;i--)
        printf("%d ", stack[i]);
    return 0;
}

Example 5 β€” Push Until Full

#include <stdio.h>
#define MAX 3

int main(){
    int stack[MAX], top=-1;

    for(int i=0;i<5;i++){
        if(top==MAX-1) printf("Full\n");
        else stack[++top]=i;
    }
    return 0;
}

Real Life Uses of Stack

Practice Questions

  1. Explain LIFO with real examples.
  2. Write stack operations using array.
  3. Difference between push() and pop().
  4. Implement stack using linked list.
  5. Explain function call stack.