ProgrammingVery hardProduct company OA · code-tracing level

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

What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer a[8] = {1, 2, 3, 4, 6, 7, 8, 9}
Integer i = 0, j = 7, 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. 12
  2. B. 28
  3. C. 15
  4. D. 16

Correct answer: D. 16

Since the array is sorted, when a[i] + a[j] ≤ 10 every partner between i + 1 and j also works, so the code adds j − i pairs at once. It counts pairs with sum ≤ 10: partners of 1 — 7 (all, since 1 + 9 = 10); of 2 — 3, 4, 6, 7, 8 (5); of 3 — 4, 6, 7 (3); of 4 — 6 (1). Total 16. 28 = C(8, 2) counts all pairs; 15 misses the boundary pair 1 + 9 = 10.

More Pseudocode and Code Tracing questions

Exams that ask this topic