C# For Loop
Syntax
for(initialization; condition; increment/decrement)
{
// code to be executed
}
Example
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Output
0
1
2
3
4
Explanation
The for
loop is used in C# to repeatedly execute a block of code based on a condition. The for
loop is initialized with a counter variable and an expression that evaluates to a Boolean value. If the expression is true
, the loop body is executed. After the loop body is executed, the counter variable is incremented or decremented.
In the example above, the loop is initialized with the counter variable i
. The loop body executes as long as the value of i
is less than 5. After each iteration of the loop body, the value of i
is incremented by 1. When the value of i
is equal to 5, the loop terminates.
Use
The for
loop is very common in C# programs and is used to iterate through arrays or loops. It can also be used to repeat a block of code a fixed number of times. The for
loop is often used where the number of iterations is known in advance.
Important Points
- The
for
loop is used to repeatedly execute a block of code based on a condition. - The
for
loop is initialized with a counter variable and an expression that evaluates to a Boolean value. - The loop body is executed as long as the expression is
true
. - After the loop body is executed, the counter variable is incremented or decremented.
- The
for
loop is often used where the number of iterations is known in advance.
Summary
In C#, the for
loop is used to repeatedly execute a block of code based on a condition. The for
loop is initialized with a counter variable and an expression that evaluates to a Boolean value. It is often used to iterate through arrays or loops and can be used to repeat a block of code a fixed number of times. It is an important construct in any C# program.