Skip to content
Codewilds

Lesson 6 of 34 · Fundamentals

C# Loops: for, while, do-while and foreach

medium20 XP3 min readFree lesson

Computers are brilliant at doing the same thing many times without getting bored. Loops are how you ask them to. C# has four loops, and choosing the right one makes your code shorter and clearer.

The for loop

Use for when you know how many times to repeat:

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine($"Round {i}");
}
// Round 1, Round 2, Round 3

The header has three parts separated by semicolons: the start (int i = 1), the condition checked before every round (i <= 3), and the step run after every round (i++). Counting down or in bigger steps works too: for (int i = 10; i > 0; i -= 2).

while and do-while

while repeats as long as a condition is true — ideal when you do not know the number of rounds in advance:

int gold = 1;
int days = 0;
while (gold < 100)
{
    gold *= 2;
    days++;
}
Console.WriteLine(days);   // 7 (1 → 128)

do/while checks the condition after the body, so it always runs at least once:

int tries = 0;
do
{
    tries++;
} while (tries < 0);
Console.WriteLine(tries);   // 1

If the condition never becomes false, the loop never ends. In these lessons a program that runs too long is stopped automatically — check that something inside the loop moves it towards the exit.

foreach

foreach visits every element of a collection, one by one. A string is a collection of chars:

int spaces = 0;
foreach (char c in "fire and ice")
{
    if (c == ' ')
    {
        spaces++;
    }
}
Console.WriteLine(spaces);   // 2

You will use foreach constantly with arrays and lists in Chapter 3.

break and continue

break leaves the loop immediately; continue skips to the next round:

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;   // skip even numbers
    if (i > 7) break;           // stop after 7
    Console.Write(i + " ");     // 1 3 5 7
}

Building results in a loop

A loop often accumulates a result in a variable declared before the loop:

string stars = "";
for (int i = 0; i < 5; i++)
{
    stars += "*";
}
Console.WriteLine(stars);   // *****

For long texts prefer StringBuilder (from System.Text), which avoids creating a new string on every +=.

Common mistakes

  • Off-by-one errors: for (int i = 0; i <= 5; i++) runs six times. Starting at 0 usually pairs with <, starting at 1 with <=.
  • Declaring the accumulator inside the loop: it is reset in every round.
  • Overflow: int tops out at about 2.1 billion, and 13! is already bigger. Use long for big products.

Assignment

Complete four methods in Program:

  1. SumTo(n) returns 1 + 2 + … + n, or 0 when n is 0 or negative. SumTo(4) is 10.
  2. CountVowels(text) counts the vowels a e i o u, upper or lower case. CountVowels("Sharpforge Citadel") is 6.
  3. Factorial(n) returns n! as a long (1 × 2 × … × n); Factorial(0) is 1 and Factorial(20) is 2432902008176640000.
  4. Countdown(from) returns the numbers from from down to 1 followed by Liftoff!, separated by spaces: Countdown(3) is "3 2 1 Liftoff!" and Countdown(0) is "Liftoff!".

Loops in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Press Run to execute your code, or Submit to check it against the tests.