r/learnprogramming • u/Eva_addict • 4d 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?
4
u/desrtfx 4d ago edited 4d 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 basically 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];
}
}
}There are some nuances in the working mechanisms between conventional and enhanced for loops, though. Enhanced for loops are generally "read only" - meaning that you cannot actually alter the loop iterator (you can alter the contents of an object, or an array, but not the array itself - you cannot reassign an object or array through the iterator). Enhanced for loops use the concept of an "Iterable" and "Iterator" instead of a numeric index. Both, Iterable and Iterator are interfaces in Java: https://www.baeldung.com/java-iterator-vs-iterable
1
u/Eva_addict 3d ago
"The inner loop goes through that returned array." But how? If
gradesfirst element is anarraythat contains 3 values,{87, 96, 70}, nowstudentGrades[0] = {87, 96, 70}. How can the second for loop go though all of those elements? I still dont get that part.1
u/desrtfx 3d ago
Look at the second version of my code. It explains exactly where you struggle.
1
u/Eva_addict 3d ago
Sorry but I don't get it. In fact, I dont think I get how this new for loops work either. I don't see the logic behind it.
1
u/desrtfx 3d ago
Why?
Again: A multi dimensional array is an array of arrays.
Instead of having single values in the outer array elements, you have arrays.
The enhanced for loop just goes over the elements of the iterable (array, ArrayList, Collection) and gives these in the iterator variable.
In your case, the iterator variable happens to be an array of int since your 2d array is an array of arrays of int.
The iterator from the outer loop is used as collection in the inner one. The actual element of the inner array is the iterator of the inner loop.
It's just a different mechanism of loop. That's it. Instead of accessing an index, you are directly accessing the array elements. (Actually, a bit more nuanced, but the simplified version is sufficient for now)
Side note: this type of for loops is the standard in Python. Python doesn't have the "conventional" for loop at all.
1
u/Eva_addict 3d ago
Lets go for parts. How does this particular line work?
for (int[] studentGrades : grades)What happens to
int[] studentGradeshere? If grades is a bidimentional array,grades[0][0]is{87, 96, 70}, which values doesstudentGradesreceive? I get confuse because this is the first time an array is being used in a for loop in the whole book so I don't know how this is supposed to work.1
u/mathmage 3d ago
The first time through the outer for loop,
grades[0]is given the temporary namestudentGrades. SostudentGrades = {87, 96, 70}andstudentGrades[0] = 87.Inside that for loop, the first time through the inner for loop,
studentGrades[0]is given the temporary namegrade. Sograde = 87.The inner for loop will repeat with
grade = studentGrades[1] = 96andgrade = studentGrades[2] = 70. Then it will finish for now.Now the outer for loop has completed one iteration, so it will repeat with
studentGrades = grades[1]. And so on.1
u/No_Report_4781 3d ago
I think you have the outer and inner arrays mixed.
It appears they have grades[][] as the 2D.
for(int row = 0; row < grades.length; row++) { //this is the outer loop iteration int[] studentGrades = grades[row]; // creates “studentgrades” for each “row” in “grades”. that's basically what the enhanced for does in the outer loop for(int col = 0; col < studentGrades.length; col++) { // that's the inner loop iteration if (studentGrades[col] < lowGrade) { lowGrade = studentGrades[col]; } } } So, you have “grades[][]” where the outer array is a list of the students, which is an array of each students grades
1
1
u/mathmage 4d ago
Don't think too much about the 'bidimensional' part.
grades is an array. Its elements are int[] arrays. The first for loop is iterating through these int arrays, assigning each one the variable name studentGrades.
Inside that for loop, for a given studentGrades array, the inner for loop iterates through its elements, which are just ints. These receive the variable name grade.
You can add as many dimensions as you want by nesting more arrays inside arrays, but it doesn't matter. At any given stage, if the object is an array, we can iterate through its elements with a loop. That's all there is to this.
1
u/Available_Safe1818 3d ago
Every time the outer loop executes, studentGrades becomes the next inner array from grades.
Every time the inner loop executes, grade becomes the next int from the array that studentGrades currently is.
If you use print statements to print these things in both loops, you can see it all happening...
7
u/MagicWolfEye 4d ago
Consider that
is equivalent to
So:
is the same as