# help 2d array confusion

• November 27th, 2010, 06:17 PM
Macgrubber
help 2d array confusion
Code Java:

```int [] [] matrix = { {16, 3, 2, 13}, {5, 10, 11, 8}, {2, 6, 7, 12}, {2, 15, 14, 1} };       result = 0; for(row = 3 ; row > 3; row--){ result = matrix[row][row] +result; } sumDiag2 = result; if (sumDiag2 == magic){ System.out.println("Minor Diagonal = "+ result + " OK");} else System.out.println("Minor Diagonal = "+ result + " NOT OK");     } }```

ok so i have this code i want to add the minor diagonals which should be 32 (13,11,6,2)
but i keep getting 0... i dont get it help
• November 27th, 2010, 10:46 PM
javapenguin
Re: help 2d array confusion
Code java:

```for(row = 3 ; row > 3; row--){ result = matrix[row][row] +result; }```

This will never go through the for loop as row is already 3, which means that it already is not greater than 3.

That might be part of the problem.
• November 27th, 2010, 10:47 PM
javapenguin
Re: help 2d array confusion
So result will still be 0?
• November 28th, 2010, 12:28 AM
Macgrubber
Re: help 2d array confusion
Code java:

```result = 0; for(row = 3 ; row >= 0; row--){ result = matrix[row][row] +result; } sumDiag2 = result; if (sumDiag2 == magic){ System.out.println("Minor Diagonal = "+ sumDiag2 + " OK");} else System.out.println("Minor Diagonal = "+ sumDiag2 + " NOT OK");```

oh darn i overlooked sorry so i changed it to row >= 0
now it just displays 34 when it supposed to display 32

i dont understand its supposed to add
matrix[3][3] because the value of row starts at 3
but it keeps computing the value of the major diagonal (matrix[0][0])
• November 29th, 2010, 04:30 PM
javapenguin
Re: help 2d array confusion
for(row = 3 ; row >= 0; row--){
result = matrix[row][row] +result;
}

First iteration x = 3
result = matrix[3][3];
Second iteration x = 2
result = matrix[3][3] + matrix[2][2];
Third iteration x = 1
result = matrix[3][3]+ matrix[2][2] + matrix[1][1];
Fourth iteration x = 0;
result = matrix[3][3] + matrix[2][2] + matrix[1][1] + matrix[0][0];

So result should be

1 + 7 + 10 + 16
= 34

I could think that perhaps an array of results

result[0] = matrix[3][3];
result[1]= result[0] + matrix[2][2];
result[2] = result[1] + matrix[1][1];
result[3] = result[2] + matrix[0][0];

Code java:

```for (int x = 0; x < =3; x++) { if (x ==0) result[x] = matrix[3-x][3-x];   else { result[x] = result[x-1] + matrix[3-x][3-x]; } }```

Now check if result[3] = magic.