+ 2

Difference between for for Loop and Enhanced for Loop with example?

Loops

28th May 2019, 8:21 AM
Ashish Mewada
Ashish Mewada - avatar
5 ответов
28th May 2019, 8:29 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 2
For loop and enhanced for loop work same but difference in their syntax... Code int a[】={1,2,3,4,5}; /*for loop code*/ for(int i=0;i<5;i++) { System. out.println(a[¡]); } /*enhanced for loop example */ for(int b:a) { System. out.println(b); }
28th May 2019, 6:20 PM
Ajay
Ajay - avatar
+ 1
Ajay in the enhanced for loop can we initialize b to a specific array element?
1st Jun 2019, 9:36 AM
Jazib Dawre
Jazib Dawre - avatar
0
an enhanced for loop can be translated to “Foreach/element/in/elements” or for example: String lines[] = {“hello”, “hi”, “hey”}; for(String line : lines) { System.out.println(line); } line being the element, the semicolon being “in” and lines being the array of elements. So each time it loops it will print out each element in the lines array: hello hi hey this is just essentially an easier or “enhanced” way of using the standard for loop to produce the same outcome: String[] lines = {“hello”, “hi”, “hey”}; for(int i = 0; i < lines.length; i++){ System.out.println(lines[i]); } the enhanced for loop is best used for iterating through a list/array/collection, whereas the standard for loop would be best when you know exactly how many times you’re going to be looping through a block of code.
30th May 2019, 5:01 AM
Jake
Jake - avatar