Codiqo

Learn C# · lesson 20 of 61 · about 8 minutes

foreach, break and continue

Explore the dark tunnel tile by tile: visit every character with foreach, skip empty tiles with continue, and stop at a locked gate with break.

What you'll learn

  • Loop over an array or string with foreach
  • Skip with continue
  • Stop with break

The dark tunnel

Last unit, explore found a dark tunnel. It's typed as a line of tiles, like ..G.X.G: a . is empty, a G is a gold coin to pick up, and an X is a locked gate where the hero has to turn back. The program walks the tiles in order, skips the empty ones, picks up the gold, and stops at the first gate.

Every item

foreach (var item in items) visits each item in order, with no index to manage. It works on arrays, lists and strings (one char at a time). continue jumps to the next item; break leaves the loop entirely. var lets C# work out the type.

Skipping and stopping

int[] scores = { 7, -1, 12, 0, 9 };
foreach (int s in scores)
{
    if (s < 0) continue;
    if (s == 0) break;
    Console.Write($"{s} ");
}
Console.WriteLine();

int vowels = 0;
foreach (char ch in "foreach")
{
    if ("aeiou".Contains(ch)) vowels++;
}
Console.WriteLine($"{vowels} vowels");

Output

7 12
3 vowels

Exploring the tunnel

string tunnel = "..G.GX.G";
int gold = 0;
foreach (char tile in tunnel)
{
    if (tile == 'X')
    {
        Console.WriteLine("A locked gate. You turn back.");
        break;
    }
    if (tile != 'G')
    {
        continue;
    }
    gold++;
    Console.WriteLine($"Found gold! Gold: {gold}");
}
Console.WriteLine($"Tunnel done with {gold} gold.");

Output

Found gold! Gold: 1
Found gold! Gold: 2
A locked gate. You turn back.
Tunnel done with 2 gold.

Tip

The loop variable in a foreach is read-only: tile = '.' doesn't compile. To build something new from the items, add them to another variable instead.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.