Question
Let be a square matrix of size . 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]);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.
-
Examine the inner loop body for each pair :
Temp = A[i][j] + C; A[i][j] = A[j][i]; A[j][i] = Temp - C;Since , this block performs a swap of the elements and .
-
Trace diagonal elements ():
When , is swapped with itself, leaving its value unchanged. -
Trace off-diagonal elements ():
- When the outer loop visits where , the elements and are swapped.
- Later, when the outer loop visits the symmetric position where , the exact same code executes, swapping and a second time.
-
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).
A
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.