A matrix to be designed in following manner for a n x n order :
1 5 9 2
12 13 14 6
8 16 15 10
4 11 7 3
view sourceprint?01 int i,j,k,l,m,b=n;
02 int w=1, x=2, y=3, z=4;
03 int a[][] = new int[n][n];
04 for(i=0;i<=n/2;i++)
05 {
06 for(j=i; j<n-1; j++)
07 {
08 a[j]=w;
09 w+=4;
10 }
11 for(k=i;k<n-1;k++)
12 {
13 a[k][n-1]=x;
14 x+=4;
15 }
16 for(l=n-1;l>i;l--)
17 {
18 a[n-1][l]=y;
19 y+=4;
20 }
21 for(m=n-1;m>i;m--)
22 {
23 a[m]=z;
24 z+=4;
25 }
26 n--;
27 w=z-3;
28 x=z-2;
29 y=z-1;
30 }
31 if(n%2!=0)
32 a[b/2][b/2]=z-n;
33 for(i=0;i<n;i++)
34 {
for(j=0;j<n;j++)
{
System.out.print(a[j]);
}
System.out.println();
}
}
}
this code gave a wrong output
for an input of 4
it gave
1 5
12 13
instead of the actual output