+ 1
Can any one explain working of for each loop
int[] arr ={2,3,4,5}; for(int n: arr){ System.out.println (n);}
3 Answers
+ 6
In foreach loop,
we refer array's each element with a single variable and access it.
Like in above example,
arr is an array. The value of each index of array arr is assigned to variable n one by one and print with System.out.println
+ 6
The loop will run for N times, where N is the number of elements in the array. In each execution of the loop, the array elements are represented by variable n. Hence, on the first loop, the value of n is the value of the first element in the array. On the second loop, the value of n is the value of the second element in the array, etc.
i.e. "For each value in the array, do something..."
+ 1
It will work same as :
for(int i = 0; i<arr.length ; i++){
n= arr[i];
s.o p(n);
}
it is like a shorthand and efficient way to do it.