A for loop allows one to repeatedly execute code in a loop until a condition is met.
for (int i = 0; i < 5; i++)
{
System.Console.Write(i);
}
// => 01234
A for loop consists of four parts:
true.In general foreach-loops are preferrable over for loops for the following reasons:
foreach loop is guaranteed to iterate over all values. With a for loop, it is easy to miss elements, for example due to an off-by-one error.foreach loop is more declarative, your code is communicating what you want it to do, instead of a for loop that communicates how you want to do it.foreach loop is foolproof, whereas with for loops it is easy to have an off-by-one error.foreach loop works on all collection types, including those that don't support using an indexer to access elements.To guarantee that a foreach loop will iterate over all values, the compiler will not allow updating of a collection within a foreach loop:
char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };
foreach (char vowel in vowels)
{
// This would result in a compiler error
// vowel = 'Y';
}
A for loop does have some advantages over a foreach loop:
for loops in scenarios that don't involve collections.