Question

Let AA be a square matrix of size n×nn \times n. Consider the following pseudocode. What is the expected output?

C = 100;
for i = 1 to n do
    for j = 1 to n do
    {
        Temp = A[i][j] + C;
        A[i][j] = A[j][i];
        A[j][i] = Temp - C;
    }
for i = 1 to n do
    for j = 1 to n do
        output (A[i][j]);
Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2014 answer key

Solution

Trace the nested loop over the entire matrix to analyze the swapping behavior.

  1. Examine the inner loop body for each pair (i,j)(i, j):

    Temp = A[i][j] + C;
    A[i][j] = A[j][i];
    A[j][i] = Temp - C;
    

    Since Temp−C=(A[i][j]+C)−C=A[i][j]\text{Temp} - C = (A[i][j] + C) - C = A[i][j], this block performs a swap of the elements A[i][j]A[i][j] and A[j][i]A[j][i].

  2. Trace diagonal elements (i=ji = j):
    When i=ji = j, A[i][i]A[i][i] is swapped with itself, leaving its value unchanged.

  3. Trace off-diagonal elements (i≠ji \ne j):

    • When the outer loop visits (i,j)(i, j) where i<ji < j, the elements A[i][j]A[i][j] and A[j][i]A[j][i] are swapped.
    • Later, when the outer loop visits the symmetric position (j,i)(j, i) where j>ij > i, the exact same code executes, swapping A[j][i]A[j][i] and A[i][j]A[i][j] a second time.
  4. Swapping any two values twice restores each element to its original value and position.

Hence, the matrix remains completely unchanged, producing The matrix A itself (option A).

Final answer

A

Common trap

Mistaking this code for an in-place matrix transposition, overlooking that the loops iterate over all indices rather than j > i.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 3
Question
20 of 65, printed as CS Q.10
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.