-1

I'd like to know how to write a program in 2D array to exchange the elements of main diagonal with secondary diagonal then print the result like this

3 2 7
4 5 3
2 8 9

and the result show like this

7 2 3
4 5 3
9 8 2

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
user6234753
  • 71
  • 1
  • 1
  • 5

1 Answers1

0

Actually it's not a very specific problem, but as I don't see the part where you're stuck I'll try to explain a whole example to you:

static int[,] GetDiagonallySwitched(int[,] oldMatrix)
{
    var newMatrix = (int[,])oldMatrix.Clone();

    for (var i = 0; i < oldMatrix.GetLength(0); i++)
    {
        var invertedI = oldMatrix.GetLength(0) - i - 1;
        newMatrix[i, i] = oldMatrix[i, invertedI];
        newMatrix[i, invertedI] = oldMatrix[i, i];
    }
    return newMatrix;
}

First of all I'm cloning the old matrix, because a few values actually remain the same. Then I switch the values from the left side to the right side. I'm doing this with the invertedI, which basically is i from the other side - so that in the end the cross is mirrored and it seems as though the lines switched. This is working for any size of the matrix.

For the printing: If you actually want to print it bold, you'll have to use a RTB in WinForms, but I don't guess this was part of your question. Otherwise you could use this code to print the matrix:

static void Print(int[,] switched)
{
    for (var y = 0; y < switched.GetLength(0); y++)
    {
        for (var x = 0; x < switched.GetLength(1); x++)
            Console.Write(switched[y, x]);
        Console.WriteLine();
    }
}

I hope I could help you.

MetaColon
  • 2,895
  • 3
  • 16
  • 38
  • What errors do you get? It's very strange because it works fine for me. I hope that your matrix is quadratic? – MetaColon Apr 16 '17 at 20:44
  • i get error in OldMatrix ..and if i type any number it will close – user6234753 Apr 16 '17 at 20:55
  • What exactly are you doing? Could you provide a code example? And what closes? It totally depends on how you implemented my solution. And what exact error are you getting with the OldMatrix? – MetaColon Apr 16 '17 at 21:20