ProgrammingHardTCS Digital · Infosys pattern

What will be the output of the following pseudocode? (Arrays are indexed from 0; the matrix has 3 rows and 4 columns.)

What will be the output of the following pseudocode? (Arrays are indexed from 0; the matrix has 3 rows and 4 columns.)
Integer m[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
Integer top = 0, bottom = 2, left = 0, right = 3
while (top <= bottom and left <= right)
    for (j = left to right)  Print m[top][j]
    top = top + 1
    for (i = top to bottom)  Print m[i][right]
    right = right - 1
    if (top <= bottom)
        for (j = right down to left)  Print m[bottom][j]
        bottom = bottom - 1
    end if
    if (left <= right)
        for (i = bottom down to top)  Print m[i][left]
        left = left + 1
    end if
end while
  1. A. 1 2 3 4 8 12 11 10 9 5 6 7 6
  2. B. 1 2 3 4 8 12 11 10 9 5 6 7
  3. C. 1 2 3 4 8 12 11 10 9 5 7 6
  4. D. 1 2 3 4 5 6 7 8 9 10 11 12

Correct answer: B. 1 2 3 4 8 12 11 10 9 5 6 7

Outer ring: top row 1 2 3 4, right column 8 12, bottom row reversed 11 10 9, left column upward 5. Then top = 1, bottom = 1, left = 1, right = 2: the inner row prints 6 7; the right-column loop is empty, and the two guards stop the middle row from being printed again backwards. Without those guards 6 would be printed twice.

More Pseudocode and Code Tracing questions

Exams that ask this topic