Menu-Driven Stack and Queue (Array) - With Explanations
Stack (Array) - Menu Driven
Step-by-step explanation:
1. push(): Takes user input and adds to the top. Checks overflow.
2. pop(): Removes and prints top element. Checks underflow.
3. peek(): Prints current top element without removing it.
4. display(): Prints all stack elements from top to bottom.
5. exit: Terminates the program.
Implements interactive LIFO behavior.
#include <stdio.h>
#define SIZE 100
int stack[SIZE], top = -1;
void push() {
int value;
if (top == SIZE - 1)
printf("Stack Overflow\n");
else {
printf("Enter value to push: ");
scanf("%d", &value);
stack[++top] = value;
}
}
void pop() {
if (top == -1)
printf("Stack Underflow\n");
else
printf("Popped: %d\n", stack[top--]);
}
void peek() {
if (top == -1)
printf("Stack is empty\n");
else
printf("Top element: %d\n", stack[top]);
}
void display() {
if (top == -1)
printf("Stack is empty\n");
else {
printf("Stack: ");
for (int i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}
}
int main() {
int choice;
while (1) {
printf("\[Link]\[Link]\[Link]\[Link]\[Link]\nEnter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: push(); break;
case 2: pop(); break;
case 3: peek(); break;
case 4: display(); break;
case 5: return 0;
default: printf("Invalid choice\n");
}
}
return 0;
}
Queue (Array) - Menu Driven
Step-by-step explanation:
1. enqueue(): Adds input element at rear. Checks overflow.
2. dequeue(): Removes and prints front element. Checks underflow.
3. display(): Prints queue elements from front to rear.
4. exit: Terminates the program.
Implements interactive FIFO behavior.
#include <stdio.h>
#define SIZE 100
int queue[SIZE], front = -1, rear = -1;
void enqueue() {
int value;
if (rear == SIZE - 1)
printf("Queue Overflow\n");
else {
printf("Enter value to enqueue: ");
scanf("%d", &value);
if (front == -1) front = 0;
queue[++rear] = value;
}
}
void dequeue() {
if (front == -1 || front > rear)
printf("Queue Underflow\n");
else
printf("Dequeued: %d\n", queue[front++]);
}
void display() {
if (front == -1 || front > rear)
printf("Queue is empty\n");
else {
printf("Queue: ");
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
}
int main() {
int choice;
while (1) {
printf("\[Link]\[Link]\[Link]\[Link]\nEnter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4: return 0;
default: printf("Invalid choice\n");
}
}
return 0;
}