+ 2
How can i convert rows into columns in a 2d array in C++ without using another array?
How can i convert rows into columns in a 2d array in C++?
14 Answers
+ 3
You perform a transpose operation, like this:
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
mat2[j][i] = mat[i][j];
}
}
Note - mat2 must be of a size c*r, where c is the number of rows and r is the number of columns for the new matrix, while c is the number of columns for the original matrix.
+ 3
You may save it in the same array, but then you need to ensure that your matrix can store the transpose. Eg - for a 2*3 matrix, your matrix should be large enough to hold a 3*2 matrix. So your matrix should be of 3*3 elements.
+ 3
@Gordie
With a class, we can do things a lot differently, but with c-arrays, this is how I would do it.
+ 2
int r, c; cin>>r>>c;
int n = (r>c)?r:c;
int mat[n][n];
// Read the matrix.
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
mat[j][i] = mat[i][j];
}
}
swap(r,c);
// Print the matrix with row and column interchanged.
+ 2
@Gordie
You may just swap, but the matrix needs to be large enough so that it can represent both r*c and c*r, right? And if r!=c, won't some of the elements be wrongly read? So i think just the rows that still don't have a value must be copied in the loop.
+ 2
@kinshuk I already know the code using a temp matrix ..if you know the code without using the temp matrix then please don't hesitate to tell us..
+ 2
@JPM7 great knowledge bro i was unaware about this information
+ 1
@SD can we also do this without using another array
+ 1
means u don't know
0
@kinshuk_Vasisht can we also do this without using another array
0
can u sent the code
0
@kinshuk the code u have sent seems to have a problem..if u are transferring the value of mat[i][j] to mat[j][i] then the original value of mat[j][i] is lost..
0
@Gourav Singh
Yes, the value gets lost, but didn't you want to swap rows and columns in a single matrix?
I assumed you wanted to do:
[ 1 3 ]
[ 2 4 ]
[ 5 6 ]
to
[ 1 2 5 ]
[ 3 4 6 ]
But yes, the copying using a simple matrix will create problems as after the first half being copied, we need a second matrix.
So copy into a temp matrix, and then recopy into the original one.
Ill just post the code.