The Java program that accepts a matrix of M × N order and then interchanges diagonals of the matrix is given below:
<h3>Steps: </h3>
- 1. We can only interchange diagonals for a square matrix.
- 2. Therefore, we would have to create a square matrix of size [M × M].
- 3. We would check whether 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.
<h3>Java Code</h3>
// Java Program to Accept a Matrix of Order M x N &
// Interchange the Diagonals
import java.util.Scanner;
public class InterchangeDiagonals {
public static void main(String[] args)
{
// declare variable
int m, n, i, j, temp;
// create a object of scanner class
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows ");
// take number of rows
m = sc.nextInt();
System.out.print("Enter number of columns ");
// take number of columns
n = sc.nextInt();
// declare a mxn order array
int a[][] = new int[m][n];
// if block it's execute when m is equals to n
if (m == n) {
System.out.println(
"Enter all the values of matrix ");
// take the matrix inputs
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println("original Matrix:");
// print the original matrix
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
// perform interchange
for (j = 0; j < m; j++) {
temp = a[j][j];
a[j][j] = a[j][n - 1 - j];
a[j][n - 1 - j] = temp;
}
System.out.println(
" after interchanging diagonals of matrix ");
// print interchanged matrix
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}
// else block it's only execute when m is not equals
// to n
else {
System.out.println("Rows not equal to columns");
}
}
}
Read more about java programming here:
brainly.com/question/18554491
#SPJ1