Click here to Login

Postfix Evaluation

                                              POSTFIX EVALUATION
ALGORITHM


1. Scan the Postfix expression left to right.
1.push all operands into stack until an operator is    encountered
2. when an operator op is encountered.
2.1 pop the last two operands say Y and X off the stack and apply the operation X op Y- order of operands is important
2.2 push the result of the operation back on the stack to be used as an operand later.

2.  When end of expression is reached one operand remains on the stack - it is the final result. Pop the value from stack.

PROGRAM


#include
#include
#include
#include
int arr[100];
int top=-1;

void push(int c)
{
     top++;
     arr[top]=c;
}
int pop()
{
      if(top==-1)
      {
        return -1;
      }         
     else
      {
        int c;
        c=arr[top];
        top--;
        return (c);
      }
}
      
int main()
{
    char postfix[100];
    int i,op1,op2,res,val;
    printf("Enter the postfix expression:");
    scanf("%s",postfix);
    for(i=0;i
     {
         switch(postfix[i])
          {
                  case'+':op1=pop();
                          op2=pop();
                          res=op2+op1;
                          push(res);
                          break;
                  case'-':op1=pop();
                          op2=pop();
                          res=op2-op1;
                          push(res);
                          break;
                  case'*':op1=pop();
                          op2=pop();
                          res=op2*op1;
                          push(res);
                          break;                      
                  case'/':op1=pop();
                          op2=pop();
                          res=op2/op1;
                          push(res);
                          break;                                              
                 default:printf("Enter the value of %c:",postfix[i]);
                         scanf("%d",&val);
                         push(val);
                         break;
             }
      }
printf(" The Given postfix expression is: %s\n",postfix);
printf("Result after evaluation is :%d",arr[top]);
getch();

}

0 comments:

Post a Comment