1.
Stack operations
#include <studio.h>
#define MAX 5 // Maximum size of stack
#define MAX 5 → Defines a constant MAX = 5, meaning the stack can hold 5
elements.
int stack[MAX];
int top = -1;
stack[MAX] → Declares an array to store stack elements.
top = -1 → Initially, the stack is empty.
o If top == -1 → stack is empty.
o If top == MAX - 1 → stack is full.
🔹 Push Function
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
stack[++top] = value;
printf("%d pushed to stack\n", value);
Checks if stack is full:
o if (top == MAX - 1) → last index filled → overflow condition.
If not full:
o ++top increases top by 1.
o stack[top] = value; stores the new element at this new top position.
Prints confirmation message.
🔹 Pop Function
void pop() {
if (top == -1) {
printf("Stack Underflow! Cannot pop\n");
} else {
printf("%d popped from stack\n", stack[top--]);
Checks if stack is empty:
o if (top == -1) → no elements → underflow condition.
If not empty:
o Prints stack[top].
o top-- reduces the index, effectively removing the top element.
🔹 Display Function
void display() {
if (top == -1) {
printf("Stack is empty\n");
} else {
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
printf("\n");
If stack empty → prints "Stack is empty".
Otherwise:
o Loop runs from top → bottom.
o Prints elements in the LIFO order (last in, first out).
🔹 Main Function
int main() {
int choice, value;
while (1) {
printf("\n--- Stack Menu ---\n");
printf("1. Push\n2. Pop\n3. Display\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:
display();
break;
case 4:
return 0;
default:
printf("Invalid choice! Try again.\n");
}
}
Declares choice (menu option) and value (stack element).
Infinite loop (while (1)) → keeps showing menu until Exit is chosen.
Prints menu options each time.
Uses scanf to read user’s choice.
switch (choice):
o Case 1 (Push) → asks for value, calls push(value).
o Case 2 (Pop) → removes top element, calls pop().
o Case 3 (Display) → shows all elements in stack, calls display().
o Case 4 (Exit) → return 0; ends program.
o Default → handles invalid input.