what is enhanced for loop and how it works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

what is enhanced for loop and how it works?

for(i: arr[])

8th Aug 2019, 2:27 PM
Nagaraj P
Nagaraj P - avatar
5 Answers
+ 6
Different languages implement enhanced for loops in different ways. But the common objective is to transverse through all of the elements in an array, list or any other collection. Out of the languages you asked I can tell you about java and js In java you can use enhanced loop on arrays and classes implementing the Collections framework. Example usages are //for arrays for (var e : Object[] {54, 5, 4, 535, 6}){ //you can replace var with the datatype of the array } //for Collections (We'll use an List here) for (var e : Arrays.asList(4,3,5,4,3,5,3)) { } **"How they works?" continues below ☺
8th Aug 2019, 2:38 PM
Seniru
Seniru - avatar
+ 6
"How they work?" I ll give you examples in java Look at the following code. Basically it declares an array an prints all the values of it. var arr = new int[] {54,5,3,6,6,3,2,81}; for (var i = 0; i < arr.length; i++) { System.out.println(arr[i]); //prints all the integers in arr } You can simply convert this code into this for (var i : arr) { System.out.println(i); //prints all the integers in arr } Clean right? 😜 This also reduce verbosity and saves the time For js also we have a similar thing like this. They are for ..in loops and for .. of loops. I ll mention you lessons for that https://www.sololearn.com/learn/JavaScript/2970/?ref=app
8th Aug 2019, 2:45 PM
Seniru
Seniru - avatar
+ 5
It will index a variable through an array and run the loop content for each element in the array. int[] arr = {5, 3, 8, 6, 0}; for (int el: arr) { //... } //corresponds: for (int i = 0; i < arr.length; ++i) { int el = arr[i]; //... } keyword \ _____/ | | datatype of each | item of the array. | \ ______________/ | | | | variable name | | whose value will be | | changed in each | | iteration of the loop. l | \ _________________/ | | | | | | The array that | | | is being | | | iterated through. | | | \ ______________/ | | | | | | | | Basic code | | | | that will be ran | | | | for each item | | | | in the array. | | | | \ ___________/ v v v v v for (int el: arr) {...}
8th Aug 2019, 2:55 PM
Seb TheS
Seb TheS - avatar
+ 2
it is like normal for() loop, but instead i++ and using e=array[i], you by simple way direct get element from array into variable e and then you can work with it like s.println(e) but e is copy of value, so e++ change nothing in array (or collection)
8th Aug 2019, 7:29 PM
zemiak
0
Nice!
11th Aug 2019, 3:58 PM
Juan Debenedetti
Juan Debenedetti - avatar