.NET Academy

Loops: for, while and foreach

Repeat work with for, while, do-while and foreach — and control loops with break and continue.

12 min read

You will learn

  • Choose between for, while, do-while and foreach
  • Accumulate results in a loop
  • Use break and continue
  • Avoid infinite loops and off-by-one errors

Doing things more than once

Printing 1 to 100, processing every order, retrying a request until it succeeds — computers are good at repetition. C# has four loops; each fits a different situation.

for: when you know how many times

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Lap {i}");
}

The header has three parts, separated by semicolons:

  1. Initializer — int i = 1 runs once, before the loop starts.
  2. Condition — i <= 5 is checked before every iteration; the loop stops when it's false.
  3. Iterator — i++ runs after every iteration.

Counting down or in steps works the same way: for (int i = 10; i > 0; i -= 2).

while: when you don't know how many times

while repeats as long as a condition stays true:

int balance = 1000;
int years = 0;
while (balance < 2000)
{
    balance += balance * 7 / 100;   // 7% interest per year
    years++;
}
Console.WriteLine($"Doubled after {years} years");

If the condition is false at the start, the body never runs.

do-while: at least once

do-while checks the condition after the body, so it always runs at least once — handy for "try, then check" logic:

int number = 0, digits = 0;
do
{
    digits++;
    number /= 10;
} while (number > 0);
// digits is 1, even though number started at 0

foreach: every item in a collection

string[] fruits = { "apple", "banana", "cherry" };
 
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit.ToUpper());
}

No index, no length, no off-by-one mistakes. Use foreach whenever you simply need each item — you'll use it with arrays, lists, dictionaries and query results.

Accumulating results

A very common pattern: start with an empty result, update it in every iteration.

int sum = 0;
for (int i = 1; i <= 100; i++)
{
    sum += i;
}
Console.WriteLine(sum);   // 5050

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this iteration and moves to the next.
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;   // skip even numbers
    if (i > 7) break;           // stop entirely after 7
    Console.Write($"{i} ");     // 1 3 5 7
}

Classic mistakes

Infinite loops

If the condition never becomes false, the loop never ends. In while (i < 10) { Console.WriteLine(i); } nothing changes i. (In this course's editor, programs are stopped after 8 seconds.)

Off-by-one errors

for (int i = 0; i <= 5; i++) runs six times, not five. With arrays of length n, valid indexes are 0 to n - 1, so loop with i < n.

Nested loops

A loop inside a loop runs its inner body for every outer iteration:

Program.cs
Loading editor…

C# runtime not loaded

FizzBuzz

The most famous beginner exercise: print 1 to 15, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both. Try writing it yourself here:

Program.cs
Loading editor…

C# runtime not loaded

Key takeaways

  • for — a known number of iterations; while — repeat while a condition holds; do-while — at least once; foreach — every item in a collection.
  • Accumulate results in a variable declared before the loop.
  • break exits a loop, continue skips to the next iteration.
  • Watch for infinite loops and off-by-one boundaries.

Exercise

SumTo(n) adds 1 + 2 + … + n (0 for n ≤ 0). Countdown(3) returns "3 2 1 Liftoff!". CountDigits returns how many digits a number has — 0 has one digit, and the sign of negative numbers doesn't count.

Program.cs
Loading editor…

C# runtime not loaded

Hint 1

SumTo: start with int sum = 0, then for (int i = 1; i <= n; i++) sum += i;

Hint 2

Countdown: loop downward with i-- and append $"{i} " to a string, then add "Liftoff!" at the end.

Hint 3

CountDigits: take the absolute value, then divide by 10 in a do-while loop until it reaches 0 — do-while guarantees 0 counts as one digit.

Show solution
int SumTo(int n)
{
    int sum = 0;
    for (int i = 1; i <= n; i++)
    {
        sum += i;
    }
    return sum;
}

string Countdown(int from)
{
    string result = "";
    for (int i = from; i >= 1; i--)
    {
        result += $"{i} ";
    }
    return result + "Liftoff!";
}

int CountDigits(int number)
{
    number = Math.Abs(number);
    int digits = 0;
    do
    {
        digits++;
        number /= 10;
    } while (number > 0);
    return digits;
}

Console.WriteLine(SumTo(10));
Console.WriteLine(Countdown(3));
Console.WriteLine(CountDigits(12345));

Quiz

4 questions · 3 correct to pass
  1. 1.How many times does `for (int i = 0; i < 5; i++)` run its body?

  2. 2.What's the difference between while and do-while?

  3. 3.What does `continue` do inside a loop?

  4. 4.Which loop is the natural choice to visit every item in a collection?

To complete this lesson

  • ○ Solve the exercise
  • ○ Pass the quiz (3/4 correct)