ProgrammingHardInfosys · Accenture pattern

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[5] = {5, 1, 8, 2, 3}, c = 0
for (i = 0 to 3)
    for (j = i + 1 to 4)
        if (a[i] > 2 * a[j])
            c = c + 1
        end if
    end for
end for
Print c
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: C. 4

Only pairs with the larger value EARLIER count. 5 (index 0): 5 > 2·1 and 5 > 2·2, but not 5 > 2·3 → 2. 8 (index 2) is compared only with the later 2 and 3: 8 > 4 and 8 > 6 → 2. Total 4. The 1 at index 1 lies before 8, so (8, 1) is not a pair; counting ordinary inversions (a[i] > a[j]) gives 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic