Answer to Question #240339 in C for xyz

Question #240339

Write a menu-driven program to perform the following operations of a stack using an array by using suitable user-defined functions for each case.


a) Check if the stack is empty 

b) Display the contents of stack 

c) Push 

d) Pop


1
Expert's answer
2021-09-22T06:28:38-0400
//C Menu driven stack program
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>


#define SIZE 100 //Declare 100 element constant for stack


// Initialize stack with maximum number of elements as SIZE constant
int stack[SIZE];


int top = -1;


//Function declaration
void push(int element); //Push element to stack
int  pop(); //Pop element from stack




int main()
{
    int userChoice, data;


    while(1)
    {
        //Menu
        printf("****************Please select an option***********\n");
        printf("1. Push element\n");
        printf("2. Pop element\n");
        printf("3. Check stack\n");
        printf("4. Quit program\n");
        printf("Enter your choice: ");
        scanf("%d", &userChoice);


        switch(userChoice)
        {
            case 1:
                printf("Enter data to push into stack: ");
                scanf("%d", &data);
                // Push element to stack
                push(data);
                break;
                //Pop element from stack
            case 2:
                data = pop();
                // If stack is not empty
                if (data != INT_MIN)
                    printf("Data => %d\n", data);
                break;
            case 3:
                printf("Stack size is: %d\n", top + 1);
                break;
            case 4:
                printf("Exiting program...\n");
                exit(0);
                break;
            default:
                printf("Invalid choice, please enter 1, 2, 3 or 4 only.\n");
        }
    }


    return 0;
}


void push(int element)
{
    //Check for overflow
    if (top >= SIZE)
    {
        printf("Error! Stack overflow detected!!.\n");
        return;
    }


    //Increase element count in stack
    top++;
    // Push element in stack
    stack[top] = element;
    printf("Element pushed to stack.\n");
}


int pop()
{
    // Check for stack underflow error
    if (top < 0)
    {
        printf("Stack is empty. Pop operation impossible\n");
        return INT_MIN;
    }
    else
    {
       return stack[top--];
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS