Hello, I'm doing the Java course, and I was wondering if there was a better way to do the for loop on an array, for example the for each loop?
Hey! Yep, you are right - we can use a for-each loop.
Suppose we have an int array "arr", then we can iterate with:
for(int num: arr){ },
where num is a naming assignment. This will iterate through each term in an array. For example,
int[] arr = {1,2,3,4,5};
int sum = 0;
for(int num: arr){ sum += num;
}
This will increment the sum of all the numbers in the array. Does this clear it up?