Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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 of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:

for (;;) {
   ...
}

Example

// statements_for.cs
// 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 | C. Grammar

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft