mrKapplan - 3 days ago 5

Java Question

I have this code that was written by my professor but i dont fully understand how the diagonal loops are working, it was my work to complete the rows and columns for loops, so i understand what is going on there. The array works like a table, like this:

`int [][] square = {`

//colums 0 1 2 3

//0{16, 3, 2, 13},

//1{5, 10, 11, 8},

//2{9, 6, 7, 12 },

//3{4, 15, 14, 1}};

The parts i dont understand are the for loops that are counting through the diagonals, if i wanted to take the value of the first element i would select position [0][0], lets say i wanted to select the value 10

i would go for [1][1] etc. i just dont see how this:

`for (int i = 0; i < square.length; i++)`

{

sum += square[i][i];

}

selects all of the diagonal values, im sorry but it makes no sense to me. Could someone shed some light.

`public static void main(String[] args) {`

int [][] square = {

{16, 3, 2, 13},

{5, 10, 11, 8},

{9, 6, 7, 12 },

{4, 15, 14, 1}

};

System.out.println("Is magic square: " + magicSquare(square));

}

private static boolean magicSquare(int[][] square){

//calculate the sum of the first row and assign it to n

int n = sumOfRow(square[0]);

for (int[] row : square)

{

int sum = sumOfRow(row);

if (sum != n)

return false;

}

int sum = 0;

//rows

for (int i = 0; i < square.length; i++){

sum = 0;

for (int j = 0; j < square.length; j++){

sum += square[i][j];

}

if(sum != n){

return false;

}

}

// columns

for(int i =0; i < square.length; i++){

sum = 0;

for(int j = 0; j< square.length; j++){

sum += square[j][i];

}

if(sum != n){

return false;

}

}

//diagonal from top left corner to bottom right corner

sum = 0;

for (int i = 0; i < square.length; i++)

{

sum += square[i][i];

}

if (sum != n)

return false;

sum = 0;

// top right to bottom left diagonal

for (int i = 0; i < square.length; i++)

{

sum += square[i][square.length - 1 - i];

}

if (sum != n)

return false;

return true;

}

//returns the sum of the elements in the row

private static int sumOfRow(int[] row){

int sum = 0;

for(int el : row){

sum += el;

}

return sum;

}

Answer

Perhaps this will help. For a 4 x 4 array you can 'unwind' the code replacing `i`

with the values in the for loop:

```
//diagonal from top left corner to bottom right corner
sum = 0;
for (int i = 0; i < square.length; i++)
{
sum += square[i][i];
}
if (sum != n)
return false;
sum = 0;
// top right to bottom left diagonal
for (int i = 0; i < square.length; i++)
{
sum += square[i][square.length - 1 - i];
}
if (sum != n)
return false;
```

Would become:

```
sum = 0;
sum += square[0][0];
sum += square[1][1];
sum += square[2][2];
sum += square[3][3];
if (sum != n)
return false;
sum = 0;
sum += square[0][3];
sum += square[1][2];
sum += square[2][1];
sum += square[3][0];
if (sum != n)
return false;
```

I hope that makes it clear: it's summing up each of the diagonals in turn and comparing to the target value.

Source (Stackoverflow)

Comments