-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
54 lines (44 loc) · 1.27 KB
/
Copy pathMain.java
File metadata and controls
54 lines (44 loc) · 1.27 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
import java.util.Scanner;
public class Main {
static byte num;
private static Scanner input = new Scanner(System.in);
static void magicSquare(int number) {
int Matrix[][] = new int[number][number];
int init = 1;
int row = 0;
int col = number / 2;
int tempRow, tempCol;
while (init <= number * number) {
Matrix[row][col] = init;
init++;
tempRow = row;
tempCol = col;
row -= 1;
col += 1;
if (row == -1) {
row = number - 1;
}
if (col == number) {
col = 0;
}
if (Matrix[row][col] != 0) {
row = tempRow + 1;
col = tempCol;
if (row == -1) {
row = number - 1;
}
}
}
for (int i = 0; i < Matrix.length; i++) {
for (int j = 0; j < Matrix.length; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
System.out.print("Enter an odd number to make Magic Square : ");
num = input.nextByte();
magicSquare(num);
}
}