For class we have to do a magic square. I got my code somewhat working but it does multiple squares and the final one always returns 0, Here is how a magic square works.
Here is how I check
public int downDiagSum() {
int sum = 0;
for(int r = 0; r < grid.length; r++){
for(int c = 0; c < grid.length; c++){
sum += grid[r][c];
}
}
return sum;
public int upDiagSum() {
int sum = 0;
for(int r = grid.length - 1; r >= 0; r--){
for(int c = 0; c < grid.length; c++){
sum += grid[r][c];
}
}
return sum;
public int colSum(int col) {
int sum1 = 0;
for(int r = 0; r < grid[0].length; r++){
sum1 += grid[r][col];
}
return sum1;
public int rowSum(int row) {
int sum2 = 0;
for(int r = 0; r < grid[0].length; r++){
sum += grid[row][r];
}
return sum2;
public boolean isMagicSquare() {
int num = rowSum(0);
boolean isEqual = false;
if(downDiagSum() == upDiagSum()){
//row check
for(int r = 0; r < grid.length; r++){
if(rowSum(r) == num){
isEqual = true;
}
}
//column check
for(int r = 0; r < grid.length; r++){
for(int c = grid.length - 1; c >= 0; c--){
if(colSum(c) == num){
isEqual = true;
}
}
}
}
return isEqual;}
The code mostly works but if I have a series it always returns true for some reason. The number set below is supposed to return false but returns true
6 32 2 34 35 1
7 11 27 28 8 30
19 14 16 15 23 24
18 20 22 21 17 13
25 29 10 9 26 12
36 5 33 4 3 31
Sorry for bad formatting i'm still very new to site. Thanks, Garrows