Let be the 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]);View worked solution
Answer: A
Let's trace the effect of the nested loops on the elements of the matrix :
- For any off-diagonal pair where , the loop visits this pair twice: once when the outer loop index is and the inner loop index is , and once when the outer loop index is and the inner loop index is .
- During the first visit (say at ):
This successfully swaps the values of and . - During the second visit (at ):
The same swap operation is executed again on the already-swapped elements, which restores them to their original values. - For diagonal elements where , the operation simplifies to:
Thus, diagonal elements remain unchanged.
Since all off-diagonal elements are swapped twice and diagonal elements are unchanged, the final matrix is identical to the original matrix .
Free practice · Your answers on this page are not saved.
