How is the evaluation of a prefix expression carried out using a stack?
For example if the expession is -+/A^BC*DE*AC and given that A=16, B=2,C=3,D=10 and E=4
then what is the value of the expression?
When I solved it I got -6 but the book which I'm referring to shows the final result to be -7.
I'm quite sure I'm right but I still need to confirm.
Evaluation of a prefix expression
Page 1 of 13 Replies - 3178 Views - Last Post: 28 May 2010 - 08:32 AM
Replies To: Evaluation of a prefix expression
#2
Re: Evaluation of a prefix expression
Posted 28 May 2010 - 08:10 AM
Moved from C++ Tutorials
#3
Re: Evaluation of a prefix expression
Posted 28 May 2010 - 08:31 AM
I too got -6. I do not know if the author made a mistake or if there is some type of trick.
Good luck!
Good luck!
#4
Re: Evaluation of a prefix expression
Posted 28 May 2010 - 08:32 AM
I get 16/(2^3) + (10*4) - (16*3) = -6
Starting from the right, when you read a number, push it onto the stack. When you read an operator, pop the top two numbers, perform the operation on those numbers, then push the result onto the stack. For example if you have *+CD+AB, the following steps are performed.
If it is a valid equation, at the end you should only have one value on the stack.
Starting from the right, when you read a number, push it onto the stack. When you read an operator, pop the top two numbers, perform the operation on those numbers, then push the result onto the stack. For example if you have *+CD+AB, the following steps are performed.
//pseudocode push(B)/> push(A) v1 = pop() //A v2 = pop() //B push(v1 + v2) push(D) push(C) v1 = pop() //C v2 = pop() //D push(v1 + v2) v1 = pop() //C+D v2 = pop() //A+B push(v1 * v2) //(C+D) * (A+B)/>
If it is a valid equation, at the end you should only have one value on the stack.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote






|