What is difference between for and for each loop.

What is difference between for and for each loop.Please explain with a example.

Your Answer

for loop:

Uses index
More control (start, end, step)
Java
for(int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}
for-each loop:
No index, directly accesses elements
Simpler, used for arrays/collections
Java
for(int x : arr) {
    System.out.println(x);
}
Difference:
for loop uses index and is flexible, while for-each loop is simpler and used to directly iterate elements.

Html

Didn't get the answer.
Contact people of Talent-Html directly by clicking here