ProgrammingHardAmazon OA · Infosys SP

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

Correct answer: D. 3

total = 0. The first i where the sum on the left equals the sum on the right: at i = 3, left = −7 + 1 + 5 = −1 and right = −4 + 3 + 0 = −1. ans = 3 (index 6 also works, but the loop stops at the first).

More Pseudocode and Code Tracing questions

Exams that ask this topic