ProgrammingHardAmazon OA · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer m[3][3] = {{5, 1, 7}, {2, 9, 3}, {8, 4, 6}}
Integer c = 0
Boolean peak
for (each i from 0 to 2)
    for (each j from 0 to 2)
        peak = true
        for each (di, dj) in {(-1,0), (1,0), (0,-1), (0,1)}
            if (cell (i+di, j+dj) is inside the grid AND m[i+di][j+dj] >= m[i][j])
                peak = false
            end if
        end for
        if (peak)
            c = c + 1
        end if
    end for
end for
Print c
  1. A. 5
  2. B. 1
  3. C. 4
  4. D. 3

Correct answer: A. 5

A cell counts if it is larger than each of its up/down/left/right neighbours. The centre 9 qualifies, and so do all four corners: 5 (neighbours 1, 2), 7 (1, 3), 8 (2, 4) and 6 (3, 4). c = 5; it is not just the single largest value.

More Pseudocode and Code Tracing questions

Exams that ask this topic