ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer m[4][4] = {{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}}
Integer r = 0, c = 3, neg = 0
while (r < 4 AND c >= 0)
    if (m[r][c] < 0)
        neg = neg + (4 - r)
        c = c - 1
    else
        r = r + 1
    end if
end while
Print neg
  1. A. 6
  2. B. 7
  3. C. 16
  4. D. 8

Correct answer: D. 8

Rows and columns are sorted in decreasing order, so once m[r][c] is negative, everything below it in column c is negative too. Columns 3, 2, 1, 0 contribute 4, 2, 1, 1: neg = 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic