forked from Red-0111/Anything-Repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagic_square.java
43 lines (42 loc) · 1008 Bytes
/
magic_square.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Scanner;
public class magic_square
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix in odd numbers: ");
int n=sc.nextInt();
int [][]a=new int[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=0;
}
}
int r=n-1,c=n/2;
a[r][c]=1;
for(int i=2;i<=n*n;i++)
{
if(a[(r+1)%n][(c+1)%n]==0)
{
r=(r+1)%n;
c=(c+1)%n;
a[r][c]=i;
}
else
{
r=(r+n-1)%n;
a[r][c]=i;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}