Question

Hello, i want to parse a String mathematical expression to an infix or postfix expression in...

Hello, i want to parse a String mathematical expression to an infix or postfix expression in Swift.

For example i let's say that i have this String

let exp = "5 + 3 - 2 * 9 / 1" How can i convert it to an infix or postfix expression?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The expression of the form a operator b is called infix expression.

Here, the operator is between operands(eg: a+b*c)

The expression of the form a b operator is called postfix expression.

Here, the operator is followed for every pair of operands(eg: abc*+)

Conversion from Infix to postfix:-

Steps:-

(i) Scan the infix expression from left to right.
(ii) If the scanned character is an operand, output it.
(iii) Else,
…..(i) If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
…..(ii) Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)
(iv) If the scanned character is an ‘(‘, push it to the stack.
(v) If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis.
(vi) Repeat steps 2-6 until infix expression is scanned.
(vii) Print the output
(viii) Pop and output from the stack until it is not empty.

exp=5 + 3 - 2 * 9 / 1

So, postfix expression is:- 53291/*-+

  

Add a comment
Know the answer?
Add Answer to:
Hello, i want to parse a String mathematical expression to an infix or postfix expression in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT