typestar

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

  1. for drives an index; foreach visits every element without one.
  2. continue skips one iteration, break leaves the loop entirely.
  3. while loops on a condition the body must eventually change.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Flow control, step 10 of 29 in Language basics.

← Previous Next →

Loops in other languages