So I'm trying to print a magic Square. The program is complete but when it prints the magic square it comes out reversed. The output for a 3X3 should look like this:
8 1 6
3 5 7
4 9 2
but instead I'm getting this:
4 9 2
3 5 7
8 1 6
I don't know what I am doing wrong, any help would be great. Here's my code for making the magic square and also printing it:
//magic square
public static int[][] magicSq(int[][]table,int size){
int [][]magic=new int[size][size];
int row=size-1;
int col=size/2;
magic[row][col]=1;
for(int i=2;i<=size*size;i++){
if(magic[(row+1)%size][(col+1)%size]==0){
row=(row+1)%size;
col=(col+1)%size;
}
else{
row=(row-1+size)%size;
}
magic[row][col]=i;
}
return magic;
}
//print magic sqaure
public static void printSq(int[][]magic,int size){
int constant=0;
for(int r=0;r<size;r++){
for(int c=0;c<size;c++)
System.out.printf("%5d",magic[r][c]);
System.out.println();
constant=constant+magic[r][0];
}
System.out.println("The magic square contant is "+constant);
}
If your only problem is that it's printing the rows in the opposite order from what you'd like you can just change the order in which you print the rows:
for(int r=size-1;r>=0;r--)
Also, I'm a little confused by your code. The method magicSq is accepting an int[][]table as a parameter but then never does anything at all with it. Is the code supposed to do something with that table?