Tuesday 19 May 2015

C program to evaluate postfix expression

#include<stdio.h>
#include<string.h>
#include<math.h>
compute(char,int,int);
int main()
{
  int s[20],op1,op2,top=-1,result,i;
  char postfix[20],symbol;
  printf(" Enter the postfix expression to calculate");
  scanf("%s",postfix);

for(i=0;i<strlen(postfix);i++)
{
  symbol=postfix[i];
  if(isdigit(symbol))
   s[++top]=symbol-'0';
else
{
    op1=s[top--];
    op2=s[top--];
    result=compute(symbol,op1,op2);
    s[++top]=result;
}
}
printf(" The result =%d",result);
}
compute(char symbol,int op1,int op2)
{
  switch(symbol)
{
  case'+': return(op1+op2);
  case'-': return(op1-op2);
  case'*': return(op1*op2);
  case'/': return(op1/op2);
  case'^': return(pow(op1,op2));
}
}

No comments:

Post a Comment