# Interchange Diagonal Elements Java Program

In this section, we will learn how to interchange diagonals of a matrix through a Java program. It is usually asked in Java interviews and academics. Consider the above 4*4 matrix whose size is n.

In the above matrix, we have to swap the following indexes to interchange the diagonal.

 swap with 

 swap with 

 swap with 

 swap with 

From the above, we observe that the row index of both sides is the same and the only change in column index. If we look carefully at the column index, we found the pattern that is on the left side column index is increasing by 1 and in the right side, column index is decreasing by 1.

So, we can create a formula to get the right-side column index i.e. n-i-1.

For the above logic, we require a loop in which we swap the diagonal elements.

## Algorithm

1. Declare variables for the matrix size.
2. Ask the user to initialize the matrix rows and columns
3. Check if the number of rows and columns are equal or not.
4. If equal, then ask the user to initialize the matrix.
5. Print the original matrix.
6. Swap the diagonal elements.
7. Print the diagonals interchanged matrix.
8. If rows and columns are not equal, print the same message.

Let's implement the above logic in a Java program.

In the following program, we have taken the input of a 3*3 matrix. After that, we have printed the original matrix, performed the swapping of elements, and at last printed the diagonal interchanged matrix.

InterchangeDiagonal.java

Output: Next TopicJava Set to List

### Feedback   