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

Infix to postfix conversion

Use an operator stack to rewrite an infix expression so that operators follow their operands.

Syllabus says: “Evaluation of Expressions - Infix to Postfix”

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

Operands go STRAIGHT to the output. Operators WAIT on the stack, but first pop everything of higher (or equal, if left-associative) precedence. ‘(’ waits; ‘)’ pops until ‘(’.

Picture it

A movie-ticket counter where VIPs (higher precedence) already standing in line must be served before a new ordinary person can join.

Write this in the exam

Scan the infix expression left to right: append operands to the output; push ‘(’; on ‘)’ pop to the output until ‘(’; on an operator, pop operators of higher or equal precedence (except right-associative ^) and then push it; finally pop everything.

Learning objectives

  • Explain prefix, infix and postfix notation.
  • Apply the operator-stack algorithm, with precedence and associativity, to convert an infix expression (asked in all three available KTU papers).
  • Present the conversion as a Symbol | Stack | Postfix table.

Prerequisites

Stacks; operator precedence in C (* before +).

Introduction

In A + B * C you must look ahead to realise that * is done first. Brackets and precedence rules make infix hard for a program to evaluate in one left-to-right pass. Postfix (reverse Polish) notation puts each operator after its operands, so the order of evaluation is written into the expression itself and no brackets are needed.

Definitions

NotationExampleRule
InfixA + B * Coperator between operands
Prefix (Polish)+ A * B Coperator before operands
Postfix (reverse Polish)A B C * +operator after operands
C has no ^ operator; textbooks use it for exponentiation.
OperatorPrecedenceAssociativity
^3 (highest)right to left: A^B^C = A^(B^C)
* / %2left to right
+ −1 (lowest)left to right: A−B−C = (A−B)−C

The algorithm

  1. Scan the infix expression from left to right.
  2. Operand → append it to the output.
  3. ‘(’ → push it.
  4. ‘)’ → pop operators to the output until ‘(’ is on top; pop and discard the ‘(’.
  5. Operator t → while the top of the stack is an operator with higher precedence, or with equal precedence when t is left-associative, pop it to the output. Then push t.
  6. At the end, pop every remaining operator to the output.
Pro tipWhy equal precedence pops for − but not for ^

For A − B − C, the first − must be applied first, so it is popped before the second is pushed: A B − C −. For A ^ B ^ C the right ^ must be applied first, so the earlier ^ stays on the stack: A B C ^ ^.

A second KTU example (May 2026 Q10a), reading the scan's ‘C\D’ as C/D: A+(B−C/D*E)+F/G becomes A B C D / E * − + F G / +. Try it in the visualizer below.

Worked example

Worked example (KTU Nov 2025 Q10a): (A+B*C/D)-(E-F/G)checked by code
SymbolStackPostfix
((
A(A
+( +A
B( +A B
*( + *A B
C( + *A B C
/( + /A B C *
D( + /A B C * D
)emptyA B C * D / +
--A B C * D / +
(- (A B C * D / +
E- (A B C * D / + E
-- ( -A B C * D / + E
F- ( -A B C * D / + E F
/- ( - /A B C * D / + E F
G- ( - /A B C * D / + E F G
)-A B C * D / + E F G / -
endemptyA B C * D / + E F G / - -

Postfix: A B C * D / + E F G / - -

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

Infix to postfix
  1. 1InfixToPostfix(E): stack ← empty; output ← empty
  2. 2for each token t of E (left to right):
  3. 3if t is an operand: append t to output
  4. 4else if t = '(': push t
  5. 5else if t = ')':
  6. 6while top ≠ '(': append pop() to output
  7. 7pop() and discard '('
  8. 8else (t is an operator):
  9. 9while stack not empty and top ≠ '(' and
  10. 10(prec(top) > prec(t) or (prec(top) = prec(t) and t is left-assoc)):
  11. 11append pop() to output
  12. 12push t
  13. 13while stack not empty:
  14. 14append pop() to output
  15. 15return output

C implementation

infix_to_postfix.ctested ✓ 408/408 cases
C
/* Infix to postfix conversion using a stack — KTU PCCST303, Module 1
 * Operands: single letters or whole numbers. Operators: + - * / % ^
 * Precedence: ^ (right-associative) > * / % > + -   (others left-assoc.)
 * Input : one infix expression per line.
 * Output: "POSTFIX: tokens separated by spaces"  or  "ERROR: reason"      */
#include <ctype.h>
#include <stdio.h>
#include <string.h>

#define MAXTOK 64

char tok[MAXTOK][12];      /* tokens of the input */
int ntok;
char stack[MAXTOK][12];    /* operator stack */
int top = -1;

int prec(const char *t) {
    switch (t[0]) {
    case '^': return 3;
    case '*': case '/': case '%': return 2;
    case '+': case '-': return 1;
    default: return 0;      /* '(' or not an operator */
    }
}
int is_operator(const char *t) { return t[1] == '\0' && strchr("+-*/%^", t[0]) != NULL; }
int is_operand(const char *t)  { return isalnum((unsigned char)t[0]); }

/* Split the line into tokens; returns 0 on an illegal character. */
int tokenize(const char *s) {
    ntok = 0;
    for (int i = 0; s[i] != '\0' && s[i] != '\n'; ) {
        unsigned char c = (unsigned char)s[i];
        if (isspace(c)) { i++; continue; }
        if (ntok == MAXTOK) return 0;
        if (isdigit(c)) {                               /* whole number */
            int j = 0;
            while (isdigit((unsigned char)s[i])) {
                if (j == 9) return 0;                   /* at most 9 digits */
                tok[ntok][j++] = s[i++];
            }
            tok[ntok][j] = '\0';
            /* drop leading zeros so "007" prints as "7" */
            char *p = tok[ntok];
            while (p[0] == '0' && p[1] != '\0') p++;
            memmove(tok[ntok], p, strlen(p) + 1);
        } else if (isalpha(c) || strchr("+-*/%^()", c) != NULL) {
            tok[ntok][0] = (char)c; tok[ntok][1] = '\0'; i++;
        } else return 0;
        ntok++;
    }
    return ntok > 0;
}

/* Operand/operator must alternate and parentheses must balance. */
int valid(void) {
    int expect_operand = 1, depth = 0;
    for (int k = 0; k < ntok; k++) {
        const char *t = tok[k];
        if (expect_operand) {
            if (is_operand(t)) expect_operand = 0;
            else if (t[0] == '(') depth++;
            else return 0;
        } else {
            if (is_operator(t)) expect_operand = 1;
            else if (t[0] == ')') { if (--depth < 0) return 0; }
            else return 0;
        }
    }
    return !expect_operand && depth == 0;
}

void push(const char *t) { strcpy(stack[++top], t); }
const char *pop(void)    { return stack[top--]; }

int main(void) {
    char line[512];
    while (fgets(line, sizeof line, stdin) != NULL) {
        if (!tokenize(line) || !valid()) { printf("ERROR: invalid expression\n"); continue; }
        top = -1;
        printf("POSTFIX:");
        for (int k = 0; k < ntok; k++) {
            const char *t = tok[k];
            if (is_operand(t)) printf(" %s", t);
            else if (t[0] == '(') push(t);
            else if (t[0] == ')') {
                while (stack[top][0] != '(') printf(" %s", pop());
                top--;                                  /* discard '(' */
            } else {
                while (top >= 0 && stack[top][0] != '(' &&
                       (prec(stack[top]) > prec(t) ||
                        (prec(stack[top]) == prec(t) && t[0] != '^')))
                    printf(" %s", pop());
                push(t);
            }
        }
        while (top >= 0) printf(" %s", pop());
        printf("\n");
    }
    return 0;
}
Sample run · Nov 2025 Q10a and May 2026 Q10a · real output from gcc

Input (stdin)

(A+B*C/D)-(E-F/G)
A+(B-C/D*E)+F/G

Output (stdout)

POSTFIX: A B C * D / + E F G / - -
POSTFIX: A B C D / E * - + F G / +

Open in the Code Lab →

Complexity

Each token is pushed at most once and popped at most once, so the conversion is O(n) time and O(n) space for n tokens.

Edge cases and validation

  • Unbalanced brackets: a ‘)’ with no matching ‘(’, or a ‘(’ left at the end, means the expression is invalid.
  • Two operands or two operators in a row are invalid.
  • Unary minus (−A) needs special handling; write it as (0−A).

Common mistakes

  • Pushing an operator without first popping the higher- or equal-precedence ones.
  • Putting ‘(’ or ‘)’ in the postfix output.
  • Treating ^ as left-associative.
  • Forgetting to empty the stack at the end.

Asked in KTU exams (3)

Quick check — can you get them all?

Question 1

Q1.Postfix of A + B * C?

Question 2

Q2.Postfix of A ^ B ^ C?

Question 3

Q3.Postfix of A + B * C / D − E * F / G (KTU Nov 2025 Q10a, minus the parentheses)?

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

  • Operands → output; ‘(’ → push; ‘)’ → pop until ‘(’.
  • Operator: pop while top has higher precedence (or equal and left-assoc), then push.
  • End: pop everything.
  • Show the Symbol | Stack | Postfix table — it earns the marks.
  • O(n).

References

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

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)