Search code examples
c++arraysmatrixtranspose

Transposing 2D array in C++


I have a 2D static array which looks like this:

1 1 1 1 1 1 
2 2 2 2 2 2 
3 3 3 3 3 3 
4 4 4 4 4 4 
5 5 5 5 5 5 
6 6 6 6 6 6 

I'm trying to transpose the rows and columns of this array:

1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6

I was able to solve it by using 1D array like following:

for (int i = 0; i < 6; ++i)
    for (int j = 0; j < 6; ++j)
        copyArray[i * 6 + j] = array[j * 6 + i];

But how would I do this for an array which is 10x10?

Can someone help me out here?


Solution

  • Are you looking for something like:

    int array[10][10], copyArray[10][10];
    
    ... // (fill array here)
    
    for (int i = 0; i < 10; ++i)
        for (int j = 0; j < 10; ++j)
            copyArray[j][i]= array[i][j];