Unit 5 Lesson 5 Enhanced For Loops to traverse 2D Array

Hi @cicaneser,
Thanks for your question. I think I am understanding the spot where this gets confusing, in double loops that are set up like this:

for (int row : matrix) {// don’t need index here
for (int index = 0; index < row.length ; index ++) {//need index here
row[index] += 2 ;//this will change what is stored
}
}

The outer loop is an enhanced for loop that takes each inner array out of the 2D array. Since what it is getting is a 1D array, that row is stored using a reference address, and row copies the address that points to the “actual data”.

The inner loop now is going to get each primitive int value from the row. If we used an enhanced for loop there it would make a copy of that value and we wouldn’t be able to change what is stored. So having the inner loop set up with an index allows this to get to the ‘actual data’ not just a copy, and change the values stored.

This concept can feel confusing because the int row holds primitives, but since it is a 1D array itself, it is an object and the outer enhanced for loop copies the reference address.

I hope that helps,
Lindsay

1 Like