top of page
Writer's picturecompnomics

Understanding Stacks Operation: A C Programming Guide


Stacks are simple yet powerful data structures widely used in everything from reversing words to handling function calls in programs. If the idea is new to you, imagine stacking plates: You can add a new plate only to the top, and you can only remove the topmost one. This is LIFO: Last In, First Out.


C Implementation

Let's use an array and a variable to represent a stack:

#include <stdio.h>
#define MAX_SIZE 100 

int stack[MAX_SIZE];
int top = -1; // Empty stack

// Function prototypes
void push(int data);
int pop();
int isEmpty();
int isFull();

int main() {
  // Example usage
  push(10);
  push(20);
  push(30);

  printf("Popped: %d\n", pop()); // Output: Popped: 30

  if (!isEmpty()) {
    printf("Top element: %d\n", stack[top]); 
  }

  return 0;
}

// Stack operation functions
void push(int data) {
  if (isFull()) {
    printf("Stack Overflow\n");
  } else {
    top++;
    stack[top] = data;
  }
}

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

int isEmpty() {
  return top == -1; 
}

int isFull() {
  return top == MAX_SIZE - 1; 
}

Explanations

  1. Initialization: top is initialized to -1 indicating an empty stack.

  2. push(data):

  • Checks if the stack is full; if so, indicates overflow.

  • Otherwise, increments top and inserts the data element.

  1. pop():

  • Checks if the stack is empty; if so, indicates underflow.

  • Otherwise, retrieves the top element, decrements top, and returns the element.

  1. isEmpty() and isFull(): Helper functions to check the stack's state.


*Key Points

  • Stacks follow LIFO order.

  • Stack operations are simple and efficient.

  • Real-world use cases include:

  • Undo/Redo functionality in editors

  • Expression evaluation

  • Backtracking algorithms

36 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page