ProgrammingHardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (^ is exponentiation; / is integer division truncating toward zero. An operator pops the top element as b and the next as a, then pushes the value of a op b.)

What will be the output of the following pseudocode? (^ is exponentiation; / is integer division truncating toward zero. An operator pops the top element as b and the next as a, then pushes the value of a op b.)
Stack S = empty
For each token in "20 3 2 ^ 4 - / 7 3 - *"
    If token is a number Then
        push(S, token)
    Else
        b = pop(S)
        a = pop(S)
        push(S, a token b)
    End If
End For
Print pop(S)
  1. A. 12
  2. B. 16
  3. C. 4
  4. D. 10

Correct answer: B. 16

Evaluate left to right: 3^2 = 9; 9 - 4 = 5; 20 / 5 = 4; then 7 - 3 = 4; finally 4 * 4 = 16. Reading the operands in the wrong order would give a different value.

More Pseudocode and Code Tracing questions

Exams that ask this topic