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
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
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.