We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Wednesday, February 25, 2015

Q.What Difference For Loop and For-Each Loop in C#?

Q.What Difference For Loop and For-Each Loop in C#?

Ans:-

Why Loops

If we want to perform the repetitive tasks “n” number of times or an 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 want 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","Parot" }

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 a for-each loop is much more than for loop so For loops are faster than For-each loop.

 

No comments: