Most calculators use infix notation, in which the operator is typed between the operands. Everyone is familiar with solving infix math expressions, such as 2 + 3
, or 9 - 5
.
There are two other types of notation: prefix and postfix. In prefix, the operator comes before ("pre") the operands, such as in these expressions: + 2 3
or - 9 5
.
Postfix expressions are used on some specialized calculators called RPN calculators, so complex math expressions can be entered without the need for parentheses. Postfix math is also called reverse polish notation (RPN). RPN is defined as a mathematical expression in which the numbers precede the operation (i.e., 2 + 2 is 2 2 + in RPN, or 10 - 3 * 4 is 10 3 4 * - in RPN). Postfix statements look like 2 3 +
or 9 5 -
.
Here is a comparison of infix versus postfix math expressions:
infix |
postfix |
5 + ((7 + 9) * 2)
|
5 7 9 + 2 * +
|
A postfix expression is evaluated as follows:
- if a value is entered, it is placed on the stack
- if an operation is entered (+, -, *, /), the stack is popped twice and the operation is applied to those two numbers. The resulting answer is placed back on the stack.
The expression 5 7 9 + 2 * +
is solved in this order:
5 16 2 * +
5 32 +
37
Notice that postfix expressions are simply solved by moving from left to right and parentheses are not needed.
The following special cases must be addressed:
- if the problem to be solved is 7 - 5
(infix), the problem is entered on an RPN calculator in the following order.
7 (enter)
5 (enter)
-
This causes the stack to be popped twice and the correct expression to be evaluated is:
7 5 -
The answer is 2
.
A similar ordering issue surrounds the (/
) operator:
If the problem to be solved is 9 / 2
(infix), the problem is entered on an RPN calculator as:
9
2
/
The answer is 4
.