Поделиться через


for (C# Reference)

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.

Example

In the following example, the value of int i is written to the console and i is incremented every time through the loop by 1.


class ForLoopTest 
{
    static void Main() 
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
        }
    }
}
/*
Output:
1
2
3
4
5
*/

The for statement executes the enclosed statement or statements repeatedly as follows:

  • First, the initial value of the variable i is evaluated.

  • Then, as long as the value of i is less than or equal to 5, the condition evaluates to true, the Console.WriteLine statement is executed and i is reevaluated.

  • When i is greater than 5, the condition becomes false and control is transferred outside the loop.

Because the test of a conditional expression occurs before the execution of the loop, a for statement executes zero or more times.

You can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword. You also can exit the loop by using a goto, return, or throw statement.

All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop.

for (; ; )
{
    // ...
}

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Keywords

foreach, in (C# Reference)

for Statement (C++)

Iteration Statements (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference