For Loop and For-Each Loop in C#
- By Gurunatha Dogi in C#
- Nov 19th, 2012
- 26908
- 3
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
- 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.
Gurunatha Dogi
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 and lots more..... read more