C# for Loop: Usage & Examples

The basic syntax of a for loop statement in C# is as follows:

for (initialization; condition; increment)
{
    // 循环体
}

Among them, the initialization expression is used to set the initial value of the loop variable, the condition expression determines the termination condition of the loop, and the increment expression is used to update the loop variable.

For example, here is a simple example of a for loop that prints numbers 1 to 5:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

In the example above, the initialization expression initializes the variable i as 1, the condition expression checks if i is less than or equal to 5, and the increment expression increases i by 1. The Console.WriteLine(i) statement in the loop body will print the value of the variable i.

You can also use the break statement in a for loop to prematurely exit the loop, or the continue statement to skip the current iteration.

bannerAds