ProgrammingVery hardTCS NQT · Infosys · Capgemini

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

What will be the output of the following pseudocode? (Arrays are 0-indexed.)
Integer a[7] = {1, 2, 4, 5, 7, 9, 10}
Integer i = 0, j = 6, c = 0
While i < j
    If a[i] + a[j] <= 11 Then
        c = c + (j - i)
        i = i + 1
    Else
        j = j - 1
    End If
End While
Print c
  1. A. 12
  2. B. 13
  3. C. 9
  4. D. 3

Correct answer: A. 12

When a[i] + a[j] fits the limit, every index between i+1 and j also pairs with a[i], so the whole block of (j - i) pairs is added at once. The routine therefore counts all pairs with sum at most 11 (brute force also gives 12).

More Pseudocode and Code Tracing questions

Exams that ask this topic