+ 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 */

8th Feb 2018, 4:53 PM
Shivani Goyal
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]); }
8th Feb 2018, 5:01 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 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
10th Feb 2018, 2:35 AM
Maharshi Patel
Maharshi Patel - avatar
+ 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
12th Feb 2018, 2:19 PM
Ashish C Joseph
Ashish C Joseph - avatar
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)
12th Feb 2018, 6:10 PM
ankit bihani
ankit bihani - avatar
"foreach" loop are use to print collection of elements
18th Feb 2018, 3:34 PM
vishnu kumar
vishnu kumar - avatar