What is difference between for and for each loop.

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


12 Answers
1-12 of  12
12 Answers
  • for loop: Used when you know the number of iterations (uses index). forEach loop: Used to iterate over elements of an array directly (no index control). Example: JavaScript // for loop for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // forEach loop arr.forEach(function(item) { console.log(item); });

  • 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.

  • For loop is best for iterating over name value pairs and for each loop is best for iterating over values

  • The for loop is best for iterating over name-value pairs, and the forEach is loop best for iterating over values, for example arrays or objects. The for loop is best for name-value pairs. The for loop can be used to explore the possible properties and methods of an object. The forEach loop is best for iterating values.

  • a for loop is a construct that says "perform this operation n. times". a foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"

  • For-each loop in Java
    Prerequisite: Decision making in Java
    For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5.

    * It starts with the keyword for like a normal for-loop.
    * Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
    * In the loop body, you can use the loop variable you created rather than using an indexed array element.
    * It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

    Syntax:

    for (type var : array) { statements using var; }

    is equivalent to:

    for (int i=0; i<arr.length; i++) { type var = arr[i]; statements using var; }
    // Java program to illustrate 
    // for-each loop
    class For_Each     
    {
        public static void main(String[] arg)
        {
            {
                int[] marks = { 125, 132, 95, 116, 110 };
                  
                int highest_marks = maximum(marks);
                System.out.println("The highest score is " + highest_marks);
            }
        }
        public static int maximum(int[] numbers)
        { 
            int maxSoFar = numbers[0];
              
            // for each loop
            for (int num : numbers) 
            {
                if (num > maxSoFar)
                {
                    maxSoFar = num;
                }
            }
        return maxSoFar;
        }
    }

    Output:

    The highest score is 132
    Limitations of the for-each loop

    1. For-each loops are not appropriate when you want to modify the array:

    for (int num : marks)
    {
    // only changes num, not the array element
    num = num*2;
    }

    2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop

    for (int num : numbers)
    {
    if (num == target)
    {
    return ???; // do not know the index of num
    }
    }

    3. For-each only iterates forward over the array in single steps

    // cannot be converted to a for-each loop
    for (int i=numbers.length-1; i>0; i--)
    {
    System.out.println(numbers[i]);
    }

    4.For-each cannot process two decision making statements at once

    // cannot be easily converted to a for-each loop
    for (int i=0; i<numbers.length; i++)
    {
    if (numbers[i] == arr[i])
    { ...
    }
    }

  • Hello,
    The main difference between for and for each loop is to set the number of iteration manually. In for loop you have to set the number of iteration manually while in for each loop the iteration will be counted automatically as per the length of an array. Following the example of both loops respectively.

    For Loop
    int[] arr = new int[5];
    arr[0] = 5;
    arr[1] = 7;
    arr[2] = 13;
    arr[3] = 20;
    arr[4] = 25;
    for(int i=0;i<5;i++){
         print(arr[i]);
    }

    Foreach Loop
    foreach(var i in arr){
         print(i);
    }

  • The  foreach loop works only on arrays, and is used to loop through each key/value pair in an array. The main difference is that, you can set the number of iterations in for loop by adjusting counter value. Whereas in foreach loop, the iterations depend on the number of values of the array.

  • 1) Foreach loop used when you have an array, without array it's not worked.
    2) For loop used according to condition.

  • FOR EACH LOOP work only on arrays.In this the iterations depend on the number of values on the array.But in FOR LOOP we can set the number of iterations by adjusting counter value.
    FORLOOP EXAMPLE:
    <?php
    for( $i = 0 ; $i < 5 ; $i++)
    {
    $mul= 10 * $i;
    echo "result of 10*$i is $mul.<br>";
    }
    ?>
    Output:
    result of 10*0 is 0.
    result of 10*1 is 10.
    result of 10*2 is 20.
    result of 10*3 is 30.
    result of 10*4 is 40.


    FOREACH LOOP EXAMPLE:
    <?php
    $alp = arr("ab"," bc","cd","de");
    foreach($alp as $ arr_values)
    {
    echo $arr_values."<br>"
    }
    ?>
     
    Output:
    ​ab
    bc
    cd
    de

  • 1. Foreach Loop:- Details are following.

    a) Foreach loop used when you have an array, without array it's not worked.
    b) Loop working at the end of array count. For example an array have 5 value then loop run 5 times.
    c) Syntax is following.

    $array = array("Surinder","Rahul","Manoj","Bharti","Rana","Manish"); Foreach($array as $name )
    {
    echo "Employe Name is ".$name.".";
    }
    This will print as following.
    Employe Name is Surinder.
    Employe Name is Rahul.
    Employe Name is Manoj.
    Employe Name is Bharti.
    Employe Name is Rana.
    Employe Name is Manish.


    2. For Loop:- Details are following.
    a) For loop used according to condition.
    b) Loop working at the end of given condition.
    c) Syntax is following.
    $array = array("Surinder","Rahul","Manoj","Bharti","Rana","Manish");
    For($i=0;$i<6;$i++)
    {
    echo "Employe Name is ".$array[$i].";
    }
    At the place of 6,You can used count array function.

    This will print as following.
    Employe Name is Surinder.
    Employe Name is Rahul.
    Employe Name is Manoj.
    Employe Name is Bharti.
    Employe Name is Rana.
    Employe Name is Manish.

Html

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