Wednesday, August 29, 2012

Difference between for and foreach loop


S.NoFor loopForeach loop
1In case of for the variable of the loop is always be int only.In case of Foreach the variable of the loop while be same as the type of values under the array. 
2The For loop executes the statement or block of statements repeatedly until specified expression evaluates to false. The Foreach statement repeats a group of embedded statements for each element in an array  or an object collection. 
3There is need to specify the loop bounds(Minimum, Maximum). We do not need to specify the loop bounds minimum or maximum. 
4
example:  
using sytem;
  class class1
  {
      static void Main()
      {
         int j=0;
         for(int i=0; i<=10;i++)
          {
            j=j+1;
          }
           Console.ReadLine();
        }
      }  
example:  
using sytem;
  class class1
  {
     static void Main()
      {
        int j=0;
        int[] arr=new int[] {0,3,5,2,55,34,643,42,23};
        foreach(int i in arr)
        {
           j=j+1;
         }
         Console.ReadLine();
       }
  }  

No comments:

Post a Comment