Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 1 · syllabusAsked 2× in KTU papersChecked by code · teacher review pending

Evaluating postfix expressions

Evaluate a postfix expression in one pass with a stack of operands.

Syllabus says: “Evaluating Postfix Expressions”

On this page · 17 sections
ormakkurippu ✎
Never-forget card

Number → PUSH. Operator → POP TWICE: the FIRST pop is the RIGHT operand. Push the result. The last value left is the answer.

Picture it

Collecting ingredients on a tray (stack); when a recipe step (operator) comes, you take the top two ingredients, combine them and put the dish back.

Write this in the exam

Scan the postfix expression left to right; push operands; on an operator pop op2 then op1, compute op1 operator op2 and push the result; at the end the stack holds the value.

Learning objectives

  • Evaluate a postfix expression with an operand stack.
  • Pop operands in the correct order for − and /.
  • Detect invalid postfix expressions.

Prerequisites

Stacks; infix-to-postfix conversion.

Introduction

Postfix was designed for this: read left to right, keep the numbers you have seen on a stack, and whenever an operator appears, apply it to the two most recent numbers. Brackets and precedence never come into it.

Algorithm

  1. Scan the postfix expression from left to right.
  2. Operand → push its value.
  3. Operator op → b ← pop(), a ← pop(), push (a op b).
  4. At the end exactly one value must remain on the stack; it is the result.
Watch outOrder of operands

The first value popped is the right operand. For ‘8 4 /’ you pop b = 4, then a = 8, and compute 8 / 4 = 2, not 4 / 8.

Integer or real division?

The model paper (Q11a) asks to evaluate 4*5/3−(4%2)+(1*5)−2 without saying whether / is integer division.

