C# for loop

A for loop in C# is a control flow statement that allows you to repeatedly execute a block of code a specific number of times. It is commonly used when the number of iterations is known before entering the loop. The for loop consists of three main components:

1. Initialization: This part sets up a counter variable or any other variables before the loop begins. It is executed once at the start of the loop.

2. Condition: A boolean expression that is evaluated before each iteration of the loop. The loop continues executing as long as this condition evaluates to true. Once it becomes false, the loop terminates.

3. Increment/Decrement: This statement is executed after each iteration of the loop, and it modifies the counter variable. Usually, the counter is incremented or decremented.

Syntax:


for (initialization; condition; increment/decrement)
{
    // Code block to execute for each iteration
}

Example: Print the value from 0 to 4


using System;

class ProgramExample
{
    static void Main()
    {
        for (int i = 0; i < 5; i++) // Initialization: i=0, Condition: i<5, Increment: i++
        {
            Console.WriteLine(i); // Prints the current value of i
        }
    }
}

Output:

0
1
2
3
4

Explanation:

  • Initialization: int i = 0 initializes the loop variable i to 0 before the loop starts.
  • Condition: i < 5 checks whether i is less than 5. If this condition is true, the loop executes; if false, the loop exits.
  • Increment: i++ increases the value of i by 1 after each iteration.

Example: Print the table of 2 through for loop


using System;

class ProgramExample
{
    static void Main()
    {
        for (int i = 2; i <=20; i=i+2) 
        {
            Console.WriteLine(i); // Prints the current value of i
        }
    }
}

Output:

2
4
6
8
10
12
14
16
18
20