C# For Loop
The for
loop is used for iterating over a range of values or elements.
Syntax of for loop.
for (initialization; condition; iteration)
{
// code to be executed in each iteration
}
Here's a breakdown of the components.
Initialization:
Executed once before the loop begins. It is typically used to initialize a loop control variable.
Condition:
Checked before each iteration. If the condition is true
, the loop continues; otherwise, it exits.
Iteration:
Executed after each iteration of the loop. It is typically used to modify the loop control variable.
Example of for loop.
using System;
class Program
{
static void Main()
{
// Example: Print numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
In this example, int i = 1
initializes the loop control variable, i <= 5
is the condition, and i++
increments the variable i
in each iteration. The loop prints numbers from 1 to 5.
You can customize the for
loop based on your specific requirements, such as iterating over arrays, collections, or other sequences.