Replace elements above by below of a diagonal in a matrix

Viewed 64

I want to make a program which replaces the elements below the main diagonal by the elements below the main diagonal in a matrix, I made a function called swap and it doesn't do what I want it to do, the output is the same for some reason. What could be the reason for that?

static int[,] swap(int[,] mat, int row, int col)
{
    int temp;
    temp = mat[row, col];
    mat[row, col] = mat[col, row];
    mat[col, row] = temp;

    return mat;
}

static void viceVersa(int[,] mat, int N)
{
    for (int row = 0; row < N; row++)
        for (int col = 0; col < N; col++)
            mat = swap(mat, row, col);
}

Expected output

Before

{5, 4, 3, 2}
{6, 1, 2, 4}
{9, 0, 2, 1}
{1, 2, 6, 2}

After

{5, 6, 2, 1}
{1, 1, 0, 9}
{4, 2, 2, 6}
{2, 3, 4, 2}
1 Answers

The nested loop in viceVersa function causes the problem, each element in the matrix (outside of the diagonal) is swaped twice so nothing changes after all.
This is one possible version:

static void viceVersa(int[,] mat, int N)
    {
        for (int row = 0; row < N; row++)
        for (int col = 0; col < N; col++)
        {
            if(row>col)
               mat = swap(mat, row, col);
        }
            
    }
Related