Difference Between For Loop and For Each Loop in C#

A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.

A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.

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();

       }

}                        

Ebook Download
View all
Learn
View all