Program in c++ to push and pop an element into/from a stack implemented using Array.
Program:
#include<iostream.h>
#include<conio.h>
#define NULL
0
class
stackmenu
{
int top,max,item;
int *stack;
public:
stackmenu()
{
cout<<"\n Enter maximum limit
of stack:";
cin>>max;
stack=new int[max];
top=NULL;
}
void push(int item)
{
if(top==max)
{
cout<<"\n OVERFLOW";
return;
}
top=top+1;
stack[top]=item;
cout<<item<<"is pushed
at"<<top<<"position"<<endl;
}
void pop()
{
if(top==NULL)
{
cout<<"\n UNDERFLOW";
return;
}
item=stack[top];
cout<<"\n"<<item<<"is poped
from"<<top<<"position"<<endl;
top=top+1;
return;
}
};
void main()
{
int ch,it;
clrscr();
stackmenu s;
do
{
clrscr();
cout<<"\n STACK MENU";
cout<<"\n 1.PUSH";
cout<<"\n 2.POP";
cout<<"\n 3.EXIT";
cout<<"\n Enter
choice(1-3)......";
cin>>ch;
switch(ch)
{
case 1:cout<<"\n Enter
item..";
cin>>it;
s.push(it);
break;
case 2:s.pop();
break;
case 3:return;
}
cout<<"\n Enter any key to
continue...";
getch();
}
while(ch!=3);
}
output:
Enter
maximum limit of stack:4
STACK MENU
1.PUSH
2.POP
3.EXIT
Enter
choice(1-3)...…..1
Enter
item..2
2 is pushed
at 1 position
Enter any
key to continue…
Enter item..4
4 is pushed
at 2 position
Enter any
key to continue…
Enter
item..6
6 is pushed
at 3 position
Enter any
key to continue…
Enter
item..8
8 is pushed
at 4 position
Enter any
key to continue…
STACK MENU
1.PUSH
2.POP
3.EXIT
Enter
choice(1-3)...…..2
8 is poped
from 4 position
Enter any
key to continue…
STACK MENU
1.PUSH
2.POP
3.EXIT
Enter
choice(1-3)...…..2
6is poped
from 3 position
Enter any
key to continue…
STACK MENU
1.PUSH
2.POP
3.EXIT
Enter
choice(1-3)...…..3