Write a Program for Stack implementation through Array?
Data Structure > Stack Data Structure > Stack operations and Implementation
551
Answer:
In this program, the stack is implemented using an array stack
of size MAXSIZE
. The variable top
stores the index of the top element in the stack, initialized to -1 indicating an empty stack.
The program provides four operations on the stack:
- Push: Inserts an element into the stack. If the stack is full, it displays a message "Stack Overflow".
- Pop: Removes the top element from the stack and displays it. If the stack is empty, it displays a message "Stack Underflow" and returns -1.
- Display: Prints all the elements in the stack.
- Exit: Terminates the program.
The switch
statement is used to perform the desired operation based on the user's choice. The program runs in an infinite loop until the user chooses to exit.
#include #include #define MAXSIZE 100 int stack[MAXSIZE]; int top = -1; void push(int item) { if (top == MAXSIZE - 1) { printf("Stack Overflow\n"); return; } top++; stack[top] = item; printf("Pushed %d to the stack\n", item); } int pop() { int item; if (top == -1) { printf("Stack Underflow\n"); return -1; } item = stack[top]; top--; printf("Popped %d from the stack\n", item); return item; } void display() { int i; if (top == -1) { printf("Stack is empty\n"); return; } printf("Stack elements are:\n"); for (i = top; i >= 0; i--) printf("%d\n", stack[i]); } int main() { int choice, item; while (1) { printf("\nStack Operations:\n"); printf("1. Push\n2. Pop\n3. Display\n4. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Enter the element to be pushed: "); scanf("%d", &item); push(item); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("Invalid choice\n"); } } return 0; }
This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.