Kodewick
Start learning →
Evaluating expressions: postfix13 / 50

Evaluating expressions: postfix

Lesson 13 of 50 · Part 3 · Stacks and queues · about 15 minutes

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 b and push the result.
  • At the end: the one number left on the stack is the answer.
stack (bottom on the left)012

Working out 3 4 + 2 *: each operator takes two numbers off the top and puts the result back
main.c
1#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}
Output
14
14

The second is 5 + (1 + 2) * 4 - 3, in postfix 5 1 2 + 4 * + 3 -, and it is 14 too.

Guess the outputA wrong guess is fine

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}
Choose one

What is the value of the postfix expression 6 2 3 + *?

Put in orderDrag, or use the arrows

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.

  1. int a = st[top--];
  2. int b = st[top--];
  3. st[++top] = a - b;
Should print
6
Exercise 1

Work out postfix

Finish eval: numbers are pushed, an operator pops twice and pushes the result. Watch which way round − and / go.

It should print
9 6
exercise1.c
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}
Output
Press Run or Ctrl+Enter

Turning infix into postfix

The conversion uses a stack too, this time holding operators:

  1. A number: write it straight to the output.
  2. (: push.
  3. ): pop to the output until (, then throw the ( away.
  4. An operator: first pop to the output every operator on top with the same or higher precedence (stopping at (), then push it.
  5. At the end: pop everything left to the output.

Here is 3 + 4 * 2 - 1 step by step:

ReadWhat happensOutputOperator stack
3to the output3
+stack empty, push3+
4to the output3 4+
*+ on top is lower than *, no pop; push3 4+ *
2to the output3 4 2+ *
-* on top is higher than -, pop; + is the same as -, pop too; then push -3 4 2 * +-
1to the output3 4 2 * + 1-
endpop everything3 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).

main.c
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}
Output
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.

Choose one

What is the infix (3 + 4) * 2 in postfix?

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 2

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.

It should print
123*+4-
exercise2.c
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}
Output
Press Run or Ctrl+Enter

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:

  1. Put brackets round every step, in the order it is worked out: 3 + 4 * 2 - 1 becomes ((3 + (4 * 2)) - 1).
  2. Move each operator just past its closing bracket.
  3. 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.

Choose one

Which is the postfix form of a * b + c / d?

Choose one

Which is the prefix form of a + b * (c - d)?

Summary

Take-away

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--];