Algorithm for evaluation of postfix expressions/notations:-
(1) Add right parenthesis ')' at the end of postfix expression P.
(2) Scan P from left to right and repeat steps (3) and (4) until right parenthesis occurred.
(3) If an operand encountered then push it into the stack.
(4) If an operator encountered then operate top two elements of stack as follows:-
(a) Evaluate BoA where A is top element and B is next top element.
(b) Push the result into the stack.
(5)If right parenthesis ')' encountered then pop the final result from the stack, it means evaluation is completed.
(6) Exit.
Examples:-
1.) P = 52/42^3*+
solve :- given expression P = 52/42^3*+
s.no. | Scanned symbol | Stack |
1 | 5 | 5 |
2 | 2 | 5,2 |
3 | / | 2 |
4 | 4 | 2, 4 |
5 | 2 | 2, 4, 2 |
6 | ^ | 2, 16 |
7 | 3 | 2, 16, 3 |
8 | * | 2, 48 |
9 | + | 50 |
answer is 50.
2.) P = AB*C/DE*F/-
where A=5, B=2, C=7, D=4, E=1 AND F=3
Solve :- given expression P = 52*7/41*3/-
s.no. | Scanned symbol | Stack |
1 | 5 | 5 |
2 | 2 | 5, 2 |
3 | * | 10 |
4 | 7 | 10, 7 |
5 | / | 1 |
6 | 4 | 1, 4 |
7 | 1 | 1, 4, 1 |
8 | * | 1, 4 |
9 | 3 | 1, 4, 3 |
10 | / | 1, 1 |
11 | - | 0 |
Answer is 0.
3.) P = 1273-/215+*+
solve :- given expression P = 1273-/215+*+
s.no. | Scanned symbol | Stack |
1 | 1 | 1 |
2 | 2 | 1, 2 |
3 | 7 | 1, 2, 7 |
4 | 3 | 1, 2, 7, 3 |
5 | - | 1, 2, 4 |
6 | / | 1, 2 |
7 | 2 | 1, 2, 2 |
8 | 1 | 1, 2, 2, 1 |
9 | 5 | 1, 2, 2, 1, 5 |
10 | + | 1, 2, 2, 6 |
11 | * | 1, 2, 12 |
12 | + | 15 |
Answer is 15.
4.) P = 35+64-*41-2^+
solve :- given expression,
P = 35+64-*41-2^+
S.no. | Scanned symbol | Stack |
1 | 3 | 3 |
2 | 5 | 3, 5 |
3 | + | 8 |
4 | 6 | 8, 6 |
5 | 4 | 8, 6, 4 |
6 | - | 8, 2 |
7 | * | 16 |
8 | 4 | 16, 4 |
9 | 1 | 16, 4, 1 |
10 | - | 16, 3 |
11 | 2 | 16, 3, 2 |
12 | ^ | 16, 9 |
13 | + | 25 |
Answer is 25
No comments:
Post a Comment