Design Develop and Implement Program in C for STACK of Integers Push and Pop.

STACK of Integers (Array Implementation of Stack with maximum size MAX) for Push an Element on to Stack Pop an Element from Stack and Demonstrate Overflow and Underflow situations on Stack and Display the status of Stack. 3rd Sem Data Structure and application lab 3rd question

Design, Develop and Implement a menu driven Program in C for the following operations on STACK of Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate Overflow and Underflow situations on Stack
d. Display the status of Stack
e. Exit

/*Design, Develop and Implement a menu driven Program in C for the following operations on STACK of Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate Overflow and Underflow situations on Stack
d. Display the status of Stack
e. Exit*/
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

int stack[MAX];
int top = -1;

void push(int element);
int pop();
void displayStack();

int main()
{
    int choice, element;

    while (1)
    {
        printf("\nStack Operations:\n");
        printf("1. Push an Element\n");
        printf("2. Pop an Element\n");
        printf("3. Display Stack\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1:
                printf("Enter the element to be pushed: ");
                scanf("%d", &element);
                push(element);
                break;
            case 2:
                element = pop();
                if (element != -1)
                {
                    printf("Popped element: %d\n", element);
                }
                break;
            case 3:
                displayStack();
                break;
            case 4:
                exit(0);
            default:
                printf("Invalid choice\n");
        }
    }
    return 0;
}

void push(int element)
{
    if (top == MAX - 1)
    {
        printf("Stack Overflow\n");
    }
    else
    {
        top++;
        stack[top] = element;
        printf("Element pushed: %d\n", element);
    }
}

int pop()
{
    if (top == -1)
    {
        printf("Stack Underflow\n");
        return -1;
    }
    else
    {
        return stack[top--];
    }
}

void displayStack()
{
    int i;
    if (top == -1)
    {
        printf("Stack is Empty\n");
    }
    else
    {
        printf("Stack elements:\n");
        for (i = top; i >= 0; i--)
        {
            printf("%d\n", stack[i]);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *