0

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.

enter image description here

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

2 Answers 2

3

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]);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.