Stack using array
1) Stack using Array
Aim
To implement stack operations (Push, Pop, Display) using arrays in C.
Objective
To study the LIFO (Last In, First Out) principle.
To practice array-based implementation of data structures.
Algorithm
Push:
If top == n-1, then overflow.
Else top = top + 1 and insert element at stack[top].
Pop:
If top == -1, then underflow.
Else delete element from stack[top], then top = top - 1.
Display:
If top == -1, stack empty.
Else print elements from stack[top] to stack[0].
Flowchart
C Code (Stack using Array)
#include <stdio.h>
#define MAX 5
int main() {
int stack[MAX], top = -1, choice, item, i;
while (1) {
printf("\n--- Stack Menu ---\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice == 1) {
if (top == MAX - 1)
printf("Stack Overflow!\n");
else {
printf("Enter item to push: ");
scanf("%d", &item);
top++;
stack[top] = item;
}
}
else if (choice == 2) {
if (top == -1)
printf("Stack Underflow!\n");
else {
printf("Popped: %d\n", stack[top]);
top--;
}
}
else if (choice == 3) {
if (top == -1)
printf("Stack is Empty!\n");
else {
printf("Stack elements: ");
for (i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}
}
else if (choice == 4) {
printf("Exiting...\n");
break;
}
else {
printf("Invalid choice!\n");
}
}
return 0;
}
Comments
Post a Comment