+ 11
i'm unable to understand "for each " loop..
int[ ] primes = {2, 3, 5, 7}; for (int t: primes) { System.out.println(t); } /* 2 3 5 7 */
5 Answers
+ 4
It's basically saying this:
FOR EACH item INSIDE OF array {
// do this to each element
}
It's looping through EACH element of the array and performing whatever code you specify. The loop ends once it reaches the end of the array. As you can see by your output, it printed out EACH element of the array and stopped.
't' is the variable that holds the current element of that iteration of the loop. In other loops that's the equiv of primes[i] (i being the loop counter variable).
It's basically a simplified version of:
int[ ] primes = {2, 3, 5, 7};
for(int i = 0; i < primes.length; ++i) {
System.out.println(primes[i]);
}
+ 3
you can see int t:primes and primes contain some elements. so when it will run then int t will be assigned by all value of primes one by one.
After it will print on the screen
+ 1
In C# foreach loop helps us to operate on every elements of an array from the first element to the last element
eg:
int[] Diamonds= new int[]{0,2,4,6,8};
foreach (int b in Diamonds)
{
Console.WriteLine(b*b);
}
OUTPUT:
0
4
16
36
64
0
for each loop is advance loop it works only in forward direction . It always increment by 1 after every pass .Here we take variable (t) same fata type as out array .
first element from array primes [0] will copy to (t)
then we manipulate (t)
0
"foreach" loop are use to print collection of elements