Reputation: 23
I would like to transpose a square matrix in place using a 2D array. However, when I iterate over the array using a nested for loop, the elements are visited twice causing no transpose to occur.
I would like to access each array element only once to correct this.
How could I alter my current code to do this?
// transpose in-place
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
Thank you.
Upvotes: 2
Views: 121
Reputation: 24427
Change your inner loop condition to stop when j equals i:
for (int j = 0; j < i; j++)
This way you are only iterating over a triangular area of the matrix (formed by the values on one side of the diagonal defined by i = j), and swapping each value with the corresponding value on the other side of the diagonal.
Upvotes: 1