Thursday, March 21, 2013

Difference between for and for each loop..?


They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.Following Difference  for and for each loop.


  1. For can be used to run statements for a fixed number of times, 
    Foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query). Foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one. 
  2. Foreach will works only and only with arrays.
    For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference.

  3. For loop can be more optimized if we know the count of array and index of array.
    Foreach is better when we have dynamic array without knowing index of array and size of an array.
  4. For loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. there is need to specify the loop bounds( minimum or maximum).
    int k = 0;
    for (int i = 1; i <= 5; i++) 
    k = k + i ; 
    }



    Foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
    int k = 0;
    int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; 
    foreach (int i in tempArr ) 
    k = k+ i ; 
    }

No comments:

Post a Comment