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 ; Driver Code ; Get the size of size ; Print the Spiral Pattern
public class GFG { public static void printSpiral ( int size ) { int row = 0 , col = 0 ; int boundary = size - 1 ; int sizeLeft = size - 1 ; int flag = 1 ; char move = ' r ' ; int matrix [ ] [ ] = new int [ size ] [ size ] ; for ( int i = 1 ; i < size * size + 1 ; i ++ ) { matrix [ row ] [ col ] = i ; switch ( move ) { case ' r ' : col += 1 ; break ; case ' l ' : col -= 1 ; break ; case ' u ' : row -= 1 ; break ; case ' d ' : row += 1 ; break ; } if ( i == boundary ) { boundary += sizeLeft ; if ( flag != 2 ) { flag = 2 ; } else { flag = 1 ; sizeLeft -= 1 ; } switch ( move ) { case ' r ' : move = ' d ' ; break ; case ' d ' : move = ' l ' ; break ; case ' l ' : move = ' u ' ; break ; case ' u ' : move = ' r ' ; break ; } } } for ( row = 0 ; row < size ; row ++ ) { for ( col = 0 ; col < size ; col ++ ) { int n = matrix [ row ] [ col ] ; System . out . print ( ( n < 10 ) ? ( n + " ▁ " ) : ( n + " ▁ " ) ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int size = 5 ; printSpiral ( size ) ; } }