Sunday, March 18, 2012

Evaluation of Postfix Expression

/* Program Name: Evaluation of Postfix Expression
Done By: Prof.Dhumane A.V. VIIT, Pune
*/

#include
#include

int isoperator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
return 1;
else
return 0;
}

int eval(int operand1,int operand2,char ch)
{
if(ch=='+')
{
return (operand1+operand2);
}
if(ch=='-')
{
return (operand1-operand2);
}
if(ch=='*')
{
return (operand1*operand2);
}
if(ch=='/')
{
return (operand1/operand2);
}


}
void main()
{
char *exp;
int *stack,top=-1,result,i,operand1,operand2,val;

clrscr();

printf("\nEnter the expression ");
scanf("%s",exp);

for(i=0;exp[i]!='\0';i++)
{
if(isoperator(exp[i]))
{
operand1=stack[top];
top--;
operand2=stack[top];
top--;
result=eval(operand1,operand2,exp[i]);
top++;
stack[top]=result;
}
else
{
printf("\nEnter the value of %c",exp[i]);
scanf("%d",&val);
top++;
stack[top]=val;
}
}
printf("\n\nresult =%d",stack[top]);
getch();
}

No comments:

Post a Comment