Question 2:
WAP to implement Stack using array.
Answer:
A stack is a linear data structure that follows the LIFO (Last In First Out) principle. It means
the element inserted last is removed first. In stack, insertion is called PUSH and deletion is
called POP. Here, we implement stack using an array.
C Program:
#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 element.\n");
} else {
top++;
stack[top] = value;
printf("%d pushed into stack.\n", value);
}
}
void pop() {
if (top == -1) {
printf("Stack Underflow! Stack is empty.\n");
} else {
printf("%d popped from stack.\n", stack[top]);
top--;
}
}
void display() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Stack elements are: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
int main() {
int choice, value;
while (1) {
printf("\n--- Stack Menu ---\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:
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!\n");
}
}
}
Explanation:
1. We use an array 'stack' to store elements.
2. 'top' keeps track of the top position of stack.
3. push() inserts an element at the top.
4. pop() removes the top element.
5. display() shows all elements of the stack.
6. main() provides menu-driven operations.