Evaluation of postfix expression
One of the reasons that postfix expression is preferred is that it takes less time to be evaluated. The following algorithm is followed to evaluate postfix expression:
- A stack to store operands is created.
- The postfix expression is then scanned, if the scanned element is a number, it is pushed to stack, and if the element is an operator, pop operands for the operator from stack, it evaluates the operator and pushes it back to the stack.
- The stack’s number is the final answer.
An example of the above algorithm is as follows:
#include<stdio.h> int stack[20]; int top = -1; void push(int x) { stack[++top] = x; } int pop() { return stack[top--]; } int main() { char exp[20]; char *e; int n1,n2,n3,num; printf("Enter the expression :: "); scanf("%s",exp); e = exp; while(*e != '\0') { if(isdigit(*e)) { num = *e - 48; push(num); } else { n1 = pop(); n2 = pop(); switch(*e) { case '+': { n3 = n1 + n2; break; } case '-': { n3 = n2 - n1; break; } case '*': { n3 = n1 * n2; break; } case '/': { n3 = n2 / n1; break; } } push(n3); } e++; } printf("\nThe result of expression %s = %d\n\n",exp,pop()); return 0; } |
Reference