Lesson 6 of 34 · Fundamentals
C# Loops: for, while, do-while and foreach
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:
inttops out at about 2.1 billion, and13!is already bigger. Uselongfor big products.
Assignment
Complete four methods in Program:
SumTo(n)returns1 + 2 + … + n, or0whennis 0 or negative.SumTo(4)is10.CountVowels(text)counts the vowelsa e i o u, upper or lower case.CountVowels("Sharpforge Citadel")is6.Factorial(n)returnsn!as along(1 × 2 × … × n);Factorial(0)is1andFactorial(20)is2432902008176640000.Countdown(from)returns the numbers fromfromdown to 1 followed byLiftoff!, separated by spaces:Countdown(3)is"3 2 1 Liftoff!"andCountdown(0)is"Liftoff!".
Loops in other languages
- JavaScript Loops: for and while · JavaScript
- Python Loops: for, range() and while · Python
- Go for Loops: The Only Loop You Need · Go
- Java Loops: for, while and do-while · Java
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .