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

I'm not going to answer your post anymore until you really learn how to post your code in "Code" tag... You have been posting for days and always copy-and-paste without using the forum code tag...

class zicy
{
public void main(int n)
{
int i,j,k,l,m,b=n;
int w=1,x=2,y=3,z=4;
int a[][]=new int[n][n];
for(i=0;i<=n/2;i++)
{
for(j=i;j<n-1;j++)
{
a[i][j]=w;
w+=4;
}
for(k=i;k<n-1;k++)
{
a[k][n-1]=x;
x+=4;
}
for(l=n-1;l>1;l--)
{
a[n-1][l]=y;
y+=4;
}
for(m=n-1;m>i;m--)
{
a[m][i]=z;
z+=4;
}
n--;
w=z-3;
x=z-2;
y=z-1;
}
if(n%2!=0)
a[b/2][b/2]=z-n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.