Consider the following C program which is supposed to compute the transpose of…

2004

Consider the following C program which is supposed to compute the transpose of a given 4 x 4 matrix M. Note that, there is an X in the program which indicates some missing statements. Choose the correct option to replace X in the program.

#include<stdio.h>
#define ROW 4
#define COL 4
int M[ROW][COL] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
main()
{
    int i, j, t;
    for (i = 0; i < 4; ++i)
    {
        X
    }
    for (1 = 0; i < 4; ++i)
        for (j = 0; j < 4; ++j)
            printf ("%d", M[i][j]);
}

A)

for(j = 0; j < 4; ++j){
     t = M[i][j];
     M[i][j] = M[j][i];
     M[j][i] = t;
}

B)

for(j = 0; j < 4; ++j){
     M[i][j] = t;
     t = M[j][i];
     M[j][i] = M[i][j];
}

C)

for(j = i; j < 4; ++j){
     t = M[i][j];
     M[i][j] = M[j][i];
     M[j][i] = t;
}

D)

for(j = i; j < 4; ++j){
     M[i][j] = t;
     t = M[j][i];
     M[j][i] = M[i][j];
}

  1. A.

    A

  2. B.

    B

  3. C.

    C

  4. D.

    D

Attempted by 7 students.

Show answer & explanation

Correct answer: C

Correct replacement:

for (j = i; j < 4; ++j) {

t = M[i][j];

M[i][j] = M[j][i];

M[j][i] = t;

}

Explanation:

  • We perform an in-place swap between M[i][j] and M[j][i] so the element above the diagonal exchanges with its mirrored element below the diagonal.

  • Starting the inner loop at j = i ensures each pair is swapped only once. If j started at 0, pairs would be swapped twice and the matrix would end up unchanged.

  • The temporary variable t must be assigned from M[i][j] before overwriting M[i][j], which is why the order t = M[i][j]; M[i][j] = M[j][i]; M[j][i] = t; is required.

  • Minor optimization: you can use j = i + 1 to skip swapping diagonal elements with themselves, but using j = i is functionally correct.

Explore the full course: Gate Guidance By Sanchit Sir