Write an algorithm to evaluate postfix expression with example.

Step 1: Add a right parenthesis “)” at the end of the expression.

Step 2: Scan P from left o right and repeat steps 3 and 4 for each elements of expression until the “)” is encountered.

Step 3: If an operand is encountered, put it on STACK.

Step 4: If an operator is encountered, then

  1. Remove the two top elements of STACK, where A is the top element and B is the next-to-top element.
  2. Evaluate B (operator) A
  3. Place the result on to the STACK.

Step 5: Result equal to the top element on STACK.

Step 6: Exit.

Symbol

opnd 1

opnd 2

value

opndstack

4

 

 

 

4

3

 

 

 

4,3

2

 

 

 

4,3,2

5

 

 

 

4,3,2,5

*

2

5

10

4,3

 

 

 

 

4,3,10

-

3

10

-7

4

 

 

 

 

4,7

+

4

-7

-3

 

 

 

 

 

-3(result)

 

Share with

Comments 0

Add your comment