Swap upper and lower triangular halves of a given Matrix | Java program for the above approach ; Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diagonal ; If current element lies below the principal diagonal ; If current element lies above the principal diagonal ; Traverse again to swap values ; Find the index ; Principal diagonal ; Below main diagonal ; Above main diagonal ; Traverse the matrix and print ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves
import java . io . * ; class GFG { static void ReverseSwap ( int [ ] [ ] mat , int n ) { int [ ] lowerEle = new int [ n ] ; int [ ] upperEle = new int [ n ] ; int index ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = Math . abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { lowerEle [ index ] = mat [ i ] [ j ] ; } else { upperEle [ index ] = mat [ i ] [ j ] ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = Math . abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { mat [ i ] [ j ] = upperEle [ index ] ; } else { mat [ i ] [ j ] = lowerEle [ index -- ] ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] mat = new int [ ] [ ] { { 1 , 2 } , { 4 , 5 } } ; int N = mat . length ; ReverseSwap ( mat , N ) ; } }