ProgrammingVery hardProduct company OA

What will be the output of the following pseudocode? (Arrays are passed by reference and indexed from 0.)

What will be the output of the following pseudocode? (Arrays are passed by reference and indexed from 0.)
Procedure p(Integer arr[], Integer n)
    if (n == 0)
        return
    end if
    arr[n - 1] = arr[n - 1] + arr[n mod 3]
    p(arr, n - 1)
End Procedure
Integer a[4] = {1, 2, 3, 4}
p(a, 4)
Print a[0], a[1], a[2], a[3]
  1. A. 2 4 4 6
  2. B. 7 6 4 6
  3. C. 7 4 4 6
  4. D. 3 6 4 6

Correct answer: B. 7 6 4 6

The recursion goes from the last index down, and each update reads the CURRENT array. n = 4: a[3] += a[1] → 6. n = 3: a[2] += a[0] → 4. n = 2: a[1] += a[2] (now 4) → 6. n = 1: a[0] += a[1] (now 6) → 7. Result 7 6 4 6. Using the original values everywhere gives 2 4 4 6-style answers; arrays passed by reference see every earlier write.

More Pseudocode and Code Tracing questions

Exams that ask this topic