An arithmetic expression has operands (the values, like A or 7) and operators (+ - * / ^). There are three ways to write where an operator goes relative to its two operands — and stacks are how computers read and convert between them.
A + B. How people write maths.+ A B. The operator comes before its operands.A B +. The operator comes after its operands. Old HP calculators, the Java Virtual Machine and many compilers work this way.What is 2 + 3 * 4? It's 14, not 20 — but only because we agreed that * binds tighter than +. Infix can't be read left to right without knowing these precedence rules, and when you want the other order you need brackets: (2 + 3) * 4.
Prefix and postfix need neither precedence rules nor brackets. The position of each operator already says when it runs:
infix prefix postfix
2 + 3 * 4 + 2 * 3 4 2 3 4 * +
(2 + 3) * 4 * + 2 3 4 2 3 + 4 *
(A + B) * (C - D) * + A B - C D A B + C D - *Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come