Integer division (as in C): 20 / 3 = 6checked by code
SymbolStackPostfix
4empty4
**4
5*4 5
//4 5 *
3/4 5 * 3
--4 5 * 3 /
(- (4 5 * 3 /
4- (4 5 * 3 / 4
%- ( %4 5 * 3 / 4
2- ( %4 5 * 3 / 4 2
)-4 5 * 3 / 4 2 %
++4 5 * 3 / 4 2 % -
(+ (4 5 * 3 / 4 2 % -
1+ (4 5 * 3 / 4 2 % - 1
*+ ( *4 5 * 3 / 4 2 % - 1
5+ ( *4 5 * 3 / 4 2 % - 1 5
)+4 5 * 3 / 4 2 % - 1 5 *
--4 5 * 3 / 4 2 % - 1 5 * +
2-4 5 * 3 / 4 2 % - 1 5 * + 2
endempty4 5 * 3 / 4 2 % - 1 5 * + 2 -
SymbolActionStack
4push 44
5push 54 5
*4 * 5 = 2020
3push 320 3
/20 / 3 = 66
4push 46 4
2push 26 4 2
%4 % 2 = 06 0
-6 - 0 = 66
1push 16 1
5push 56 1 5
*1 * 5 = 56 5
+6 + 5 = 1111
2push 211 2
-11 - 2 = 99

Postfix: 4 5 * 3 / 4 2 % - 1 5 * + 2 - · Result: 9 (integer division)

With real division, 20 / 3 = 6.6667 and the result is 9.6667. In the exam, write which interpretation you use; % (remainder) only makes sense for integers, which suggests integer arithmetic was intended.

Worked example

Worked example (KTU Nov 2025 Q10a, second part): A..G = 3, 2, 4, 2, 5, 8, 4checked by code
SymbolActionStack
3push 33
2push 23 2
4push 43 2 4
*2 * 4 = 83 8
2push 23 8 2
/8 / 2 = 43 4
+3 + 4 = 77
5push 57 5
8push 87 5 8
4push 47 5 8 4
/8 / 4 = 27 5 2
-5 - 2 = 37 3
-7 - 3 = 44

Result: 4 (integer division)

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Algorithm / pseudocode

Evaluating a postfix expression
  1. 1EvaluatePostfix(P): stack ← empty
  2. 2for each token t of P (left to right):
  3. 3if t is an operand: push value(t)
  4. 4else (t is an operator):
  5. 5b ← pop(); a ← pop() // b first!
  6. 6push (a t b)
  7. 7return pop() // exactly one value must remain

C implementation

postfix_eval.ctested ✓ 400/400 cases
C
/* Evaluation of a postfix expression using a stack — KTU PCCST303, Module 1
 * Tokens are whole numbers and the operators + - * / % ^, separated by spaces.
 * Integer arithmetic as in C: / truncates toward zero, % takes the sign of the
 * dividend. Values are limited to +/- 10^15 to rule out overflow.
 * Input : one postfix expression per line.
 * Output: "RESULT: value"  or  "ERROR: reason"                              */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LIMIT 1000000000000000LL   /* 10^15 */
#define MAXSTACK 64

long long stack[MAXSTACK];
int top = -1;

/* Returns 1 and stores the result in *r, or returns 0 with *err set. */
int apply(long long a, char op, long long b, long long *r, const char **err) {
    switch (op) {
    case '+': *r = a + b; break;
    case '-': *r = a - b; break;
    case '*':
        if (a != 0 && llabs(b) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
        *r = a * b; break;
    case '/': if (b == 0) { *err = "division by zero"; return 0; } *r = a / b; break;
    case '%': if (b == 0) { *err = "division by zero"; return 0; } *r = a % b; break;
    case '^':
        if (b < 0) { *err = "negative exponent"; return 0; }
        if (a == 0 || a == 1) { *r = (b == 0) ? 1 : a; break; }
        if (a == -1) { *r = (b % 2 == 0) ? 1 : -1; break; }
        *r = 1;
        for (long long i = 0; i < b; i++) {
            if (llabs(*r) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
            *r *= a;
        }
        break;
    default: *err = "unknown operator"; return 0;
    }
    if (*r > LIMIT || *r < -LIMIT) { *err = "value too large"; return 0; }
    return 1;
}

const char *evaluate(char *line, long long *result) {
    top = -1;
    for (char *t = strtok(line, " \t\r\n"); t != NULL; t = strtok(NULL, " \t\r\n")) {
        if (isdigit((unsigned char)t[0])) {
            if (top == MAXSTACK - 1) return "stack overflow";
            stack[++top] = strtoll(t, NULL, 10);
        } else if (t[1] == '\0' && strchr("+-*/%^", t[0]) != NULL) {
            if (top < 1) return "operator needs two operands";
            long long b = stack[top--];                 /* right operand first! */
            long long a = stack[top--];
            long long r;
            const char *err = NULL;
            if (!apply(a, t[0], b, &r, &err)) return err;
            stack[++top] = r;
        } else return "bad token";
    }
    if (top != 0) return "invalid postfix expression";
    *result = stack[0];
    return NULL;
}

int main(void) {
    char line[512];
    while (fgets(line, sizeof line, stdin) != NULL) {
        long long r = 0;
        const char *err = evaluate(line, &r);
        if (err) printf("ERROR: %s\n", err);
        else printf("RESULT: %lld\n", r);
    }
    return 0;
}
Sample run · model Q11a · real output from gcc

Input (stdin)

4 5 * 3 / 4 2 % - 1 5 * + 2 -

Output (stdout)

RESULT: 9

Open in the Code Lab →

Complexity

One push or two pops plus one push per token: O(n) time, O(n) stack space.

Detecting invalid expressions

  • An operator finds fewer than two values on the stack → too few operands (e.g. ‘4 +’).
  • More than one value remains at the end → too many operands (e.g. ‘4 5’).
  • Division or % by zero → undefined; report an error.

Common mistakes

  • Computing b op a instead of a op b.
  • Pushing operators onto the stack (only operands go on it).
  • Forgetting to substitute the variable values before starting.

Asked in KTU exams (2)

Quick check — can you get them all?

Question 1

Q1.Evaluate 6 2 3 + − 3 8 2 / + *

Question 2

Q2.Evaluating ‘8 2 −’, the first value popped is…

Question 3

Q3.Evaluating a postfix expression of n symbols takes…

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Operand → push. Operator → b = pop, a = pop, push a op b.
  • Answer = the single value left.
  • Show a Symbol | Action | Stack table.
  • O(n).

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 3 (Stacks and Queues) §3.6

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)