Print matrix in diagonal pattern | Javascript program to print an n * n matrix in diagonal order ; Initialize matrix ; n - size of the array mode - to switch from top / bottom treversal it - iterator count - increases until it reaches n and then decreases lower - to ensure we move to the next row when columns go out of bounds ; A 4 * 4 matrix has 7 diagonals . Hence ( 2 * n - 1 ) iterations ; function call
function MatrixDiag ( arr ) { let arr = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] ; let n = arr . length , mode = 0 , it = 0 , lower = 0 ; for ( let t = 0 ; t < ( 2 * n - 1 ) ; t ++ ) { let t1 = t ; if ( t1 >= n ) { mode ++ ; t1 = n - 1 ; it -- ; lower ++ ; } else { lower = 0 ; it ++ ; } for ( let i = t1 ; i >= lower ; i -- ) { if ( ( t1 + mode ) % 2 === 0 ) { console . log ( arr [ i ] [ t1 + lower - i ] ) } else { console . log ( arr [ t1 + lower - i ] [ i ] ) } } } } MatrixDiag ( arr )