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
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 ‘(’.
A movie-ticket counter where VIPs (higher precedence) already standing in line must be served before a new ordinary person can join.
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
| Notation | Example | Rule |
|---|---|---|
| Infix | A + B * C | operator between operands |
| Prefix (Polish) | + A * B C | operator before operands |
| Postfix (reverse Polish) | A B C * + | operator after operands |
| Operator | Precedence | Associativity |
|---|---|---|
| ^ | 3 (highest) | right to left: A^B^C = A^(B^C) |
| * / % | 2 | left to right |
| + − | 1 (lowest) | left to right: A−B−C = (A−B)−C |
The algorithm
- Scan the infix expression from left to right.
- Operand → append it to the output.
- ‘(’ → push it.
- ‘)’ → pop operators to the output until ‘(’ is on top; pop and discard the ‘(’.
- 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.
- At the end, pop every remaining operator to the output.
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
| Symbol | Stack | Postfix |
|---|---|---|
| ( | ( | |
| A | ( | A |
| + | ( + | A |
| B | ( + | A B |
| * | ( + * | A B |
| C | ( + * | A B C |
| / | ( + / | A B C * |
| D | ( + / | A B C * D |
| ) | empty | A 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 / - |
| end | empty | A 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 ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1InfixToPostfix(E): stack ← empty; output ← empty
- 2for each token t of E (left to right):
- 3if t is an operand: append t to output
- 4else if t = '(': push t
- 5else if t = ')':
- 6while top ≠ '(': append pop() to output
- 7pop() and discard '('
- 8else (t is an operator):
- 9while stack not empty and top ≠ '(' and
- 10(prec(top) > prec(t) or (prec(top) = prec(t) and t is left-assoc)):
- 11append pop() to output
- 12push t
- 13while stack not empty:
- 14append pop() to output
- 15return output
C implementation
infix_to_postfix.ctested ✓ 408/408 cases/* 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 / +
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)
- November 2025 · Q10a6 markssolved ✓Convert the infix expression (A+B*C/D)-(E-F/G) to postfix form using a stack. Evaluate the resultant postfix expression by replacing A,B,C,D,E,F and G with 3,2,4,2,5,8 and 4.
- May 2026 · Q10a6 markssolved ✓Write algorithm for convert the given infix expression to postfix expression. Using a stack convert infix expression A+(B-C\D*E)+F/G to postfix expression.
- — 2024 · Q11a5 markssolved ✓Evaluate the given expression using stack 4*5/3-(4%2)+(1*5)-2
Quick check — can you get them all?
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)