C# Tutorial · Control Flow · Lesson 9 of 22

C# Loops

for, while, do-while, foreach, break and continue.

Loops

Example 1
for (int i = 1; i <= 3; i++)
    Console.Write(i + " ");
Console.WriteLine();

int n = 1;
while (n < 100) n *= 3;
Console.WriteLine(n);

int tries = 0;
do { tries++; } while (tries < 0);
Console.WriteLine($"ran {tries} time(s)");

string[] langs = { "C#", "F#", "VB" };
foreach (var lang in langs)
    Console.WriteLine($"{lang} runs on .NET");

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;
    if (i > 7) break;
    Console.Write(i + " ");
}
Console.WriteLine();

Output

1 2 3 
243
ran 1 time(s)
C# runs on .NET
F# runs on .NET
VB runs on .NET
1 3 5 7 

Run this on your computer — see “Get Started” for setup.

foreach works with arrays, lists and anything that implements IEnumerable<T> — it's the loop you'll use most. break exits a loop; continue skips to the next iteration.

Test yourself

Which loop is designed for iterating over a collection?

  1. for
  2. while
  3. foreach
  4. do-while
Show answer

Answer: foreach