C#C#
BeginnerLesson 4 of 16

Loops: for, foreach, while – C#

Repeating tasks – over numbers and collections.

The for loop has a start value, a condition and a step statement. With foreach you iterate over any collection without managing an index.

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

foreach (string frucht in new[] { "Apple", "Pear", "Cherry" })
{
    Console.WriteLine(frucht.ToUpper());
}

foreach (int i in Enumerable.Range(1, 3))
    Console.Write(i + " ");   // 1 2 3

while checks the condition before each iteration, do ... while only afterwards (at least one iteration). break ends the loop, continue jumps to the next iteration.

int n = 0;
while (true)
{
    n++;
    if (n % 2 == 0) continue;
    if (n > 7) break;
    Console.Write(n + " ");   // 1 3 5 7
}
Console.WriteLine();

int versuch = 0;
do
{
    versuch++;
} while (versuch < 3);
Console.WriteLine(versuch);   // 3
WarningInside a foreach loop you must not modify the list being iterated (Add/Remove) – that throws an InvalidOperationException. Iterate over a copy (.ToList()) or use a for loop that runs backwards.