Program to print Spiral Pattern | Create row and col to traverse rows and columns ; Variable to determine the movement r = right , l = left , d = down , u = upper ; Array for matrix ; Assign the value ; switch - case to determine the next index ; If right , go right ; If left , go left ; If up , go up ; If down , go down ; Check if the matrix has reached array boundary ; Add the left size for the next boundary ; If 2 rotations has been made , decrease the size left by 1 ; switch - case to rotate the movement ; If right , rotate to down ; If down , rotate to left ; If left , rotate to up ; If up , rotate to right ; Print the matrix ; Get the size of size ; Print the Spiral Pattern
function printSpiral ( size ) { let row = 0 , col = 0 ; let boundary = size - 1 ; let sizeLeft = size - 1 ; let flag = 1 ; let move = ' ' ; let matrix = new Array ( size ) ; for ( let i = 0 ; i < size ; i ++ ) { matrix [ i ] = new Array ( size ) . fill ( 0 ) ; } for ( let i = 1 ; i < size * size + 1 ; i ++ ) { matrix [ row ] [ col ] = i ; switch ( move ) { case ' ' : col += 1 ; break ; case ' ' : col -= 1 ; break ; case ' ' : row -= 1 ; break ; case ' ' : row += 1 ; break ; } if ( i == boundary ) { boundary += sizeLeft ; if ( flag != 2 ) { flag = 2 ; } else { flag = 1 ; sizeLeft -= 1 ; } switch ( move ) { case ' ' : move = ' ' ; break ; case ' ' : move = ' ' ; break ; case ' ' : move = ' ' ; break ; case ' ' : move = ' ' ; break ; } } } for ( row = 0 ; row < size ; row ++ ) { for ( col = 0 ; col < size ; col ++ ) { let n = matrix [ row ] [ col ] ; if ( n < 10 ) document . write ( n + " " ) ; else document . write ( n + " " ) ; } document . write ( " " ) ; } } let size = 5 ; printSpiral ( size ) ;