Search code examples
compiler-constructionstack

Postfix conversion


INFIX EXPRESSION: A*B+C/D-E^F-G

STANDARD POSTFIX EXPRESSION: AB*CD/+EF^-G-

The one that my program yields: AB*CD/EF^G--+

Yep, postfix expression and prefix expression are used by compiler to apply arithmetic ops on operands in proper order (as per their priority) and it also helps compiler to do operations that are not defined or known to it::::

lets take an example: I have to calculate expression A?B$C#E

Here, A,B,C,E are operands and ?,$,# are operations to be performed. Now, the problem we don't know what operations should we perform first unlike with BODMAS.

So what's the solution huh?

To solve this, the expression will simply be changed in either postfix or prefix expression to be calculated here Postfix expression is AB?C$E#. Now it can easily be solved to get an appropriate answer without dealing with operations priority.

So the one that my program yields right or wrong?


Solution

  • The expression produced by your program is incorrect. It computes

    (A*B)+((C/D)-((E^F)-G))
    

    Instead of

    (((A*B)+(C/D))-(E^F))-G
    

    Your bug is to make the operators associate to the right instead of associating to the left. The end result is a difference of 2G,which you can easily see by setting all the variables to 1; your formulation returns 2 but the correct value is 0.