简体   繁体   中英

Swapping elements in 2d array

So, I'm trying to swap the matrix elements with respect to the main diagonal. I have tried using temp method (switching values while using temp variable), also tried std::swap(a,b) . Somehow it only swaps upper right side of the matrix and leaves another half not changed.

在此处输入图片说明

How do I make everything swap?

My code:

#include <iostream>

using namespace std;

int main()
{
    const int n = 7;
    srand (time(NULL));

    int matrix[n][n];

    cout << "Original Matrix :" << endl;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            (i == j) ?  matrix[i][j] = 0 : matrix[i][j] = rand() % 100+1;
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }   

    cout << "\nRemade Matrix:" << endl;

    for (int i = 0; i < n; i++)
    {   

        for (int j = 0; j < n; j++)
        {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;


//          swap(matrix[i][j], matrix[j][i]);      //another method

            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}

You are basically swapping them twice, replace your swapping loops with this. Notice the condition of the second loop, it's j < i . Then, you can print it with another set of loops.

for (int i = 0; i < n; i++)
    for (int j = 0; j < i ; j++)
        swap(matrix[i][j], matrix[j][i]);

Your logic is almost ok. Just the inner loop counter will start from "i+1" else after the swapping the value is again getting overlapped. Try the following code and make sure you understand it. Happy coding!

for (int i = 0; i < n; i++)
{   

    for (int j = i + 1; j < n; j++)
    {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }

}

for (int i = 0; i < n; i++)
{   
    for (int j = 0; j < n; j++)
    {
        cout << matrix[i][j] << "\t";
    }
    cout << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM