As the header says, I was tipped by some people that if I wanted to print the sum of everything in an array of numbers, I should use the above-mentioned parameter for a for-loop (code will follow if further explanation is needed). But what is the exact definiton of what that does? The :-part I mean. Is it; for every number i in the array tall?
import java.util.*;
class Uke36{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
int[] tall=new int[5];
for (int i=0; i<=4; i++){
System.out.println("Vennligst oppgi det " + (i+1) + ". tallet: ");
tall[i]=input.nextInt();
}
int sum = 0;
for(int i : tall){
sum+=;
}
}
}
This is how for-each
loops are represented in Java.
for (int i : tall) {
sum += i;
}
Read it as: For each integer i
in the array called tall
...
It's enhanced loop. It was introduced in Java 5 to simplify looping. You can read it as "For each int
in tall
" and it's like writing:
for(int i = 0; i < tall.length; i++)
...
Although it's simpler, but it's not flexible as the for loop.. It's good when you don't really care about the index of the elements.
More reading.
That enhanced for loop equals to
for (int i=0; i < tall.length; i++) {
System.out.println("Element: " + tall[i]);
}
The below form
for(int i : tall){
Is the short hand form the classical for loop.
Note:
But there is a condition to use the above form
Form Language specification
The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.
Here the docs from oracle
Finally
int sum = 0;
for(int i : tall){
sum+=; // sum = sum+i
}
That means adding the all elements in the array.
If it Collection, See how that loop converts :What are for-each expressions in Java translated to?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With