Understanding the Stack in C Programming

Understanding the Stack in C Programming

Understanding the Stack in C Programming

The stack is a fundamental data structure in computer science, commonly used for managing function calls, storing local variables, and handling recursive algorithms. In this article, we'll delve into the concept of the stack and explore its implementation in the C programming language.

What is a Stack?

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. It can be visualized as a collection of elements stacked on top of each other, where new elements are added or removed from the top of the stack.

Key Operations

A stack typically supports the following operations:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes and returns the top element from the stack.
  • Peek/Top: Returns the top element of the stack without removing it.
  • isEmpty: Checks if the stack is empty.
  • isFull: Checks if the stack is full (applicable in fixed-size implementations).

Implementation in C

Using Arrays

One common way to implement a stack in C is using arrays. Let's see a basic implementation:

stack_array.c
#include <stdio.h>
#define MAX_SIZE 100
 
int stack[MAX_SIZE];
int top = -1;
 
void push(int value) {
    if (top >= MAX_SIZE - 1) {
        printf("Stack Overflow\n");
        return;
    }
    stack[++top] = value;
}
 
int pop() {
    if (top < 0) {
        printf("Stack Underflow\n");
        return -1;
    }
    return stack[top--];
}
 
int peek() {
    if (top < 0) {
        printf("Stack is empty\n");
        return -1;
    }
    return stack[top];
}
 
int isEmpty() {
    return top < 0;
}
 
int main() {
    push(10);
    push(20);
    push(30);
 
    printf("Top element: %d\n", peek());
    printf("Popped element: %d\n", pop());
    printf("Top element after pop: %d\n", peek());
 
    return 0;
}