Lets see the logic to evaluate both postfix & prefix
expressions.
Logic for evaluating Postfix
Do refer the code available the end of this section to
understand the following thoery.
- Create stack for operands using arrays of float type.
- Scan the postfix expression from left to right.
-
If the character read is an operand then convert it into it's
corresponding numeric value and push it to the stack.
-
Else perform the following operation:
- Pop the top of stack and save it as operand2.
-
Once again pop the top of stack and save it as operand1.
-
Compute the relevant operation between operand1,
operator(character read) & operand2.
- Push this result to the stack.
-
After scanning all the characters of the postfix expression,
pop the top of stack and save is as result.
-
If the stack is not empty then the given postfix expression is
invalid. Else print the result.
Logic for evaluating Prefix
Do refer the code available the end of this section to
understand the following theory.
- Create stack for operands using arrays of float type.
- Scan the prefix expression from right to left.
-
If the character read is an operand then convert it into it's
corresponding numeric value and push it to the stack.
-
Else perform the following operation:
- Pop the top of stack and save it as operand1.
-
Once again pop the top of stack and save it as operand2.
-
Compute the relevant operation between operand1,
operator(character read) & operand2.
- Push this result to the stack.
-
After scanning all the characters of the prefix expression,
pop the top of stack and save is as result.
-
If the stack is not empty then the given prefix expression is
invalid. Else print the result.