C# - For loop

In C#, a "for loop" is a control structure that allows you to repeatedly execute a block of code for a specific number of iterations. It's a structured way to perform tasks such as iterating over arrays, processing data, or performing repetitive operations. The syntax of the for loop is as follows:


for (initialization; condition; iteration)
{
    // Code to be executed
}

Here's the data flow diagram of for loop:

Here's an example of using a for loop to iterate from 1 to 5 and display the values:


using System;

class Program
{
    static void Main()
    {
        // Using a for loop to count from 1 to 5
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine("Iteration " + i);
        }
    }
}

Explanation of the code:

  • In this example, we use a "for loop" to count from 1 to 5.
  • The loop consists of three parts:
    • Initialization (int i = 1;): We initialize a loop control variable i to 1, which sets the starting point for our loop.
    • Condition (i <= 5;): The loop continues as long as the condition i is less than or equal to 5.
    • Iteration (i++): After each iteration, the loop control variable i is incremented by 1.
  • Inside the loop, we use Console.WriteLine to display the current iteration.

Expected Output:


Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

In this output, you can see that the for loop executes the code block five times, counting from 1 to 5. It's a fundamental construct in C# for performing repetitive tasks with a clear structure and control over the number of iterations.