if j=0 then double swapping will take place and no transpose will occur

only at j=i will lead to single swap from m[i][j] to m[j][i].

option c

Dark Mode

10,003 views

28 votes

Consider the following C program which is supposed to compute the transpose of a given $4 \times 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 (i = 0; i < 4; ++i) for (j = 0; j < 4; ++j) printf ("%d", M[i][j]); }

1

Here’s the output with Option A: https://onlinegdb.com/3qVymaWLM

And with Option C: https://onlinegdb.com/VYrmwX4iD

0

51 votes

Best answer

Ooption **C**:

look at the initial value of $j$, if $j$ starts with $0$, then double *for* loop will swap $ M[i][j]$ with $M[j][i]$ and also $M[j][i]$ and $M[i][j]$ so the matrix $M$ will remain unchanged, so to avoid this double swapping we need to initialize $j = i$ and swap only upper triangular matrix with lower triangular matrix.

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

5 votes

When swapping, this is the correct assignment for the very first location

t = M[i][j];

and not this

M[i][j] = t;

We want to save our first value in a temporary variable; and not overwrite our first value by the temporary variable.

So, Options B and D are eliminated straightaway.

Now, if column 0 and row 0 are already swapped, we don't wanna swap it again.

So, j shouldn't start from 0 every time. It should start with value == i.

So, **Option C**