Wednesday 19 August 2015

What is difference between For loop and Foreach loop in C#.Net

For Loop:
  • In case of for the variable of the loop is always be int only.
  • The For Loop executes the statement or block of statements repeatedly until specified expression evaluates to false.
  • There is need to specify the loop bounds(Minimum, Maximum).
example:  
       
               using sytem;
                 class class1
                 {
                   static void Main()
                    {
                      int j=0;
                       for(int i=0; i<=10;i++)
                         {
                           j=j+1;
                            }
                             Console.ReadLine();
                                }
                           }        


 Foreach  loop :

  •  In case of Foreach the variable of the loop while be same as the type of values under the array.
  • The 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.
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