[圖解C] ex 6-4

// exercise 6-4: transpose the matrix

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int arrA[3][4] = {{1, 2, 3, 4},
                    {5, 6, 7, 8},
                    {9, 10, 11, 12}};
                                                     
    // display arrA[3][4]
    int row, col;  // arrA[3][4]
    for (row=0 ; row<3 ; row++){
        for (col=0 ; col<4 ; col++){
            printf("%d  ", arrA[row][col]);
        }
        printf("\n");
    }
    printf("\n");
 
 
    int tempA[12];       // trans 3x4 arrA to 1x12 tempA
    int transA[4][3];    // trans 1x12 tempA to 4x3 transA
 
    // trans 3x4 arrA to 1x12 tempA
    int i=0;
    for (row=0 ; row<3 ; row++){
        for (col=0 ; col<4 ; col++){4
           tempA[i] = arrA[row][col];
           i++;
        }
    }
 
    // trans 1x12 tempA to 4x3 transA
    i=0;
    int tRow, tCol; // transA[4][3]
    for (tCol=0 ; tCol<3 ; tCol++){
        for (tRow=0 ; tRow<4 ; tRow++){
            transA[tRow][tCol] = tempA[i];
            i++;
        }
    }
 
    // display the transposed matrix
    for (tRow=0 ; tRow<4 ; tRow++){
        for (tCol=0 ; tCol<3 ; tCol++){
            printf("%d  ", transA[tRow][tCol]);
        }
        printf("\n");
    }
 
 
    system("pause");
    return 0;
}