in Programming edited by
10,003 views
28 votes
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. for(j = 0; j < 4; ++j){
         t = M[i][j];
         M[i][j] = M[j][i];
         M[j][i] = t;
    }
    
  2. for(j = 0; j < 4; ++j){
         M[i][j] = t;
         t = M[j][i];
         M[j][i] = M[i][j];
    }
    
  3. for(j = i; j < 4; ++j){
         t = M[i][j];
         M[i][j] = M[j][i];
         M[j][i] = t;
    }
    
  4. for(j = i; j < 4; ++j){
         M[i][j] = t;
         t = M[j][i];
         M[j][i] = M[i][j];
    }
in Programming edited by
10.0k views

2 Comments

just take examples and try to find out. the only difference will the value of j.

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
1
1

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

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

0
0

3 Answers

51 votes
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;
}
edited by

3 Comments

Its correct, and output is transposed matrix.
http://ideone.com/DGjfQU
4
4

In option C it was t = M[j][i]; so option a is answer.

2
2
@Ravi, 3 lines inside inner for loop are to swap M[i][j] and M[j][i]. It doesn't matter if you assign t value of M[i][j] or M[j][i].
2
2
5 votes
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

3 votes
3 votes
option C

3 Comments

there was a typo in the choices, can you check your answer again?
0
0
option D is non-sensical, right?
0
0
Sir what is typo
0
0
Answer:

Related questions