Certainly! The for
loop in C# is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. Here's a simple example of how the for
loop works:
Example
using System;
class Program
{
static void Main()
{
// Syntax: for (initialization; condition; update)
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
}
}
Explanation:
for
loop starts with the keyword for
.int i = 0;
initializes a variable i
to 0
.i < 5;
specifies the condition that needs to be true for the loop to continue. As long as i
is less than 5
, the loop will continue.i++
increments i
by 1
after each iteration.{}
. In this example, it prints "Iteration: " followed by the current value of i
.i
is incremented by 1
, and the condition is checked again. The loop continues until the condition becomes false (i.e., i
is no longer less than 5
).When you run this program, it will output:
OutPut
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
This demonstrates that the loop executes five times, with i
ranging from 0
to 4
, and prints the value of i
in each iteration.