For Loop and For-Each Loop in C#
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 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.
for (; Boolean-expression;) ….Statement }
for(int I =0; I <= 20; I++) if(I%2 == 0) Console.WriteLine(“Print Even Numbers 0}”,I); } }
For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.
foreach ( ) ….Statement }
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
- For loop iterates a statement or a block of statements repeatedly until a specified expression evaluates to false.
- For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.
- 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.
By Ramana on 2015-09-12Nice ... i like it .... simply understand each point...
By Prabhakar Bharti on 2015-08-12Nice Article sir
By Gdrealspace on 2012-06-11Nice Article bro..
Add a Comment
Thank you, for commenting !!
Your comment is under moderation...
Keep reading other blogs