I have to write a program that takes in an odd number from the user and creates a magic square. A magic square is one where the sum of each row, column, and diagonal is the same. These are the characteristics for writing the code:
- Ask the user for an odd number
- Create an n by n array.
- Follow these steps to create a magic square.
a. Place a 1 in the middle of the first row.
b. Subtract 1 from the row and add 1 to the column.
i. If possible place the next number at that position.
ii. If not possible, follow these steps.
- If in row -1, then change to last row
- If in last column change to first column
- If blocked, then drop down to next row (from original position)
- if in the upper right corner, then drop down to next row.
- Print the array
I've written the code but when I run it, the program puts in all the numbers except for the number two; for some reason, my program skips over it. For example, if I put in the number 3 as the odd number, my output is:
6 1 0
3 4 5
9 7 8
0 isn't supposed to be there but the number two is. Here is my code:
public static void main(String[] args) {
System.out.print("Give an odd number: ");
int n = console.nextInt();
int[][] magicSquare = new int[n][n];
int number = 1;
int row = 0;
int column = n / 2;
while (number <= n * n) {
magicSquare[row][column] = number;
number++;
row -= 1;
column += 1;
if (row == -1) {
row = n - 1;
}
if (column == n) {
column = 0;
}
if (row == 0 && column == n - 1) {
column = n - 1;
row += 1;
} else if (magicSquare[row][column] != 0) {
row += 1;
}
}
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare.length; j++) {
System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
}
Could someone tell me where I went wrong and why my program is skipping the number 2? *This is a homework question so code only answers, please. Thanks.
Removing 3.4 will probably fix your code.
public static void main(String[] args) {
System.out.print("Give an odd number: ");
int n = console.nextInt();
int[][] magicSquare = new int[n][n];
int number = 1;
int row = 0;
int column = n / 2;
int curr_row;
int curr_col;
while (number <= n * n) {
magicSquare[row][column] = number;
number++;
curr_row = row;
curr_col = column;
row -= 1;
column += 1;
if (row == -1) {
row = n - 1;
}
if (column == n) {
column = 0;
}
if (magicSquare[row][column] != 0) {
row = curr_row + 1;
column = curr_col;
if (row == -1) {
row = n - 1;
}
}
}
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare.length; j++) {
System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
}
Setting n = 3 gets me the following output which seems correct.
8 1 6
3 5 7
4 9 2