ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (Arrays are indexed from 0; a 'from a down to b' loop does nothing when a < b.)

What will be the output of the following pseudocode? (Arrays are indexed from 0; a 'from a down to b' loop does nothing when a < b.)
Integer m[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
Integer top = 0, bottom = 3, left = 0, right = 3, k = 0
while (top <= bottom and left <= right)
    for (each j from left to right)
        k = k + 1
        if (k == 10) Print m[top][j]
    end for
    top = top + 1
    for (each i from top to bottom)
        k = k + 1
        if (k == 10) Print m[i][right]
    end for
    right = right - 1
    for (each j from right down to left)
        k = k + 1
        if (k == 10) Print m[bottom][j]
    end for
    bottom = bottom - 1
    for (each i from bottom down to top)
        k = k + 1
        if (k == 10) Print m[i][left]
    end for
    left = left + 1
end while
  1. A. 13
  2. B. 10
  3. C. 9
  4. D. 14

Correct answer: A. 13

The loops walk the matrix in a clockwise spiral: top row 1 2 3 4, right column 8 12 16, bottom row backwards 15 14 13, left column upwards 9 5, then the inner ring 6 7 11 10. The 10th element visited is 13. 10 is the last element of the spiral; 9 and 14 are its neighbours in the order.

More Pseudocode and Code Tracing questions

Exams that ask this topic