ProgrammingHardAmazon OA · Capgemini

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

Correct answer: B. 5

The loops test every subarray and count those with sum 3: [1, 2], [2, 3, −2], [3], [3, −2, 2] and [2, 1], so c = 5. Because of the −2, a running sum can come back to 3 after passing it, so stopping at the first hit misses some.

More Pseudocode and Code Tracing questions

Exams that ask this topic