C Stack Program Using Array
A stack follows the rule “last in, first out” (LIFO). The last item which is pushed is the first one to come out, like a pile of plates. Here we make a stack with an array.
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = value;
}
int pop(void) {
if (top == -1) {
printf("Stack underflow\n");
return -1;
}
return stack[top--];
}
int peek(void) {
return (top == -1) ? -1 : stack[top];
}
int main(void) {
push(10);
push(20);
push(30);
printf("Top element: %d\n", peek());
printf("Popped: %d\n", pop());
printf("Popped: %d\n", pop());
printf("Top element: %d\n", peek());
pop();
pop(); // stack is empty now
return 0;
}
Output:
Output of the above program is
Top element: 30
Popped: 30
Popped: 20
Top element: 10
Stack underflow
How it works
topis the index of the last item. It is -1 when the stack is empty.push()increasestopand stores the value.pop()returns the value and decreasestop.- We check
topbefore each operation, to avoid overflow (full stack) and underflow (empty stack).
Note:
Stacks are used in function calls, undo operations and checking the brackets of an expression. Related: C Arrays and Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |