![]() |
VOOZH | about |
Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix.
Steps:
1. We can only interchange diagonals for a square matrix.
2. Create a square matrix of size [M × M].
3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program.
4. Apply logic for interchange diagonal of the matrix some logic is given below.
Method 1: Swap element a[i][i] and a[i][n - i -1]
for (j = 0; j < m; j++) {
temp = a[j][j];
a[j][j] = a[j][n - 1 - j];
a[j][n - 1 - j] = temp;
}
Example:
Output:
Enter number of rows 3
Enter number of columns 3
Enter all the values of matrix
1
2
3
4
5
6
7
8
9
Original Matrix:
1 2 3
4 5 6
7 8 9
After interchanging diagonals of matrix
3 2 1
4 5 6
9 8 7
Example 2:
Output:
Enter number of rows 2
Enter number of columns 1
Enter all the values of matrix
1
2
Rows not equal to columns