Your program should take postfix expression as an input, process it with the hel
ID: 3633640 • Letter: Y
Question
Your program should take postfix expression as an input, process it with the help of stack and display the result after performing required calculations.Only following Binary operators are allowed for this program:
+, -, *, /, ^ [addition, subtraction, multiplication, division, exponentiation]
If some error occurs while processing postfix expression, your program should display a meaningful message, like:
Error: Division by zero not allowed
Error: Two operands required for __ operator
Error: Invalid postfix expression
Sample Run:
Enter postfix expression to evaluate:
10 20 + Entered by user
The result is: 30
Do you want to enter another postfix expression to evaluate? [Y/N]
Y Entered by user
Enter postfix expression to evaluate:
30 40 + * Entered by user
Error: Two operands required for * operator
Do you want to enter another postfix expression to evaluate? [Y/N]
Y Entered by user
Enter postfix expression to evaluate:
30 40 + 50 60 * Entered by user
Error: Invalid postfix expression
Do you want to enter another postfix expression to evaluate? [Y/N]
Y Entered by user
Enter postfix expression to evaluate:
6 2 3 + - 3 8 2 / + * 2 ^ 3 + Entered by user
The result is: 52
Do you want to enter another postfix expression to evaluate? [Y/N]
N Entered by user
Thank you for using this program.
Explanation / Answer
This is a huge one, but i can give an idea which works for all postfix expressions except those which involve numbers 42, 43,45,47,94. SOlution: ASCII values of '+','-','/','*','^' are 43,45,47,42,94 respectively. we use this fact and accept even the characters as integers. Now when we store the expression as an array of integers, we search for these numbers, because these numbers mean mathematical expression. every time you find an expression, check if the two numbers before it are plain numbers i.e. not mathematical expressions. when you find this condition, you can perform the actions on the numbers. repeat the search, and when you find the condition, solve it. dont forget when you solve, three numbers need to be replaced with a single number, and so the array should be rearranged. now, after repeating this process, you will be left out with one number, that is you solution. I really hope you'll write the code, and solve it. Because i spent a lot to come up with this. All the best.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.