User987
User987

Reputation: 3823

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?

Upvotes: 0

Views: 12277

Answers (4)

3Dave
3Dave

Reputation: 29051

In-place transpose:

void transpose(vector<vector<int>>& matrix)
{
    // assumes square matrix
    int wh = matrix.size();

    for(int y=0; y < wh; ++y)
    {
        for(int x=0; x < y; ++x)
        {
            swap(matrix[y][x], matrix[x][y]);
        }
    }

}

Upvotes: 0

John Sick
John Sick

Reputation: 436

You can also do this in easy way

#include <iostream>

using namespace std;

int main(){
int n,m;
cin>>n>>m;

int arr_1[n][m];
int arr_2[n][m];

for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
        cin>>arr_1[i][j];
    }
}
for(int i=0;i<m;i++){
    for(int j=0;j<n;j++){

        cout<< arr_1[j][i]<<' ';
    }
    cout<<endl;
}

}

Upvotes: 0

boriaz50
boriaz50

Reputation: 858

You should use two dimensional arrays.

#include <iostream>
using namespace std;

const int N = 10;

int main()
{
    int a[N][N];
    int b[N][N];

    // fill matrix
    cout << "Input matrix:" << endl;
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
            cin >> a[i][j];

    // transpose matrix
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
            b[i][j] = a[j][i];

    // print matrix
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
        {
            cout << b[i][j] << ' ';
        }

        cout << endl;
    }

    return 0;
}

Upvotes: 2

frslm
frslm

Reputation: 2978

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];

Upvotes: 3

Related Questions