Loops in C#
for counts, foreach walks, while runs until told otherwise.
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"for: {i}");
}
var langs = new[] { "C#", "F#", "VB" };
foreach (var lang in langs)
{
if (lang == "VB") continue;
Console.WriteLine($"foreach: {lang}");
}
int n = 1;
while (n < 100)
{
n *= 3;
if (n > 50) break;
}
Console.WriteLine($"stopped at {n}");
How it works
fordrives an index;foreachvisits every element without one.continueskips one iteration,breakleaves the loop entirely.whileloops on a condition the body must eventually change.
Keywords and builtins used here
breakcontinueforforeachifinintnewvarwhile
The run, in numbers
- Lines
- 19
- Characters to type
- 300
- Tokens
- 93
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 3 of 3 in Flow control, step 10 of 29 in Language basics.