Question

I Am new to C & programming entirely. I am currently working through Kochans Programming in C and have hit a brick wall with exercise 8.12. This asks to create a function which transposes matrix M which is 4 X 5 to matrix N which is 5 x 4. I have the below code which works to a point, the transpose appears to work fine however some of the elements print incorrectly, as can be seen in the output.

#include <stdio.h>

void transposeArray (int arrayM[4][5], int arrayN[5][4]);

int main (void)
{
    int i, j;
    int arrayM[4][5] =
    {
    {  1,  2,  3,  4,  5 },
    {  6,  7,  8,  9, 10 },
    { 11, 12, 13, 14, 15 },
    { 16, 17, 18, 19, 20 }
    };

    int arrayN[5][4] ={0};

    for( i = 0; i < 4; ++i )
        {
        for( j = 0; j < 5; ++j )
            {
            printf("%3i  ",arrayM[i][j]);
            }
        printf("\n\n");
        }
    printf("\n\nTransposed\n\n");
    transposeArray(arrayM, arrayN);

    for( i = 0; i < 5; ++i )
        {
        for( j = 0; j < 4; ++j )
            {
            printf("%3i  ",arrayN[i][j]);
            }
        printf("\n\n");
        }

    return 0;
}

void transposeArray (int arrayM[4][5], int arrayN[5][4])
{

    int i, j;
    for (i = 0; i < 5; ++i)
        {
        for ( j = 0; j < 4; ++j)
            {
            arrayN[j][i] = arrayM[i][j];
                //printf("%i, \n\n", arrayN[j][i]);
            }
        }
}

Output -

  1    2    3    4    5  

  6    7    8    9   10  

 11   12   13   14   15  

 16   17   18   19   20 

Transposed

  1    6   11   16  

  0    7   12   17  

  0    8   13   18  

  0    9   14   19  

  5    0    0    0  

Program ended with exit code: 0

Was it helpful?

Solution 2

Replace

arrayN[j][i] = arrayM[i][j];

with

arrayN[i][j] = arrayM[j][i];

Input:

  1    2    3    4    5  

  6    7    8    9   10  

 11   12   13   14   15  

 16   17   18   19   20  

Transposed

  1    6   11   16  

  2    7   12   17  

  3    8   13   18  

  4    9   14   19  

  5   10   15   20  

OTHER TIPS

i is index for rows in M, and cols in N so it should go until 4, and j should go until 5.
So instead of

for (i = 0; i < 5; ++i)
    {
    for ( j = 0; j < 4; ++j)
        {
        arrayN[j][i] = arrayM[i][j];
            //printf("%i, \n\n", arrayN[j][i]);
        }
    }

should be

for (i = 0; i < 4; ++i)
    {
    for ( j = 0; j < 5; ++j)
        {
        arrayN[j][i] = arrayM[i][j];
            //printf("%i, \n\n", arrayN[j][i]);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top