Once an expression is in postfix form, evaluating it is easy: read the symbols from left to right, keep the operands on a stack, and apply each operator to the top two operands. This is the second step of the two-step method described in the study material.
The algorithm
Intuition
A calculator that works in postfix (“RPN” calculators) has a stack of numbers. Typing a number puts it on the stack. Pressing + takes the two top numbers, adds them, and puts the answer back. There is never any need for brackets.
Scan the postfix expression from left to right:
Operand: push it.
Operator op: pop the top item into b, pop the next item into a, compute a op b, and push the result.
End: the stack must contain exactly one item; that is the value. Any other number of items means the expression was invalid.
The first item popped is the right operand. For -, / and ^ the order matters: 8 2 / means 8 / 2 = 4 8 / 2 = 4 8/2 = 4 , not 2 / 8 2 / 8 2/8 .
Example 4.13 Evaluate 6 2 3 + - 3 8 2 / + * 2 ^ 3 +
Goal. Evaluate the postfix expression and show the stack after every token; also test some short and some invalid expressions.
Program. Tokens are separated by spaces, so multi-digit numbers work. The function returns 0 for an invalid expression (too few operands, leftover operands, division by zero).
C · postfix_eval.c Copy #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
long stack[MAX];
int top = - 1 ;
long ipow( long b, long e) /* b^e for e >= 0 */
{
long r = 1 ;
while (e -- > 0 )
r *= b;
return r;
}
/* Evaluate a postfix expression whose tokens are separated by spaces.
Returns 1 and stores the value in *result, or 0 if the expression is invalid. */
int eval_postfix( const char * expr, long * result, int trace)
{
char buf[MAX];
top = - 1 ;
strncpy(buf, expr, MAX - 1 );
buf[MAX - 1 ] = ' \0 ' ;
for ( char * tok = strtok(buf, " " ); tok != NULL ; tok = strtok( NULL , " " )) {
if (isdigit(( unsigned char )tok[ 0 ])) {
if (top == MAX - 1 )
return 0 ;
stack[ ++ top] = strtol(tok, NULL , 10 ); /* operand: push */
} else {
if (top < 1 )
return 0 ; /* need two operands */
long b = stack[top -- ]; /* right operand first! */
long a = stack[top -- ];
long r;
switch (tok[ 0 ]) {
case '+' : r = a + b; break ;
case '-' : r = a - b; break ;
case '*' : r = a * b; break ;
case '/' : if (b == 0 ) return 0 ; r = a / b; break ;
case '^' : r = ipow(a, b); break ;
default : return 0 ;
}
stack[ ++ top] = r; /* push the result */
}
if (trace) {
printf( " %-3s stack:" , tok);
for ( int i = 0 ; i <= top; i ++ )
printf( " %ld" , stack[i]);
printf( " \n " );
}
}
if (top != 0 )
return 0 ; /* operands left over */
* result = stack[ 0 ];
return 1 ;
}
int main( void )
{
long v;
const char * e1 = "6 2 3 + - 3 8 2 / + * 2 ^ 3 +" ;
printf( "%s \n " , e1);
if (eval_postfix(e1, & v, 1 ))
printf( "value = %ld \n\n " , v);
const char * more [] = { "5 3 -" , "2 3 4 * +" , "2 3 + 4 *" , "4 +" , "1 2 3 +" };
for ( int i = 0 ; i < 5 ; i ++ ) {
if (eval_postfix(more[i], & v, 0 ))
printf( "%-10s = %ld \n " , more[i], v);
else
printf( "%-10s : invalid expression \n " , more[i]);
}
return 0 ;
}
Run it.
Output Copy 6 2 3 + - 3 8 2 / + * 2 ^ 3 +
6 stack: 6
2 stack: 6 2
3 stack: 6 2 3
+ stack: 6 5
- stack: 1
3 stack: 1 3
8 stack: 1 3 8
2 stack: 1 3 8 2
/ stack: 1 3 4
+ stack: 1 7
* stack: 7
2 stack: 7 2
^ stack: 49
3 stack: 49 3
+ stack: 52
value = 52
5 3 - = 2
2 3 4 * + = 14
2 3 + 4 * = 20
4 + : invalid expression
1 2 3 + : invalid expression
Check by hand. 6 − ( 2 + 3 ) = 1 6 - (2 + 3) = 1 6 − ( 2 + 3 ) = 1 ; 3 + 8 / 2 = 7 3 + 8/2 = 7 3 + 8/2 = 7 ; 1 × 7 = 7 1 \times 7 = 7 1 × 7 = 7 ; 7 2 = 49 7^2 = 49 7 2 = 49 ; 49 + 3 = 52 49 + 3 = 52 49 + 3 = 52 .
Result. The expression evaluates to 52; 4 + (too few operands) and 1 2 3 + (operands left over) are rejected.
Putting the two steps together
To evaluate an infix expression such as (2 + 3) * 4: convert it to postfix (2 3 + 4 *), then evaluate the postfix (20). Each step is one pass with a stack, so the whole evaluation is O ( n ) O(n) O ( n ) . A prefix expression can be evaluated the same way by scanning from right to left ; then the first item popped is the left operand.
Key idea
To evaluate postfix, push operands and, at each operator, pop the right operand then the left operand, apply the operator and push the result; a valid expression leaves exactly one value on the stack.
TEE Exam note
“Evaluate the postfix expression … showing the contents of the stack” is a standard 4–6 mark question. Draw a table with columns “symbol” and “stack”, write the operation performed at each operator (e.g. “8 / 2 = 4”), and give the final value. Remember to pop the right operand first. Check Your Progress 2, Q2: postfix (and prefix) expressions are evaluated by stacks.
Common mistake
Reversing the operands: computing b - a instead of a - b. For 5 3 - the answer is 2, not −2.
Common mistake
Taking whatever is on top at the end as the answer without checking that the stack holds exactly one item. Leftover operands mean the expression was not valid.
Key takeaways
Operand: push. Operator: pop b, pop a, push a op b.
The first value popped is the right operand.
A valid postfix expression leaves exactly one value; too few or too many operands mean an error.
Infix evaluation = infix → postfix + postfix evaluation, both O ( n ) O(n) O ( n ) .
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice What is the value of the postfix expression 5 1 2 + 4 * + 3 -?
A 14 B 18 C 12 D 20
Check answer
Show answer Answer: A. 14
1 + 2 = 3; 3 × 4 = 12; 5 + 12 = 17; 17 − 3 = 14. Stopping before the final - would give 17.
Question 2 · multiple choice While evaluating 9 3 /, the evaluator pops 3 and then 9. What does it compute?
A 3 / 9 B 9 / 3 C 3 × 9 D 9 − 3
Check answer
Show answer Answer: B. 9 / 3
The first value popped (3) is the right operand, so the result is 9 / 3 = 3.
Question 3 · multiple choice What does this program print?
C · q4-eval.c Copy #include <stdio.h>
int main( void )
{
int st[ 10 ], top = - 1 ;
const char * e = "23*54*+9-" ; /* single-digit operands */
for ( const char * p = e; * p; p ++ ) {
if ( * p >= '0' && * p <= '9' ) {
st[ ++ top] = * p - '0' ;
} else {
int b = st[top -- ], a = st[top -- ];
st[ ++ top] = ( * p == '+' ) ? a + b : ( * p == '-' ) ? a - b : a * b;
}
}
printf( "%d \n " , st[top]);
return 0 ;
} A 26 B 35 C 17 D -17
Check answer
Show answer Answer: C. 17
2 × 3 = 6; 5 × 4 = 20; 6 + 20 = 26; 26 − 9 = 17. −17 would come from computing b - a instead of a - b.
Question 4 · multiple choice Which postfix expression is invalid?
A 4 2 -B 1 2 + 3 +C 1 + 2D 7
Check answer
Show answer Answer: C. 1 + 2
When + is read, only one operand is on the stack, so it cannot be applied. A single operand such as 7 is a valid expression whose value is 7.
Question 5 · multiple choice After all tokens of a postfix expression are processed, the stack holds two values. What does this mean?
A The answer is the top value. B The answer is the sum of the two values. C The expression had too many operators. D The expression had too many operands (or too few operators), so it is invalid.
Check answer
Show answer Answer: D. The expression had too many operands (or too few operators), so it is invalid.
Each binary operator reduces the stack by one item, so a valid expression with k k k operands has k − 1 k - 1 k − 1 binary operators and ends with one item.
Question 6 · short answer
Evaluate the postfix expression 8 2 3 ^ / 2 3 * + 5 1 * - showing the stack after each symbol.
Show worked answer 8 → [8]; 2 → [8 2]; 3 → [8 2 3]; ^: 2^3 = 8 → [8 8]; /: 8 / 8 = 1 → [1]; 2 → [1 2]; 3 → [1 2 3]; *: 2 × 3 = 6 → [1 6]; +: 1 + 6 = 7 → [7]; 5 → [7 5]; 1 → [7 5 1]; *: 5 × 1 = 5 → [7 5]; -: 7 − 5 = 2 → [2]. Value = 2.