Javatpoint Logo
Javatpoint Logo

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.

Interchange Diagonal Elements Java Program

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.

[0][0] swap with [0][3]

[1][1] swap with [1][2]

[2][2] swap with [2][1]

[3][3] swap with [3][0]

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.

Note: To perform the diagonal interchange, the number of rows and columns must be the same.

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:

Interchange Diagonal Elements Java Program
Next TopicJava Set to List





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA