# How to write stack programs for arithmetic terms?

I have been given a question about a stack program which I can not solve.

Write a stack program to evaluate the term

$$\qquad (((A+B)-(A*B))*C)/(((A-B-C))⁄2)$$

How do I approach this problem?

• Hint: Check for reverse polish notation Commented Mar 28, 2013 at 8:21
• what is the reverse polish notation? it is important ? Commented Mar 28, 2013 at 8:24
• hint: it might help to change the representation of the equation before feeding it to your program Commented Mar 28, 2013 at 8:52
• may be if i put A=3,B=2,C=4 Then first i find the (A+B)-(A*B)*C = R1 Commented Mar 28, 2013 at 9:06
• hint: try a simpler equation first. heed bartek's advice. Commented Mar 28, 2013 at 10:36

What you want to do is; either first translate the expression into something that is easier for a stack machine to handle (like reverse polish).

The other is to use a modified shunting yard algorithm which can handle parenthesis.

You have 2 stacks: a result stack that holds the numbers where you push the numbers as you encounter them;

and an operator stack that holds operators in decreasing priority order.

When you need to add a operator that is of lower precedence you pop from the operator stack. Then apply that operator to the top 2 values on the result stack and replace them with the result. A parenthesis is of lowest priority but is the only one that can go on top of a higher priority operator.

When you encounter a closing parenthesis you pop from the operator stack and apply to the result stack until you find a closing parenthesis which you pop.

• Please try to adhere to common styling courtesy, e.g. punctuation and capitalisation. Commented Mar 28, 2013 at 12:02
• i still not understand Commented Mar 31, 2013 at 13:36