1,353 views
0 votes
0 votes
Assume that the operators +,−,× are left associative and ^ is right associative. The order of precedence (from highest to lowest) is ^,×,+,−. The postfix expression corresponding to the infix expression a+b×c−d^e^f is
A) abc*+def^^-
answer is above option but i f I do infix to postfix conversion then i get abc*+de^f^-   because in stack its giving ^^ at a time then because of same precedeence I put ^ first ....where am i wrong?

1 Answer

4 votes
4 votes

I don't know how did you get this.But then let me try to explain  infix to postfix conversion with this.
you will scan infix expression from left to right.whenever you see operand just print it. But In case of operator
   if(stack is empty) then push it.
   if(precedence(tos) < precedence(current operator) ) push it.
   else if (precedence(tos) > precedence(current operator) ) pop and print.
   else if (precedence(tos) ==  precedence(current operator) ) then check for associativity.In case Operators are Left to right then pop and print it otherwise push the current operator (Right to Left Associativity)
And once you have scanned infix expression completely. Make sure pop all the element and print it in same order.


Here the infix expression is a+b×c−d^e^f

a  : print it
+ : push into the Operator Stack
b  : print it
*  : its having higher precedence than + then push into Operator Stack
c  : print it
'-' : '-' is having less precedence than '*' so pop from operator stack and print '*'. after this stack will be having '+' on top.which is having same precedence as '-' but both are left to right associative then just pop + and print it.Now stack is empty. Push '-' to it.
d : print it
'^' : top of the stack is having '-' which has lower precedence than '^' so simply push '^' into stack
e : print it.
'^' : Now top of the stack is '^' and has same precedence so associativity will come to picture. Since '^' is right associative as given in question. So '^' will be pushed.
f : print it.

Now we have scanned entire infix expression.Now pop the stack untill it becomes empty.This way you will get
abc*+def^^-

I hope, you will get it now. smiley

Related questions

0 votes
0 votes
1 answer
4
akash28 asked Feb 23, 2023
785 views
Convert the following infix expression to postfix and prefixA^B^C^D