2081 4

CSC211 · 2081 · 5 marks

Convert the infix expression A+(((B-C)*(D-E)+F)/G$(H-I) into post expression using stack.

Convert the infix expression A+(((B-C)*(D-E)+F)/G$(H-I) into post expression using stack. [5]

Data Structures and AlgorithmsChapter 2: StackConversion from infix to postfix/prefix expression, EvaluatiNumerical: infix to postfix conversion

Infix to Postfix Conversion Using Stack

Given

Infix expression: A+(((B-C)*(D-E)+F)/G$(H-I))

Note: The original problem text shows an apparent typo with unbalanced parentheses. Counting the brackets:

  • Open parens: ( before ((, giving 4 opening: ( ( ( (
  • Actually reading A+(((B-C)*(D-E)+F)/G$(H-I)) the balanced form has 4 opens and 4 closes.

I take the balanced expression: A+(((B-C)*(D-E)+F)/G$(H-I))

Operator precedence ($ = exponentiation, highest):

OperatorPrecedence
$Highest
*, /Medium
+, -Lowest

$ is right-associative; *, /, +, - are left-associative.


Solution

SymbolActionStack (bottom→top)Postfix
AoutputA
+push+A
(push+ (A
(push+ ( (A
(push+ ( ( (A
Boutput+ ( ( (A B
-push+ ( ( ( -A B
Coutput+ ( ( ( -A B C
)pop to (+ ( (A B C -
*push+ ( ( *A B C -
(push+ ( ( * (A B C -
Doutput+ ( ( * (A B C - D
-push+ ( ( * ( -A B C - D
Eoutput+ ( ( * ( -A B C - D E
)pop to (+ ( ( *A B C - D E -
+pop *, push ++ ( ( +A B C - D E - *
Foutput+ ( ( +A B C - D E - * F
)pop to (+ (A B C - D E - * F +
/push+ ( /A B C - D E - * F +
Goutput+ ( /A B C - D E - * F + G
$push+ ( / $A B C - D E - * F + G
(push+ ( / $ (A B C - D E - * F + G
Houtput+ ( / $ (A B C - D E - * F + G H
-push+ ( / $ ( -A B C - D E - * F + G H
Ioutput+ ( / $ ( -A B C - D E - * F + G H I
)pop to (+ ( / $A B C - D E - * F + G H I -
)pop $, /, to (+A B C - D E - * F + G H I - $ /
Endpop all(empty)A B C - D E - * F + G H I - $ / +

Explanation of key steps:

  • At the + after (D-E): top of stack (inside brackets) is *, which has higher precedence than +, so * is popped, then + is pushed.
  • At final ): pop $ then / until matching (.
  • At End: pop remaining +.

Final Postfix Expression

$$\boxed{A\ B\ C-D\ E-*\ F+G\ H\ I-$\ /\ +}$$

That is: ABC-DE-*F+GHI-$/+

Verification: evaluating the postfix from left to right, A B C - builds (B-C), D E - builds (D-E), the * multiplies them, F + adds F, then G H I - $ builds G raised to (H-I), the / divides the bracketed sum by it, and the final + adds A, which reproduces the original infix expression exactly. The stack is empty at the end and every opening parenthesis was matched by a closing one, so the conversion is complete and correct.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.