3 Replies - 5778 Views - Last Post: 28 May 2010 - 08:32 AM Rate Topic: -----

#1 sanya_14  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 28-May 10

Evaluation of a prefix expression

Posted 28 May 2010 - 02:05 AM

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.
Is This A Good Question/Topic? 0
  • +

Replies To: Evaluation of a prefix expression

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: Evaluation of a prefix expression

Posted 28 May 2010 - 08:10 AM

Moved from C++ Tutorials
Was This Post Helpful? 0
  • +
  • -

#3 jessicalegner  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 66
  • Joined: 05-June 09

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!
Was This Post Helpful? 0
  • +
  • -

#4 mojo666  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 356
  • View blog
  • Posts: 783
  • Joined: 27-June 09

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.
//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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1