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

1 Upvotes

2 comments sorted by

•

u/MagicWolfEye 16m 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];
    ...
}

•

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:

for(int row = 0; row < studentGrades.length; row++) {
    for(int col = 0; col < studentGrades[row].length; col++) {
        if (studentGrades[row][col] < lowGrade) {
            lowGrade = studentGrades[row][col];
        }
    }
}

You could just as well write the loops as:

for(int row = 0; row < studentGrades.length; row++) {
    int[] currentGrades = studentGrades[row]; // that's exactly what the enhanced for does in the outer loop
    for(int col = 0; col < currentGrades.length; col++) { // that's the inner loop
        if (currentGrades[col] < lowGrade) {
            lowGrade = currentGrades[col];
        }
    }
}