ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (product of array except self, without using division)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (product of array except self, without using division)? (Arrays are indexed from 0.)
Integer arr[4] = {1, 2, 3, 4}
Integer n = 4
Integer res[4] = {1, 1, 1, 1}
Integer left = 1
for (each i from 0 to n - 1)
    res[i] = left
    left = left * arr[i]
end for
Integer right = 1
for (each i from n - 1 down to 0)
    res[i] = res[i] * right
    right = right * arr[i]
end for
Print res
  1. A. [24, 12, 8, 6]
  2. B. [6, 8, 12, 24]
  3. C. [1, 2, 3, 4]
  4. D. [24, 24, 24, 24]

Correct answer: A. [24, 12, 8, 6]

res[i] ends up as the product of all elements except arr[i]: res[0]=2*3*4=24, res[1]=1*3*4=12, res[2]=1*2*4=8, res[3]=1*2*3=6.

More Pseudocode and Code Tracing questions

Exams that ask this topic