wiz-icon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Consider the following C program which is supposed to compute the transpose of a given 4×4 matrix M. Note that, there is an X in the program which indicates some missing statements. Choose the correct option to repalce 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]);
}

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

}
No worries! We‘ve got your back. Try BYJU‘S free classes today!
B
for (j = 0; j < 4; ++j)
{
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}
No worries! We‘ve got your back. Try BYJU‘S free classes today!
C
for (j = i; j < 4; ++j)
{
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}
Right on! Give the BNAT exam to get a 100% scholarship for BYJUS courses
D
for (j = i; j < 4; ++j)
{
M[i][j] = t;
t = M[j][i];
M[j][i] = M[i][j];
}

No worries! We‘ve got your back. Try BYJU‘S free classes today!
Open in App
Solution

The correct option is C for (j = i; j < 4; ++j)
{
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}
Code for Transpose of matrix;
for(i = 0; i < 4; ++i)
{
for (j = i; j < 4; ++j)
{
t = M[i][j];
M[i][j] = M[j][i];
M[j][i] = t;
}
}

Key part here is both index i.e. i and j should not start with same index. Otherwise transpose will be done 2 time which results original matrix.

So here first for loop start with i = 0. So second for loop must be start with j = i. Since t initially contain garbage value if we do M [i][j] = t then we loose our data. So, inside second for loop 1st statement must be t = M [j][i].

Note: Take 2×2 matrix and run the code on it.

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Series
QUANTITATIVE APTITUDE
Watch in App
Join BYJU'S Learning Program
CrossIcon