In: Computer Science
Problem 2: Evaluate the following postfix expression, using the rules given in Section I of Lab 10: 1 5 4 – 3 + * 3.
Computer Science
`Hey,
Note: If you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
1 5 4 – 3 + * 3.
Scan ‘1’, it’s a number, so push it to stack. Stack contains ‘1’
Scan ‘5’, again a number, push it to stack, stack now contains ‘1 5’ (from bottom to top)
Scan ‘4’, again a number, push it to stack, stack now contains ‘1 5 4’ (from bottom to top)
Scan ‘-’, it’s an operator, pop two operands from stack, apply the - operator on operands, we get 5-4 which results in 1. We push the result ‘1’ to stack. Stack now becomes ‘1 1’.
Scan ‘3’, again a number, push it to stack, stack now contains ‘1 1 3’ (from bottom to top)
Scan ‘+’, it’s an operator, pop two operands from stack, apply the + operator on operands, we get 1+3 which results in 4. We push the result ‘2’ to stack. Stack now becomes ‘1 4’.
Scan ‘*’, it’s an operator, pop two operands from stack, apply the * operator on operands, we get 1*4 which results in 4. We push the result ‘4’ to stack. Stack now becomes ‘4’.
So, answer is 4
Kindly revert for any queries
Thanks.