#define NUMCOLS 5 int transpose( int x[NUMCOLS][NUMCOLS] ) { int r, c, temp ; for ( r=0; r<NUMCOLS; r++ ) for ( c=0; c<r; c++ ) { temp = x[r][c]; x[r][c] = x[c][r]; x[c][r] = temp; } }
Remarks: A good number of you probably made this mistake:
#define NUMCOLS 5 int transpose( int x[NUMCOLS][NUMCOLS] ) { int r, c, temp ; for ( r=0; r<NUMCOLS; r++ ) for ( c=0; c< NUMCOLS; c++ ) { temp = x[r][c]; x[r][c] = x[c][r]; x[c][r] = temp; } }
and discovered that the 2D array did not change.
Of course, this is because when c
is
to the right of the diagonal, the function swaps two
elements that have already been swapped.
In effect, the fuction transposes the array twice.
The transpose of the transpose is the same as the original.
This solution ignores the fact that diagonal
elements do not change.
When r==c
int transpose( int x[][NumColumns], int nrows ) { int r, c, temp ; for ( r=0; r<NUMCOLS; r++ ) for ( c=0; c<r; c++ ) if ( r!=c ) { temp = x[r][c]; x[r][c] = x[c][r]; x[c][r] = temp; } }
But now the extra work of computing ( r!=c )
is done every time the loop body executes,
not just for the relatively rare diagonal elements.
This is much more work than the needless work done along the
diagonal.
But in either case, the extra work is trivial.