import java.io.*;
public class MagicSquare
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the value of n:");
int n=Integer.parseInt(br.readLine());
if(n%2==0)
{
System.out.print("N must be odd!!...Please re-enter:");
n=Integer.parseInt(br.readLine());
}
int[][] magic=new int[n][n];
int row=n-1;
int col=n/2;
magic[row][col]=1;
for (int i=2;i<=n*n;i++)
{
if(magic[(row+1)%n][(col+1)%n]==0)
{
row=(row+1)%n;
col=(col+1)%n;
}
else
{
row=(row-1+n)%n;
}
magic[row][col]=i;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(magic[i][j]<10) System.out.print(" ");//for alignment
if(magic[i][j]<100) System.out.print(" ");//for alignment
System.out.print(magic[i][j]+" ");
}
System.out.println();
}
}
}
//------------------------------------------------------------------------------
/**
Output:-
Enter the value of n:3
4 9 2
3 5 7
8 1 6
Enter the value of n:5
11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15
Enter the value of n:6
N must be odd!!...Please re-enter:7
22 31 40 49 2 11 20
21 23 32 41 43 3 12
13 15 24 33 42 44 4
5 14 16 25 34 36 45
46 6 8 17 26 35 37
38 47 7 9 18 27 29
30 39 48 1 10 19 28
*/
0 comments:
Post a Comment