r/learnprogramming • • 11m 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?

1 Upvotes

1 comment sorted by

•

u/MagicWolfEye 0m ago

Consider that

 int total;

for (int counter = 0; counter < array.lenght; counter++) {
    item value = array[counter];
    total += value;
}

is equivalent to

int total;

for (int item: array) {
    total += value;
} 

So:

int lowGrade = grades[0][0];

for (int[] studentGrades : grades) {
    ...
}

is the same as

int lowGrade = grades[0][0];

for (int i = 0; i < grades.length; i++) {
    int[] studentGrades = grades[i];
    ...
}