I wrote a magic square program and it's run good.
But I need to reverse the output of my work into this: (look at the output):
Currently my program output is:
My desired output is:
This is my code at the moment:
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 = num - 1;
int col = num / 2;
magic[row][col] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic[(row + 1) % num][(col + 1) % num] == 0) {
row = (row + 1) % num;
col = (col + 1) % num;
} else {
row = (row - 1 + num) % num;
// don't change
}
magic[row][col] = i;
}
// print results
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
System.out.print(magic[i][j] + "\t");
}
System.out.println();
}
}
Guys, Please help me to debug my code, All i need is a little changes that wont totally hurt my code. I think there's something to change in my LOOP but I couldn't find it.
Maybe the mathematically formula..
You need to print out in reverse - start from the end. Change your loop traversal condition as shown below
or keeping the loop variables intact use