MAGIC SQUARE

Java program to accept odd integer "N" and print MAGIC SQUARE of this order.





In magic square sum of each row or column or diagonal of matrix (of odd order)is same.


 Computer generated output for the same is:







Coding:


import java.io.*;
class magic
{ public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(" N =");
int n=Integer.parseInt(br.readLine());   
if(n%2==0)
{System.out.println("N is not odd.Sorry!!!!!");
System.exit(0);
}
System.out.println("\n\nMagic square of order "+n+" is:\n\n\n");

int i=n/2;int j=n-1,x=1;int A[][]=new int[n][n];
while(x<=n*n)
{ A[i][j]=x++;int p=i,q=j;
if(j==n-1)
j=0;
else
j++;
if(i==0)
i=n-1;
else
i--;
if(A[i][j]>0)
{i=p;j=q-1;}
}


for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
System.out.print(A[i][j]+"\t");
System.out.println();
}
}
}



























Comments

Popular Posts