12 Replies Latest reply: Mar 30, 2008 7:18 PM by 807591

# Help with 2D arrays

I am required to make a magic squares program using a 2D array. How would I iterate it to separately add the row, column, and diagonals? I have four separate methods for doing each
``public int sumRow(int row)``
``public int sumCol(int col)``
``public int sumMainDiag()``
``public int sumOtherDiag()``
Edited by: sammusashi on Mar 30, 2008 3:59 PM
• ###### 1. Re: Help with 2D arrays
Iterate one dimension in an inner loop. Place that loop inside an outer loop that iterates the other dimension.
• ###### 2. Re: Help with 2D arrays
Loops.
• ###### 3. Re: Help with 2D arrays
ChuckBing wrote:
Iterate one dimension in an inner loop. Place that loop inside an outer loop that iterates the other dimension.
For row and column you don't need nested loops.
• ###### 4. Re: Help with 2D arrays
would I set a variable inside the loop to the value of the parameter? something like this for example
``````public int sumRow(int row)
{
for(int newRow = row; row < square.length; newRow++)
}``````
square is the name of my 2D array.
• ###### 5. Re: Help with 2D arrays
Why would you want to do that? Since you never change the value of row you will either be in an infinite loop or get an ArrayIndexOutOfBoundsException.
• ###### 6. Re: Help with 2D arrays
I thought that would iterate it to add. What would I do with the parameter if that's the case then?
• ###### 7. Re: Help with 2D arrays
You want to add up all the values in a single row. So row should not change, what should change instead?
• ###### 8. Re: Help with 2D arrays
column should change. I'm just not sure how to go about getting the column. unless there was a
``.height ``
method or something
• ###### 9. Re: Help with 2D arrays
sigh!
``````int sum = 0;
for(....;....;....) {
sum += square[....][....];
}``````
Just fill in the dotted lines.
• ###### 10. Re: Help with 2D arrays
I've come up with this
``````public int sumRow(int row)
{
int sum = 0;
for (int x = 0; x < square.length; x++)
sum+= square[row][0];
}``````
• ###### 11. Re: Help with 2D arrays
Apart from a missing return statement, does it work?
• ###### 12. Re: Help with 2D arrays
I'm still working on it but your help is greatly appreciated.