Let A be a square matrix of size n x n. Consider the following program. What…

2023

Let A be a square matrix of size n x n. Consider the following program. 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]);

  1. A.

    The matrix A itself

  2. B.

    Transpose of matrix A

  3. C.

    Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements of A

  4. D.

    None of the above

Show answer & explanation

Correct answer: A

Concept: When a nested loop with two independent index variables i and j (both ranging over 1..n) swaps the values at positions (i, j) and (j, i) using a temporary variable, every off-diagonal unordered pair {i, j} is reached exactly twice across the full sweep of both loops — once as (i, j) and once as (j, i). Applying the same swap twice to a pair restores its original values. Separately, whenever a constant is added to form a temporary value and then subtracted again within that same step (Temp = value + C, later Temp − C), the constant cancels out exactly regardless of what value it holds, so it can never leave a permanent change.

Application:

  1. For any i ≠ j, take the first time the pair is reached (outer index l, inner index m, with l < m). The code computes Temp = A[l][m] + C, then sets A[l][m] = A[m][l] using the still-original value at (m, l), and finally sets A[m][l] = Temp − C, which equals the original A[l][m]. The +C and −C cancel exactly, so this step is a plain swap of the two original values.

  2. The same unordered pair is reached a second time later in the sweep, at outer index m, inner index l. The same three statements run again, this time on the already-swapped values: A[m][l] is set to the current A[l][m] (which is the original A[m][l]), and A[l][m] is set to Temp − C (which works out to the original A[l][m]). Both positions land back on their original values.

  3. For i = j (the diagonal), A[i][i] is read into Temp, written to itself, and written back after subtracting C, so diagonal entries are never altered by any of this.

Cross-check:

Take n = 2 with A = [[1, 2], [3, 4]] and C = 100. The iterations run in the order (1,1), (1,2), (2,1), (2,2): (1,1) leaves A unchanged; (1,2) turns it into [[1, 3], [2, 4]]; (2,1) turns it back into [[1, 2], [3, 4]]; (2,2) leaves it unchanged. The matrix printed at the end equals the original A — the same identity outcome holds for every n, not just this example.

Explore the full course: Coding For Placement