✏️ Explanatory Question

Write a Program for Stack implementation through Array?

👁 534 Views
📘 Detailed Answer
💡

Answer with Explanation

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:

  1. Push: Inserts an element into the stack. If the stack is full, it displays a message "Stack Overflow".
  2. 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.
  3. Display: Prints all the elements in the stack.
  4. 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 <stdio.h>
#include <stdlib.h>

#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;
}