hey guys i'm having problem to my code in MAGIC SQUARE
Output of my current code
0 1 8
7 5 3
2 9 4
it's a little bit confusing.. the 6th digit turn to 0
any help will be much appreciated :)
thanks in advance
import java.util.Scanner;
public class magicSquare {
static Scanner sn = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter odd number: ");
int N = sn.nextInt();
if (N % 2 == 0) throw new RuntimeException("N must be odd");
int[][] magic = new int[N][N];
int row = 0;
int col = N/2;
magic[row][col] = 1;
for (int i = 1; i <= N*N; i++) {
magic[row][col] = i;
--row; // Move up
--col; // Move left
if(row <= 0 && col == 0){
row = N - 1;
col = 0;
}
if(row < 0){ row = N-1; } // test if row need to wrap down
if(col < 0){ col = N-1; } // test if col need to wrap right
if(magic[row][col] == 0) {
magic[row][col] = i;
}
else { //check if the spot is taken.
int temp = col;
col = row-1;
row = col;
row = N-1;
if (col < 0){
col = N - 1;
}
}
}
// print results
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();
}
}
}