Hi I created a Magic Square program in java It works fine if you input a number 3 but if i input 5 and so on there's a problem occurring.. The pattern becomes wrong.
Please help me to find out what's wrong in my code:
Here's my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
// Number must be ODD and not less than or equals to one to continue
while ((num % 2 == 0) || (num <= 1)) {
System.out.println("Enter a valid number: ");
num = input.nextInt();
}
int[][] magic = new int[num][num];
int row = 0;
int col = num / 2;
magic[row][col] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic[(row + 5) % num][(col + 2) % num] == 0) {
row = (row + 5) % num;
col = (col + 2) % num;
} else {
row = (row + 1 + num) % num;
}
magic[row][col] = i;
}
for (int x = 0; x < num; x++) {
for (int j = 0; j < num; j++) {
System.out.print(magic[x][j] + "\t");
}
System.out.println();
}
}
It's correct when i Input 3, here's the output:
But when i type a number like 5: It becomes:
UPDATED!
You seem to be trying to implement the Method for constructing a magic square of odd order.
You seem to have that right.
I would code this as:
This is clearly:
I know this doesn't actually solve your problem but I hope it gets you somewhere towards your goal. See how I take the words of the algorithm and match them as accurately as possible with code.