for Loop (C#)

A for loop in C# repeats a block of code a set number of times using a counter. It packs the start value, the continue condition, and the step into one line.

C#

The three parts inside the parentheses are: an initializer (often int i = 0), a condition that keeps the loop running while true, and an update that usually increments the counter.

Use a for loop when you know how many times to repeat or need the index; use foreach to simply walk through every item in a collection.

Syntax

for (init; condition; update) { ... }

Examples

C#

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(i);
}

Output:

0
1
2

Learn it in a lesson

See also

Back to the Dictionary