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
//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--];
}
}
Comments
Leave a comment