1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

The code is wrote is following. It is for printing a spiral matrix when n=5. It gave a correct output only for the elements on the sides.

class spiral_matrix { public static void main() { int m[][] = new int [4][4]; int n=1, s=4, c=1, i=0, j=0; while(n>=1) { do { m[i][j] = c++; n++; j++; } while(n<s); n = 0; do { m[i][j] = c++; n++; i++; } while(n<s-1); n = 0; do { m[i][j]=c++; n++; j--; } while(n<s-1); n = -1; do { m[i][j] = c++; n++; i--; } while(n<s-2); n = n - 2; } for(i=0; i<s; i++) { for(j=0; j<s; j++) { System.out.print(m[i][j] + " "); } System.out.println(); } } }