Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: help 2d array confusion

1. ## help 2d array confusion

```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

2. ## Re: help 2d array confusion

```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.

3. ## The Following User Says Thank You to javapenguin For This Useful Post:

Macgrubber (November 27th, 2010)

4. ## Re: help 2d array confusion

So result will still be 0?

5. ## Re: help 2d array confusion

```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])

6. ## 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];

```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.