This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!
for
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. It takes the following form:
for ([initializers]; [expression]; [iterators]) statement
where:
- initializers
- A comma separated list of expressions or assignment statements to initialize the loop counters.
- expression
- An expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators. The expression is used to test the loop-termination criteria.
- iterators
- Expression statement(s) to increment or decrement the loop counters.
- statement
- The embedded statement(s) to executed.
Remarks
The for statement executes the statement repeatedly as follows:
- First, the initializers are evaluated.
- Then, while the expression evaluates to true, the statement(s) are executed and the iterators are evaluated.
- When the expression becomes false, control is transferred outside the loop.
Because the test of expression takes place before the execution of the loop, a for statement executes zero or more times.
All the expressions of the for statement are optional, for example, the following statement is used to write an infinite loop:
for (;;) {
...
}
Example
// for loop
using System;
public class ForLoopTest {
public static void Main() {
for (int i = 1; i <= 5; i++)
Console.WriteLine(i);
}
}
Output
1
2
3
4
5
See Also
C# Keywords | Compare to C++ | Iteration Statements | Grammar