Expression Evaluation (Cambridge International A-Level Computer Science)
Exam board Cambridge International · A-LevelUpdated 2025-05-23
Reverse Polish Notation (RPN)
What is RPN?
-
Reverse Polish Notation (RPN) is a method of writing mathematical expressions where the operator comes after the operands
-
This is also known as postfix notation
- Infix:
3 + 4 - RPN:
3 4 +
- Infix:
Why use RPN?
- No need for brackets: The order of operations is determined by position, not parentheses
- Easier for computers to evaluate using a stack
- Always unambiguous
How RPN works
- RPN uses a stack to evaluate expressions
- Read from left to right
- Push numbers onto the stack
- When an operator is read:
- Pop the top two values from the stack
- Apply the operator
- Push the result back onto the stack
- When the expression ends, the final result is at the top of the stack
Example: evaluate 3 4 + 2 ×
| Step | Action | Stack |
|---|---|---|
Read 3 | Push to stack | 3 |
Read 4 | Push to stack | 3 4 |
Read + | Add 3 + 4 → 7 | 7 |
Read 2 | Push to stack | 7 2 |
Read × | Multiply 7 × 2 → 14 | 14 |
- Final result:
14
Example: convert this infix expression to RPN
- Split the expression into parts:
- Left-hand side:
(7 − 2 + 8)
- This becomes:
( (7 − 2) + 8 )
- Which in RPN is:
7 2 − 8 +
- Right-hand side:
(9 − 5)
- In RPN:
9 5 −
- Combine with the division
- In RPN, that becomes:
7 2 − 8 + 9 5 − ÷
Exam Hint RPN follows the evaluation order naturally, so there’s no need for brackets or precedence rules. Just:
- Work from inside brackets out
- Convert each sub-expression
- Add the operator after its operands
Summary
| Concept | Description |
|---|---|
| RPN (Postfix) | Operators follow operands |
| Stack | Used to store and evaluate values |
| Evaluation method | Push numbers, pop and evaluate on operator |
| Benefits | No brackets, no ambiguity, easy to compute with stack |
Was this revision note helpful?
Build on this topic