How is the for statement used in C#?

In C#, the for loop is a commonly used looping structure that repeats a specific section of code a certain number of times.

The basic syntax structure of a for loop is as follows:

for (初始条件; 循环条件; 循环迭代)
{
    // 循环体
}
  1. Initial condition: a statement executed before the loop starts, typically used to initialize the loop variable.
  2. Loop condition: a condition that is evaluated before each iteration, the loop body is executed when the condition is true, and the loop is exited when the condition is false.
  3. Iterative looping: statements executed after each loop iteration, typically used to update the loop variable.

For example, the following example uses a for loop to print numbers 1 to 10:

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

Within the loop, any code logic can be executed. The scope of the loop variable is limited to within the loop, so the loop variable cannot be accessed outside of the loop.

It is important to note that the loop condition must be able to eventually become false, or else it will result in an infinite loop. To prevent an infinite loop, you can use a break statement or other conditional control statements to exit the loop prematurely.

bannerAds