This blog is under construction

Thursday, 28 February 2013

How To Evaluate Postfix Expressions

Algorithm For Evaluating Postfix Expression:
  • Read one input character at a time.
  • If the input character is an operand, push it into the stack.
  • If the input character is an operator, then pop two elements from the stack, apply the operator to those two elements and push the result into the stack.


10 20 * 30 40 10 / - +

Input character is 10.  So, push it into the stack.

| 10 |
 -----

Input character is 20.  So, push it into the stack.

| 20 |
| 10 |
 -----

Input character is '*'.  So, pop two elements from the stack, apply operator to those two operands and push the result into the stack.

|       |
| 200 |
 -------

Input character is 30.  So, push it into the stack.

|      |
| 30  |
| 200|
 ------

Input character is 40.  So, push it into the stack.

| 40  |
| 30  |
| 200|
 ------

Input character is 10, push it into the stack.

| 10  |
| 40  |
| 30  |
| 200|
 ------

Input character is /.  So, pop two operand from the stack and apply operator to those two operands and push the result into the stack.

| 4    |
| 30  |
| 200|
 ------

Input character is -.

| 26   |
| 200 |
 -------

Input character is '+'.  So, pop two operand from the stack and apply operator to those two operands and push the result into the stack.

| 226 |
 -------

See Also:
C Program To Evaluate Postfix Expression Using Array
C Program To Evaluate Postfix Expression Using Linked List
How To Balance The Given Expressions
C Program For Balancing Expressions Using Array
C Program For Balancing Expressions Using Linked List
C Program To Implement Postfix To Prefix Conversion
C Program To Implement Infix To Prefix Conversion
C Program To Implement Infix To Postfix Conversion
How To Evaluate Postfix Expressions

No comments:

Post a Comment