push 1
push 2
Now input is +
pop 1
pop 2
calculate sum 1+2 = 3
push 3
Now input is *
pop 3
pop 3
calculate 3*3 = 9
Now no more inputs and stack top is -1, so stop
Are the four basic arithmetic functions (add, subtract, multiply, divide) sufficient or do you need to support other functions (such as exponentiation) ?
The purpose of the postfix stack is to conform to the arithmetic order of operations. You need to have a clear understanding of the proper order of operations. Note that "order of operations" is a mathematical concept -- it has nothing to do with computer programming.
You should read about postfix notation. Evaluating a postfix expression is easy (that's the allure). The trick is to translate your input expression from infix notation to postfix notation.
Look at the example in your original post: ((1+3)*5)
The postfix equivalent is 1,3,+,5,*
This can be read as ...
Put the number "1" in your left hand.
Put the number "3" in your right hand.
Add the numbers you're holding, putting the result in your left hand and dropping what's in your right hand.
Put the number "5" in your right hand.
Multiply the numbers you're holding, putting the result in your left hand and dropping what's in your right hand.
This distinction between "right hand" and "left hand" is not important for symmetric operators like add and multiply; but it is vital for asymmetric operators like subtract, divide, and exponentiate.
Writing an infix-to-postfix translator is a pretty common problem for introductory/intermediate programming courses. There is no point trying to write a program until you understand what postfix notation is, why it works, and how to do the translations with pencil and paper.
Comment