To swap the values about main Diagonal
Approach
1. In a matrix we have two set of indexes i and j for each element .
2. Indexes of diagonal are same i.e. (0,0) ,( 1,1) , ( 2,2) ,( 3,3)
3.When We say Swap elements so elements below diagonals are swapped with elements above diagonals , leaving the diagonal as it is .
In Code
We need two nested loop .Outer Loop will traverse elements row by row and and inner loop will cover element column by column. For each very element we swap B [ i ] [ j ] = B [ j ] [ i ]
Here all the diagonals elements with get swapped by itself.
So we get Code is :
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
// use a third variable to swap two elements
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
For example Output is
Input::
0 10 21 12
1 2 3 11
4 5 6 32
7 8 9 40
Output(Swaped)::
0 1 4 7
10 2 5 8
21 3 6 9
12 11 32 40
This is how we can write code segment to swap elements about diagonal in matrix
If u like the answer then Upvote it and have any doubt ask in comments
Get Answers For Free
Most questions answered within 1 hours.