Evaluating expressions: postfix
A postfix expression puts each operator after its two numbers, so 3 + 4 * 2 becomes 3 4 2 * +, with no brackets or precedence; one stack works it out left to right: numbers are pushed, and an operator pops two and pushes the result.
People write 3 + 4 * 2 and rely on "multiply before adding" and brackets. A program reads left to right, and at the + it doesn't know yet whether a * is coming. The way out is another notation: postfix (also called reverse Polish notation), with each operator after its two numbers: 3 4 2 * +. It has no brackets and no precedence, and one stack works it out left to right.
How postfix is worked out
Read from left to right:
- A number: push it.
- An operator: pop twice. The first one out is the right-hand number b, the second is the left-hand number a; work out
a op band push the result. - At the end: the one number left on the stack is the answer.
top1#include <stdio.h>2#include <ctype.h>3 4// one-digit numbers only: each character is a number or an operator5int eval(const char *s) {6 int st[100], top = -1;7 for (int i = 0; s[i] != '\0'; i++) {8 char c = s[i];9 if (isdigit(c)) {10 st[++top] = c - '0';11 } else {12 int b = st[top--]; // the first out is the right-hand one13 int a = st[top--];14 int r = c == '+' ? a + b : c == '-' ? a - b : c == '*' ? a * b : a / b;15 st[++top] = r;16 }17 }18 return st[top];19}20 21int main(void) {22 printf("%d\n", eval("34+2*"));23 printf("%d\n", eval("512+4*+3-"));24 return 0;25}
14 14
The second is 5 + (1 + 2) * 4 - 3, in postfix 5 1 2 + 4 * + 3 -, and it is 14 too.
This works out the postfix expression 9 3 - 2 /. What does it print?
1#include <stdio.h>2 3int main(void) {4 int st[10], top = -1;5 st[++top] = 9;6 st[++top] = 3;7 int b = st[top--];8 int a = st[top--];9 st[++top] = a - b;10 st[++top] = 2;11 b = st[top--];12 a = st[top--];13 st[++top] = a / b;14 printf("%d\n", st[top]);15 return 0;16}
What is the value of the postfix expression 6 2 3 + *?
+, 3 and 2 come off and 5 goes on, leaving 6 5; at *, 6 × 5 = 30. In infix it is 6 * (2 + 3). 15 is what you get by reading it as 6 × 2 + 3.When the program reads -, it does three things. Put these three lines in order so it works out the postfix expression 8 2 - and prints 6.
int a = st[top--];int b = st[top--];st[++top] = a - b;
6
a - b = 6 is pushed. Swap the first two lines and a and b trade places, giving 2 − 8 = −6.Work out postfix
✓Finish eval: numbers are pushed, an operator pops twice and pushes the result. Watch which way round − and / go.
9 6
1#include <stdio.h>2#include <ctype.h>3 4int eval(const char *s) {5 int st[100], top = -1;6 for (int i = 0; s[i] != '\0'; i++) {7 char c = s[i];8 // number: push c - '0'; operator: b out first, then a, push a op b9 }10 return st[top];11}12 13int main(void) {14 printf("%d %d\n", eval("52-3*"), eval("62/3+"));15 return 0;16}
Turning infix into postfix
The conversion uses a stack too, this time holding operators:
- A number: write it straight to the output.
(: push.): pop to the output until(, then throw the(away.- An operator: first pop to the output every operator on top with the same or higher precedence (stopping at
(), then push it. - At the end: pop everything left to the output.
Here is 3 + 4 * 2 - 1 step by step:
| Read | What happens | Output | Operator stack |
|---|---|---|---|
| 3 | to the output | 3 | |
| + | stack empty, push | 3 | + |
| 4 | to the output | 3 4 | + |
| * | + on top is lower than *, no pop; push | 3 4 | + * |
| 2 | to the output | 3 4 2 | + * |
| - | * on top is higher than -, pop; + is the same as -, pop too; then push - | 3 4 2 * + | - |
| 1 | to the output | 3 4 2 * + 1 | - |
| end | pop everything | 3 4 2 * + 1 - |
The same in "the same or higher" matters: - meeting a + on the stack pops it first, so 8 - 3 + 1 is worked out left to right as 6, not as 8 − (3 + 1).
1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5 return (op == '*' || op == '/') ? 2 : (op == '+' || op == '-') ? 1 : 0; // ( is 06}7 8void to_postfix(const char *s, char *out) {9 char st[100];10 int top = -1, k = 0;11 for (int i = 0; s[i] != '\0'; i++) {12 char c = s[i];13 if (isdigit(c)) {14 out[k++] = c;15 } else if (c == '(') {16 st[++top] = c;17 } else if (c == ')') {18 while (st[top] != '(')19 out[k++] = st[top--];20 top--; // throw the ( away21 } else {22 while (top >= 0 && prio(st[top]) >= prio(c))23 out[k++] = st[top--];24 st[++top] = c;25 }26 }27 while (top >= 0)28 out[k++] = st[top--];29 out[k] = '\0';30}31 32int main(void) {33 const char *tests[] = {"3+4*2-1", "(1+2)*3-4/2", "8-3+1"};34 char out[100];35 for (int t = 0; t < 3; t++) {36 to_postfix(tests[t], out);37 printf("%-12s -> %s\n", tests[t], out);38 }39 return 0;40}
3+4*2-1 -> 342*+1- (1+2)*3-4/2 -> 12+3*42/- 8-3+1 -> 83-1+
Giving ( precedence 0 means rule 4's "stop at (" needs no code of its own: every operator is higher than it, so it is never popped there.
What is the infix (3 + 4) * 2 in postfix?
( is pushed; 3 goes to the output; + is pushed; 4 goes out; ) pops + to the output and throws away (; * is pushed; 2 goes out; at the end * is popped. What's in the brackets comes first, so 3 4 + is written first.Fill in the comparison so that 8-3+1*2 comes out as the right postfix, 83-12*+.
1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5 return (op == '*' || op == '/') ? 2 : 1;6}7 8int main(void) {9 const char *s = "8-3+1*2";10 char st[100], out[100];11 int top = -1, k = 0;12 for (int i = 0; s[i] != '\0'; i++) {13 char c = s[i];14 if (isdigit(c)) {15 out[k++] = c;16 } else {17 while (top >= 0 && prio(st[top]) prio(c))18 out[k++] = st[top--];19 st[++top] = c;20 }21 }22 while (top >= 0)23 out[k++] = st[top--];24 out[k] = '\0';25 printf("%s\n", out);26 return 0;27}
+ first sends - to the output, so 8 - 3 is done first, left to right. * is higher than +, so + stays and * is pushed.Infix to postfix
✓Finish the operator branch: first pop to the output every operator on top with the same or higher precedence, then push it. There are no brackets here.
123*+4-
1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5 return (op == '*' || op == '/') ? 2 : 1;6}7 8int main(void) {9 const char *s = "1+2*3-4";10 char st[100], out[100];11 int top = -1, k = 0;12 for (int i = 0; s[i] != '\0'; i++) {13 char c = s[i];14 if (isdigit(c)) {15 out[k++] = c;16 } else {17 // pop to out while the top's precedence >= c's, then push c18 }19 }20 while (top >= 0)21 out[k++] = st[top--];22 out[k] = '\0';23 printf("%s\n", out);24 return 0;25}
Converting by hand in exams: the bracket trick
Exam questions often just want the answer, not every step on the stack. There's a quick way, in three steps:
- Put brackets round every step, in the order it is worked out:
3 + 4 * 2 - 1becomes((3 + (4 * 2)) - 1). - Move each operator just past its closing bracket.
- Drop all the brackets:
3 4 2 * + 1 -.
Move each operator just before its opening bracket instead and you get the prefix expression (Polish notation): - + 3 * 4 2 1. The numbers never change order, only the operators move, which is a quick way to rule out wrong answers.
Which is the postfix form of a * b + c / d?
((a * b) + (c / d)). Each operator goes past its closing bracket: a b *, c d /, and + last, so a b * c d / +. The letters stay in the order a b c d.Which is the prefix form of a + b * (c - d)?
(a + (b * (c - d))). Each operator moves in front of its opening bracket: + a * b - c d. a b c d - * + is the postfix form.Summary
Evaluating expressions: to postfix first, then one stack
- Evaluate: push numbers; an operator pops b, then a, and pushes a op b
- Convert: numbers straight out; an operator pops everything on top with precedence ≥ its own, then is pushed
- ( is pushed; ) pops back to (; at the end pop everything
1int b = st[top--], a = st[top--];2st[++top] = a - b; // the second out minus the first3while (top >= 0 && prio(st[top]) >= prio(c))4 out[k++] = st[top--];