Can someone help me with the following java questions along with explanations on
ID: 3813770 • Letter: C
Question
Can someone help me with the following java questions along with explanations on how you did it please
1. Use the concept of stack to convert the following infix expression to postfix expression.
5 * 2 + ( 14 – 12 ) – 10 * 6
The stack must be used to hold the operators and the left parentheses. The postfix string is used to hold the postfix string (the output). Show the state of the stack and the postfix string after each item is read from the infix string. The first two are done for you. The first four entries are done for you.
2. Use the concept of stack to evaluate the following postfix expression. Use the buckets below to show the state of the stack at each stage of the evaluation.
5 3 2 * + 4 - 5 +
Explanation / Answer
1.
5*2 + (14 - 12) -10 * 6
To convert an infix expression to postfix, push all operators onto stack and add operands to postfix expression. If an operator of lower precedence comes and TOS is higher precedence operator , pop the higer precedence operator and add to expression and push the lower precedence operator. Push opening brackets on stack and if closing brackets come, pop all operators upto opening brackets and add them to expression. pop the closing brackets.
Postfix Expression : 5
push * to stack
Postfix Expression : 5 2
+ has lower precedence than * so pop * and add to expression and push +
Postfix Expression : 5 2 *
push ( to stack
Postfix Expression : 5 2 * 14
Postfix Expression : 5 2 * 14 12
now ) is scanned so pop - from stack and add to expression
Postfix Expression : 5 2 * 14 12 - 10
Postfix Expression : 5 2 * 14 12 - 10 6
now pop all elements of stack and add to expression
Postfix Expression : 5 2 * 14 12 - 10 6 * - +
2.
5 3 2 * + 4 - 5 +
push all operands to stack
then comes the symbol for operator *
now pop the top two elements of stack and apply * and push the result to stack
now comes again an operator + so evaluate 5 + 6 and push result to stack
push 4
now comes -
11-4 = 7
now comes + so pop 7 and 12 and evaluate 7+ 5 = 12 , result is pushed on stack
pop it so result of evaluating the expression = 12
- * ( ( - - + + + +