C# For Loop

C# for loop is used to repeat a set of statements until a given condition is evaluated to False.

Syntax of C# For

</>
Copy
 for(initialization; boolean_expression; increment_decrement_update){
     /* statement(s) */
 }

where

  • for is the keyword.
  • initialization can have variable declarations which will be used inside for loop.
  • boolean_expression can be a complex condition that evaluates to a boolean value: True or False.
  • increment_decrement_update can have statements to increment, decrement or update the variables that control the iteration of loop execution.
  • statement(s) are a set of statements that are meant to be executed in loop until the boolean_expression evaluates to false.

Example 1 – C# For Loop

Following is a basic example of C# for loop. We print numbers from 3 to 7.

Program.cs

</>
Copy
using System;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            for(int i=3;i<=7;i++) {
                Console.WriteLine(i);
            }
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
3
4
5
6
7

How C# for loop works?

Let us see how the for loop worked in the above example.

The intialization is int i=3. Meaning, we declared a variable i with an initial value of 3. We can access this variable i inside the for loop, which means at boolean_expression, increment_decrement_update and statement(s).

The boolean expression is i<=7. Therefore, we are going to come out of the for loop when this condition returns False.

The update expression is i++.  So, during each iteration, i is incremented by 1.