A stack is a linear data structure that follows the Last In First Out (LIFO) principle. You can only access or remove the topmost element, just like a stack of plates. In this blog post, you will learn how to implement a stack in C using an array and perform basic operations like push, pop, and display.
What is a Stack?
A stack is a collection of elements with two main operations:
- Push – Add an element to the top.
- Pop – Remove the top element.
A third operation often used is:
- Display – Show all elements in the stack.
Stack Implementation in C Using Array
Here’s a complete program in C that implements a stack using an array.
#include <stdio.h>
#define SIZE 100
int stack[SIZE];
int top = -1;
// Function to push an element
void push(int value) {
if (top == SIZE - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = value;
printf("%d pushed to stack\n", value);
}
}
// Function to pop an element
void pop() {
if (top == -1) {
printf("Stack Underflow\n");
} else {
printf("%d popped from stack\n", stack[top]);
top--;
}
}
// Function to display the stack
void display() {
if (top == -1) {
printf("Stack is empty\n");
} else {
printf("Stack elements:\n");
for (int i = top; i >= 0; i--) {
printf("%d\n", stack[i]);
}
}
}
int main() {
int choice, value;
while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return 0;
default:
printf("Invalid choice!\n");
}
}
}
Output Example
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack
Enter your choice: 3
Stack elements:
10
Key Points
- Stack uses LIFO logic.
- Always check for overflow and underflow conditions.
- Arrays make it easy to implement stack but have a fixed size.
Conclusion
You now understand how to implement a stack in C using array. This includes handling push, pop, and display operations with proper checks for overflow and underflow. Mastering this basic data structure is a stepping stone to learning more complex topics like linked lists, queues, and trees.