Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a program that takes as input an infix expression and outputs the equivale

ID: 3530610 • Letter: W

Question

write a program that takes as input an infix expression and outputs the equivalent postfix expression. The basic algorithm is 1. Initialize a stack of characters to hold the operation symbols and parenthesis. 2. do if (the next input is a left parenthesis) read the left parenthesis and push it onto the stack else if(the next input is a number or other operand) read the operand and write it to the output else if (the next input is one of the operation symbols) { do print the top operation and pop it. while none of these three conditions are true: (1) The stack becomes empty, or (2) The next symbol on the stack is a left parenthesis, or (3)the next symbol on the stack is an operation with lower precedence than the next input symbol Read the next input symbol, and push this symbol onto the stack } else { Read and discard the next input symbol (which should be a right parenthesis). Print the top operation and pop it; keep printing and popping until the next symbol on the stack is a left parenthesis. (if no left parenthesis is encountered, then print an error message indicating unbalanced parenthesis, and halt.) Finally, pop the left parenthesis } while (there is more of the expression to read); 3. print and pop any remaining operations on the stack. (There should be no remaining left parenthesis; if there are, the input expression did not have balanced parenthesis.) Assume that the input may contain numbers, variables arithmetic operations +,-,* and /; as well as parenthesis. However the expression need not be fully parenthesized, and when parenthesis are missing the usual c++ precedence rules are used to determine the order of evaluation. Your program should allow the user to enter additional expressions until the user says he or she wishes to end the program. For a more difficult assignment enhance your program so that the expression need not be well formed; if it is not well formed then the user is asked to reenter the expression

Explanation / Answer

Relevent: http://interactivepython.org/courselib/static/pythonds/BasicDS/stacks.html#infix-prefix-and-postfix-expressions