[M-15]
Assume that the array has the same number of rows as columns.
To transpose such an array, exchange element
x[r][c]
with element
x[c][r].
The diagonal does not change.
Here are some examples:
Original: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Transposed: 0 5 10 15 20 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 |
Original: 0 1 2 5 6 7 10 11 12 |
Transposed: 0 5 10 1 6 11 2 7 12 |
Original: 0 1 2 3 4 5 6 7 8 |
Transposed: 0 3 6 1 4 7 2 5 8 |
Here is a testing framework:
#include <stdio.h>
#include <stdlib.h>
#define NUMCOLS 10
#define NUMROWS 10
void transpose( int nrows, int ncols, int x[nrows][ncols] )
{
. . . .
}
void fill2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
int r, c, val = 0;
for ( r=0; r<nrows; r++ )
{
for ( c=0; c<ncols; c++ )
x[r][c] = val++ ;
}
}
void print2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
int r, c; /* row and column indexes for the array */
/* Print elements in row major order */
for ( r=0; r<nrows; r++ )
{
for ( c=0; c<ncols; c++ )
printf("%3d ", x[r][c] );
printf("\n");
}
}
int main(int argc, char *argv[])
{
int x[NUMROWS][NUMCOLS];
if ( NUMROWS != NUMCOLS )
{
printf("Rows %d must be the same as number of columns %d\n", NUMROWS , NUMCOLS );
return 0;
}
fill2Darray( NUMROWS, NUMCOLS, x );
printf("\n\nOriginal:\n");
print2DArray( NUMROWS, NUMCOLS, x );
transpose( NUMROWS, NUMCOLS, x );
printf("\n\nTransposed:\n");
print2DArray( NUMROWS, NUMCOLS, x );
return 0;
}