# Evaluation of a prefix expression

Page 1 of 1

## 3 Replies - 11338 Views - Last Post: 28 May 2010 - 08:32 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=175474&amp;s=87ddad0829ef1cf8499f2480ecf3da48&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 sanya_14

Reputation: 0
• 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

• Saucy!

Reputation: 6246
• Posts: 24,014
• Joined: 23-August 08

## Re: Evaluation of a prefix expression

Posted 28 May 2010 - 08:10 AM

Moved from C++ Tutorials

### #3 jessicalegner

Reputation: 1
• 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!

### #4 mojo666

Reputation: 408
• Posts: 882
• 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.