How to Implement Stack Using Array in C: Simple Guide
To implement a
stack using an array in C, create an array and an integer to track the top position. Use functions like push to add elements, pop to remove elements, and check for overflow or underflow conditions.Syntax
A stack using an array in C typically involves:
- An array to hold the stack elements.
- An integer variable
topto track the index of the last added element. - Functions to
push(add),pop(remove), andpeek(view top element).
c
#define MAX_SIZE 100 int stack[MAX_SIZE]; int top = -1; void push(int value); int pop(void); int peek(void);
Example
This example shows a complete stack implementation using an array with push, pop, and peek operations, including checks for overflow and underflow.
c
#include <stdio.h> #define MAX_SIZE 5 int stack[MAX_SIZE]; int top = -1; void push(int value) { if (top == MAX_SIZE - 1) { printf("Stack Overflow! Cannot push %d\n", value); return; } stack[++top] = value; printf("Pushed %d\n", value); } int pop() { if (top == -1) { printf("Stack Underflow! Cannot pop\n"); return -1; // Indicates error } int popped = stack[top--]; printf("Popped %d\n", popped); return popped; } int peek() { if (top == -1) { printf("Stack is empty\n"); return -1; // Indicates empty stack } return stack[top]; } int main() { push(10); push(20); push(30); printf("Top element is %d\n", peek()); pop(); pop(); pop(); pop(); // Extra pop to show underflow return 0; }
Output
Pushed 10
Pushed 20
Pushed 30
Top element is 30
Popped 30
Popped 20
Popped 10
Stack Underflow! Cannot pop
Common Pitfalls
Common mistakes when implementing a stack using an array include:
- Not checking for stack overflow before pushing, which causes writing outside array bounds.
- Not checking for stack underflow before popping, which causes invalid reads.
- Incorrectly updating the
topindex, leading to wrong stack behavior.
c
/* Wrong: No overflow check */ void push_wrong(int value) { stack[++top] = value; // May overflow } /* Correct: Check overflow */ void push_correct(int value) { if (top == MAX_SIZE - 1) { printf("Stack Overflow!\n"); return; } stack[++top] = value; }
Quick Reference
Remember these key points when using arrays for stacks:
- top = -1 means stack is empty.
- top == MAX_SIZE - 1 means stack is full.
- push: increment
topthen add element. - pop: remove element at
topthen decrementtop. - Always check for overflow and underflow.
Key Takeaways
Use an array and a top index to implement stack operations in C.
Always check for overflow before pushing and underflow before popping.
Increment top before pushing and decrement after popping to maintain stack state.
Peek returns the current top element without removing it.
Initialize top to -1 to represent an empty stack.