Ques. Stack: Push and Pop Operation.
#include <stdio.h>
#define SIZE 5 // Maximum size of the stack
int stack[SIZE]; // Array to store stack elements
int top = -1; // Initialize the top of the stack to -1
// Function to push an element onto the stack
void push() {
int value;
if (top == SIZE - 1) {
printf("Stack Overflow! Cannot push more elements.\n");
}
else {
printf("Enter the value to push: ");
scanf("%d", &value);
top++;
stack[top] = value;
printf("%d pushed onto the stack.\n", value);
}
}
// Function to pop an element from the stack
void pop() {
if (top == -1) {
printf("Stack Underflow! No elements to pop.\n");
}
else {
int value = stack[top];
top--;
printf("%d popped from the stack.\n", value);
}
}
// Function to display the elements of the stack
void display() {
if (top == -1) {
printf("The stack is empty.\n");
}
else {
printf("Current stack: ");
for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
// Main function to handle user input
int main() {
int choice;
do {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
}
while (choice != 4);
return 0;
}