Solved
evaluating a postfix expression
Posted on 2001-06-28
dear expert!
please find why the below given program is saying "stack overflow", when i gave some postfix expression (say 65+)?
my program:
#include <iostream.h>
const int max = 50;
char exp[50];
int upper;
int lower;
class stack
{
public:
char st[max];
int top;
public:
stack()
{
top=0;
}
void push(int var)
{
if(top>=max)
{
cout<<"stack overflow";
}
else
{
st[++top]=var;
}
}
int pop()
{
if(top<0)
{
cout<<"stack underflow";
}
else
{
return st[top--];
}
}
int isempty()
{
if(top==0)
{
return 1;
}
else
{
return 0;
}
}
};
void main()
{
stack s1;
cout<<"Enter a postfix expression\n";
cin>>exp;
for (int i=0;i<50;++i)
{
while(!(exp[i]=='\0'))
{
if((exp[i]=='+')|(exp[i]=='-')|(exp[i]=='*')|(exp[i]=='/'))
{
switch(exp[i])
{
case '+':
upper=s1.pop();
lower=s1.pop();
s1.push(int(upper+lower));
case '-':
upper=s1.pop();
lower=s1.pop();
s1.push(int(upper-lower));
case '*':
upper=s1.pop();
lower=s1.pop();
s1.push(int(upper*lower));
case '/':
upper=s1.pop();
lower=s1.pop();
s1.push(int(upper/lower));
}//end of switch
}//end of if
else
{
s1.push(int(exp[i]));
}//end of else
}//end of while
}//end of for
cout<<s1.pop();
}//end of main