Problem Description
When working with basic arithmetic operators such as addition, subtraction, multiplication and division, there is sometimes the need to add parenthesis to force the order of operations. This is true in both mathematics and when programming. However there is an alternative. Jan Łukasiewicz, a Polish logician and philosopher, invented in the 1920s what is now known as prefix notation, also known as Polish notation due to the nationality of Łukasiewicz. Later in the 1950s, several computer scientists created postfix notation, which is also known as Reverse Polish Notation (RPN).
During the 1970s and 1980s, Hewlett-Packard made calculators that accepted input in RPN. This influenced a generation of engineers who relied upon those calculators.
You will write a program that accepts simple RPN statements as input, performs the requested calculation, and prints the result to the console.
Reverse Polish Notation
Consider the expression “a + b”. This is in standard algebraic notation, also know as infix notation because the addition operator appears in between the a and b. The same expression in RPN is “a b +”. As mentioned above, RPN is also known as postfix notation because the addition operator appears after its operands of a and b. By contrast the expression “+ a b” would be in prefix notation.
The benefit of RPN is that parenthesis are not needed. Consider the expression “a * (b + c)”. This is written in RPN as “a b c + *”. This is evaluated by reading the expression from left to right. When an operator is encountered, in this case the first is addition, the two most recently seen values are the arguments. The result is then substituted in place and processing of the expression continues until the end.
For reference, you have likely encountered RPN previously and did not know it. For example, the factorial function (i.e. 3! = 3 * 2 * 1) is written in RPN.
Your Program
Your program will read in simple RPN expressions and calculate the result. Full processing of a RPN expression is a bit beyond where we are now, so we will only deal with simplified single operator expressions. That is, you will need to take as input two numbers and one character.
The operations you need to support are addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^).