java code for magic square

Solutions on MaxInterview for java code for magic square by the best coders in the world

showing results for - "java code for magic square"
Vincenzo
16 Nov 2020
1public static void main(String[] args) {
2    System.out.print("Give an odd number: ");
3    int n = console.nextInt();
4    int[][] magicSquare = new int[n][n];
5
6    int number = 1;
7    int row = 0;
8    int column = n / 2;
9    while (number <= n * n) {
10        magicSquare[row][column] = number;
11        number++;
12        row -= 1;
13        column += 1;
14        if (row == -1) {
15            row = n - 1;
16        }
17        if (column == n) {
18            column = 0;
19        }
20        if (row == 0 && column == n - 1) {
21            column = n - 1;
22            row += 1;
23        } else if (magicSquare[row][column] != 0) {
24            row += 1;
25        }
26    }
27
28    for (int i = 0; i < magicSquare.length; i++) {
29        for (int j = 0; j < magicSquare.length; j++) {
30            System.out.print(magicSquare[i][j] + " ");
31        }
32        System.out.println();
33    }
34}