For Loop and For-Each Loop in C#

 

Why Loops


If we want to perform the repetitive tasks “n” number of times or infinite number of times then it is good practice to use loops.

 

For Loops:

For loops are appropriate loops when you know exactly how many times iteration you wants in statements within the loop.

For loop iterates a statement or a block of statements repeatedly until a specified expression evaluates to false.

 

Syntax:

 

        for (; Boolean-expression;)
        
         ….Statement
        }  

 

For Example:


            for(int I =0; I <= 20; I++)
            
               if(I%2 == 0)
                Console.WriteLine(“Print Even Numbers 0}”,I);
               }
               }

 

 

ForEach Loops


For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.

 

Syntax:

 

         foreach (  )
        
         ….Statement
         }   

 

For Example:

 

        string[] AnimalNames = new string[] "Dog","Tiger","Panda","Penguin" } 
        foreach (string animal in AnimalNames)
        
          Console.WriteLine(“Name of animal is 0}“,animal);
        }    


Difference Between For and For Each Loop


  1. For loop iterates a statement or a block of statements repeatedly until a specified expression evaluates to false.
  2. For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.
  3. Performance: For Loops are faster than For-each Loop. If we iterate array list or any collection with for loop and for-each loop then you will find time consumed by for-each loop is much more than for loop so For loops are faster than For-each loop.

 

 

:: SHARE THIS POST ::

        
 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

lqroh

 

 
Comments

Posted by Ramana on 2015-09-12

Nice ... i like it .... simply understand each point...

Posted by Prabhakar Bharti on 2015-08-12

Nice Article sir

Posted by Gdrealspace on 2012-06-11

Nice Article bro..