C# For Loop
When you already know how many times you want to loop, the for loop is usually the cleanest choice. It packs the starting value, the condition, and the counter update into a single line, so all the loop logic sits in one easy-to-read place.
The for Loop
A for loop has three parts separated by semicolons: the initializer runs once at the start, the condition is checked before every iteration, and the update runs at the end of each iteration. When the condition becomes false, the loop stops.
Basic for loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Number: " + i);
}- int i = 0 — the initializer, sets the starting value (runs once)
- i < 5 — the condition, keeps looping while this is true
- i++ — the update, adds 1 to i after each pass
The code above prints Number: 0 through Number: 4. Because the counter is declared inside the for statement, the variable i only exists within the loop, which keeps your code tidy.
Nested Loops
You can place one loop inside another. The inner loop runs completely for every single pass of the outer loop. This is handy for grids, tables, and multiplication charts.
A loop inside a loop
for (int i = 1; i <= 2; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.WriteLine("i = " + i + ", j = " + j);
}
}The outer loop runs twice, and for each of those passes the inner loop runs three times, giving six lines of output in total.
Exercise: C# For Loop
What are the three optional parts inside a C# for (...) header, separated by semicolons?