Stack Using Array in C
Aim:
To implement basic stack operations (Push, Pop, and Traverse) using array in C language.
Algorithm:
1. Start the program.
2. Initialize a stack array and a top variable to -1.
3. Push Operation:
- Check if the stack is full (top == MAX - 1).
- If not, increment top and add the value at stack[top].
4. Pop Operation:
- Check if the stack is empty (top == -1).
- If not, remove the element at stack[top] and decrement top.
5. Traverse Operation:
- Check if the stack is empty.
- If not, display all elements from top to 0.
6. Use a menu-driven program to perform the above operations.
7. Repeat steps 3 to 6 until user exits.
8. Stop the program.
Program Code:
#include <stdio.h>
#define MAX 100
int stack[MAX]; int
top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
top++;
stack[top] = value;
printf("%d pushed to stack.\n", value);
}
Stack Using Array in C
void pop() {
if (top == -1) {
printf("Stack Underflow! Cannot pop.\n");
} else {
printf("%d popped from stack.\n", stack[top]); top--;
}
}
void traverse() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Stack elements are:\n"); for (int
i = top; i >= 0; i--) {
printf("%d\n", stack[i]);
}
}
}
int main() {
int choice, value;
while (1) {
printf("\nStack Operations Menu:\n");
printf("1. Push\n2. Pop\n3. Traverse\n4. Exit\n"); printf("Enter 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:
traverse();
break;
case 4:
printf("Exiting program.\n"); return 0;
default:
printf("Invalid choice! Please try again.\n");
}
Stack Using Array in C
}
return 0;
}
Sample Input/Output:
Stack Operations Menu:
1. Push
2. Pop
3. Traverse
4. Exit
Enter your choice: 1 Enter
value to push: 30
30 pushed to stack.
Enter your choice: 1 Enter
value to push: 50
50 pushed to stack.
Enter your choice: 3 Stack
elements are:
50
30
Enter your choice: 2 50
popped from stack.
Enter your choice: 3 Stack
elements are:
30
Result:
The program was successfully executed and the stack operations (Push, Pop, and Traverse) using array were
Stack Using Array in C
implemented in C language.