Question #251797

Write a menu driven program to perform the following

operations of a stack using 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


Expert's answer

#include<stdio.h>
#include<stdlib.h>
#define MAX 5
int top=-1,stack[MAX];
void push();
void pop();
void display();
void main()
{
int option;
while(1)
{
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n\nChoose an option:");
scanf("%d",&option);
switch(option)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nInvalid option!!");
}
}
}
 
void push()
{
int value;
if(top==MAX-1)
{
printf("\nStack is full!!");
}
else
{
printf("\nEnter element to push:");
scanf("%d",&value);
top=top+1;
stack[top]=value;
}
}
 
void pop()
{
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nDeleted element is %d",stack[top]);
top=top-1;
}
}
 
void display()
{
int i;
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nStack is: \n");
for(i=top;i>=0;--i)
printf("%d\n",stack[i]);
}
}
LATEST TUTORIALS
APPROVED BY CLIENTS