Infix to Postix convrsion doubt

I had a doubt especially when we have all the operators of the same precedence.
Eg. if infix exp. a+b-c+d
then if we convert to postfix by going from left to right it becomes ab+ -d+ (1)
but if we first solve first + sign and then second + sign and then - sign, then the solution becomes ab+cd+ - (2)
So my question was that what is the perfect answer ?

  1. Both can be answers, both will get marks
  2. we have to go from left to right only if the precedence of all the operators are same and no parenthesis is used, hence 1 is right and 2 is wrong
  3. 2nd is right and 1st is wrong

Help me please. Thanks in advance !!

In this case, 1) ab+c-d+ is correct. To prove this, let’s evaluate both the prefix expressions. The first expression gives the result as ((a+b)-c)+d while the second expression gives (a+b)-(c+d). Clearly 1 gives the intended result while 2 doesn’t.
In case you are wondering how the prefix expressions are evaluated - If you encounter an operand(variable or constants), push it to a stack and if you encounter an operator, pop two elements from the stack, apply the operation on them and push the result back in the stack. The final element remaining in the stack is the answer.

1 Like

Thanks, got it !