ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {1, 2, 4, 5, 7, 9}
Integer i = 0, j = 5, c = 0
while (i < j)
    if (a[i] + a[j] < 10)
        c = c + (j - i)
        i = i + 1
    else
        j = j - 1
    end if
end while
Print c
  1. A. 8
  2. B. 5
  3. C. 10
  4. D. 6

Correct answer: A. 8

This two-pointer loop counts pairs with sum < 10 in a sorted array: once a[i] + a[j] < 10, all j − i partners of a[i] work. Pairs: 1 with 2, 4, 5, 7 (4); 2 with 4, 5, 7 (3); 4 with 5 (1): total 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic