This is a Java Program to Accept a Matrix of Order MxN & Interchange the Diagonals.

Enter the elements of array as input. Now we use loops and if else condition to interchange the two diagonals of the matrix.

Here is the source code of the Java Program to Accept a Matrix of Order MxN & Interchange the Diagonals. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;

public class Interchange_Diagonals

`{`

public static void main(String[] args)

`{`

int p, q, temp = 0;

Scanner s = new Scanner(System.in);

System.out.print("Enter number of rows in matrix:");

p = s.nextInt();

System.out.print("Enter number of columns in matrix:");

q = s.nextInt();

if (p == q)

`{`

int a[][] = new int[p][q];

System.out.println("Enter all the elements of matrix:");

for (int i = 0; i < p; i++)

`{`

for (int j = 0; j < q; j++)

`{`

a[i][j] = s.nextInt();

`}`

`}`

System.out.println("Given Matrix:");

for (int i = 0; i < p; i++)

`{`

for (int j = 0; j < q; j++)

`{`

System.out.print(a[i][j] + " ");

`}`

System.out.println("");

`}`

for(int j = 0; j < q; j++)

`{`

temp = a[j][j];

a[j][j] = a[j][q-1-j];

a[j][q-1-j] = temp;

`}`

System.out.println("Matrix after interchanging diagonals");

for (int i = 0; i < p; i++)

`{`

for (int j = 0; j < q; j++)

`{`

System.out.print(a[i][j] + " ");

`}`

System.out.println("");

`}`

`}`

`else`

`{`

System.out.println("Rows not equal to column");

`}`

`}`

`}`

Output:

$ javac Interchange_Diagonals.java $ java Interchange_Diagonals Enter number of rows in matrix:3 Enter number of columns in matrix:3 Enter all the elements of matrix: 1 2 3 4 5 6 7 8 9 Given Matrix: 1 2 3 4 5 6 7 8 9 Matrix after interchanging diagonals 3 2 1 4 5 6 9 8 7

**Sanfoundry Global Education & Learning Series – 1000 Java Programs.**

advertisement

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

**Related Posts:**

- Apply for Java Internship
- Apply for Computer Science Internship
- Practice BCA MCQs
- Check Programming Books
- Practice Programming MCQs