Let \(A\) be the square matrix of size \(n \times n\). Consider the following…
2014
Let \(A\) be the square matrix of size \(n \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]);
- A.
The matrix
\(A\)itself - B.
Transpose of the matrix
\(A\) - C.
Adding 100 to the upper diagonal elements and subtracting 100 from lower diagonal elements of
\(A\) - D.
None of the above
Attempted by 85 students.
Show answer & explanation
Correct answer: A
Key insight: the constant 100 cancels in the assignments, and because the loops run over all (i,j) pairs the code undoes each swap when it later visits the reversed pair.
Consider an off-diagonal pair with x = A[i][j] and y = A[j][i].
When the loop visits indices (i,j): Temp = x + 100, then A[i][j] is set to y and A[j][i] is set to Temp - 100 = x. The pair becomes (y,x).
Later, when the loop visits the reversed indices (j,i): now x' = A[j][i] = x and y' = A[i][j] = y. The same steps swap them again, returning the pair to (x,y).
Diagonal entries (i = j) are assigned back to themselves during the same iteration, so they remain unchanged.
Therefore, after completing the full nested loops over all i and j, every off-diagonal pair has been swapped twice and ends up in its original position. The final output is the original matrix A.
A video solution is available for this question — log in and enroll to watch it.