📘 Lesson · Lesson 63
Stack using Array
Stack using Array
What is a Stack?
💡 Note
A stack is a LIFO (Last In First Out) structure. We implement it with an array and a top index.
Program
C
#include <stdio.h>
#define SIZE 5
int stack[SIZE], top = -1;
void push(int x) {
if (top == SIZE-1) { printf("Overflow\n"); return; }
stack[++top] = x;
}
int pop() {
if (top == -1) { printf("Underflow\n"); return -1; }
return stack[top--];
}
int main() {
push(10); push(20); push(30);
printf("Popped: %d\n", pop()); // 30
printf("Popped: %d\n", pop()); // 20
return 0;
}Output:
Popped: 30 Popped: 20
Popped: 30 Popped: 20
Summary
- Stack is LIFO: push adds to top, pop removes from top.
- Check overflow (full) and underflow (empty).
Stack क्या है?
💡 Note
Stack एक LIFO (Last In First Out) structure है। इसे array और top index से implement करते हैं।
Program
C
#include <stdio.h>
#define SIZE 5
int stack[SIZE], top = -1;
void push(int x) {
if (top == SIZE-1) { printf("Overflow\n"); return; }
stack[++top] = x;
}
int pop() {
if (top == -1) { printf("Underflow\n"); return -1; }
return stack[top--];
}
int main() {
push(10); push(20); push(30);
printf("Popped: %d\n", pop()); // 30
printf("Popped: %d\n", pop()); // 20
return 0;
}Output:
Popped: 30 Popped: 20
Popped: 30 Popped: 20
सारांश
- Stack LIFO है: push top पर जोड़ता, pop top से हटाता है।
- Overflow (full) और underflow (empty) जाँचें।