Interchange Diagonal Elements Java ProgramIn 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. [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
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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India