edited by
12,289 views
30 votes
30 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];
    }
edited by

3 Answers

Best answer
58 votes
58 votes

Option 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
8 votes
8 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
Answer:

Related questions

29 votes
29 votes
3 answers
1
Ishrat Jahan asked Nov 1, 2014
9,747 views
Let $x$ be an integer which can take a value of $0$ or $1$. The statementif (x == 0) x = 1; else x = 0;is equivalent to which one of the following ?$x = 1 + x;$$x = 1 - ...