Can someone explain the logic behind looping through multidimensional arrays?

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.

ehm,
index1 = the index of the first element (row) in the array, say numbers[0][1], no?
index 2 = the index of the first element (column) in the array
numbers = the array
numbers[i]= the current index the loop is in
numbers[i].length (no idea, this is in fact the source of my confusion)
index2++ = no idea.

Good job, and that little exercise pointed to the source of your confusion.

Some disagree with the description of arrays in Java as "multi-dimensional." They insist, for example, that a 2D array in Java, myArray[x][y], is 'x' arrays of 'y' arrays, and 'y' doesn't have to be the same for each 'x'. That's why the notation you're confused about is important.

Imagine the array was defined this way instead of the way in your original post:

int [][] numbers = {{5,3,2},{7,5}};

In this case, y = 3 elements in the first row but only 2 elements in the second row. Then to get the iteration right in nested for loops, the inside loop - the one that iterates through each column element - has to account for this difference in length:

numbers.length=2// for 2 rows
numbers[0].length=3// for 3 elements in the first row (3 columns)
numbers[1].length=2// for 2 elements in the second row (2 columns)