forked from sunnyshahabuddin/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagic_Square.java
More file actions
58 lines (45 loc) · 1.22 KB
/
Magic_Square.java
File metadata and controls
58 lines (45 loc) · 1.22 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.*;
class bet {
static void generateSquare(int n)
{
int[][] magicSquare = new int[n][n];
int i = n / 2;
int j = n - 1;
for (int num = 1; num <= n * n;) {
if (i == -1 && j == n)
{
j = n - 2;
i = 0;
}
else {
if (j == n)
j = 0;
if (i < 0)
i = n - 1;
}
if (magicSquare[i][j] != 0) {
j -= 2;
i++;
continue;
}
else
magicSquare[i][j] = num++;
j++;
i--;
}
System.out.println("The Magic Square for " + n
+ ":");
System.out.println("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
System.out.print(magicSquare[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args)
{
int n = 7;
generateSquare(n);
}
}