r/learnprogramming • u/Eva_addict • 26m ago
I need help understanding a particular case of an improved for loop using an array as a parameter. (Java)
I am learning Java using Deitel's book. This particular for loop uses and array as a parâmeter but I can't understand exactly how it's supposed to work.
int lowGrade = grades[0][0];
for (int[] studentGrades : grades)
{
for (int grade : studentGrades)
{
if (grade < lowGrade)
lowGrade = grade;
}
}
For all I understood, the improved for loop works the same as this other example here:
int total;
for (int counter = 0; counter < array.lenght; counter++)
{
total += array[counter];
}
But I don't understand how the first one could work in a similar way with an array as a parameter since in the example in the book, the array grades is a bidimentional array. What is that first for loop doing to the int[ ] studentGrades?
The books says something like: " The external improved for loop iterates through the bidimentional array grades assingning new lines to the parameter studentGrades.". How does that even work?
•
u/MagicWolfEye 16m ago
Consider that
is equivalent to
So:
is the same as
•
u/desrtfx 2m ago
You are dealing with a multi-dimensional array, which, in Java is just an array of arrays.
So, the outer for-each (enhanced for) loop goes through the first dimension and returns an array of int on each iteration. The inner loop goes through that returned array.
With "conventional" for loops, it would look like this:
You could just as well write the loops as: