Say I ask you for a program that prints the numbers from 1 to 5. With what you know so far, you would write Console.WriteLine five times. It works. Now I ask for 1 to 1,000, and that plan stops sounding good.
That is what loops are for: a way to tell the computer “repeat this while some condition holds”. In this chapter you will learn three ways to do it in C#, two keywords that control the repetition from the inside, and how to avoid getting stuck in a loop that never ends. At the end we build a guess-the-number game.
while: repeat while the condition is true
The simplest loop is while. Create a new project with dotnet new console -n Loops, open Program.cs and write this:
int counter = 1;
while (counter <= 5)
{
Console.WriteLine($"Round {counter}");
counter = counter + 1;
}
Console.WriteLine("Done");
Round 1
Round 2
Round 3
Round 4
Round 5
Done
It reads almost like plain English: “while counter is less than or equal to 5, do what is inside the braces”. The condition in parentheses is the same kind of condition you used with if in the previous chapter. The difference is that if checks once, and while checks again every time the block finishes.
Step by step, this is how it runs:
counterstarts at 1.- C# checks
counter <= 5. It is true, so it enters the block, prints, and adds 1. - It goes back to the top and checks again. That repeats with 2, 3, 4 and 5.
- When
counterreaches 6, the condition is false. C# skips the block and moves on to what comes after it: it printsDone.
Each repetition is called an iteration. If the condition is false from the start, the block never runs at all.
A shorter way to add
Adding 1 to a variable is so common that C# has shortcuts. These three lines do the same thing (this is a fragment, not a full program):
counter = counter + 1;
counter += 1;
counter++;
+= adds whatever is on the right to the variable, so total += 5 adds 5 to total. There are also -=, *= and /=. ++ adds exactly 1, and -- subtracts 1. From here on you will see ++ a lot.
Watch out for the infinite loop
Delete the line that adds to the counter and run the program again:
int counter = 1;
while (counter <= 5)
{
Console.WriteLine($"Round {counter}");
}
The terminal fills up with Round 1 and does not stop. counter never changes, so the condition is always true and the loop never ends. This is called an infinite loop, and it happens to everyone.
To stop it, click on the terminal and press Ctrl+C. That works on both Windows and macOS.
When you write a loop, ask yourself two questions before you run it:
- What changes inside the loop that affects the condition?
- Does that change, at some point, make the condition false?
If you cannot answer both, that is where the problem is.
do-while: run first, ask later
Sometimes you need the block to run at least once. The typical case is asking the user for input: first you have to ask, and then you decide whether the answer is good or you need to ask again.
That is what do-while is for:
int number;
bool isValid;
do
{
Console.Write("Enter a number from 1 to 10: ");
isValid = int.TryParse(Console.ReadLine(), out number);
} while (!isValid || number < 1 || number > 10);
Console.WriteLine($"You picked {number}");
If you type abc, then 15, then 7, it looks like this:
Enter a number from 1 to 10: abc
Enter a number from 1 to 10: 15
Enter a number from 1 to 10: 7
You picked 7
The block runs once without checking anything, and the condition is checked at the end, in the while. If it is true, it repeats. Notice the semicolon after the while parentheses: in do-while it is required.
The condition says “repeat if it is not valid, or if it is less than 1, or if it is greater than 10”. As soon as you type a number that works, all three parts are false and the loop ends. int.TryParse is the same one you used in the previous chapter to read numbers without crashing the program.
One detail: Console.Write, without the Line, writes the text without moving to the next line. That is why what you type shows up next to the question.
for: when you know how many times
Look at the first while again. It has three pieces spread across three places: the variable that starts at 1, the condition, and the addition at the end. That pattern is so common it has its own loop, for, which puts all three pieces on a single line:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Round {i}");
}
Round 1
Round 2
Round 3
Round 4
Round 5
Inside the parentheses there are three parts separated by semicolons:
int i = 1: runs only once, before starting.i <= 5: the condition. It is checked before each round.i++: runs at the end of each round.
It does exactly the same as the while at the beginning. The advantage is that everything that controls the repetition sits in one place, and it is harder to forget the i++.
The name i is a very old habit in programming for a for counter. You can use another name, but you will see it in almost every piece of code you read.
With for you can print a multiplication table in four lines:
int table = 7;
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"{table} x {i} = {table * i}");
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Or add up every number from 1 to 100, which would take you a while by hand:
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
Console.WriteLine($"The sum from 1 to 100 is {sum}");
The sum from 1 to 100 is 5050
The three parts of a for accept other things too. This one counts down by twos:
for (int i = 10; i >= 0; i -= 2)
{
Console.WriteLine(i);
}
10
8
6
4
2
0
One more thing about i: since you declared it inside the for, it only exists inside the loop. If you try to use it after the closing brace, the compiler gives you an error.
while or for?
My rule is simple. If you know how many times you will repeat (ten rows, a hundred numbers), use for. If you repeat until something happens and you do not know when it will happen (until the user types something valid, until they guess), use while. And if what you are waiting for requires running the block first, use do-while.
break and continue: control from the inside
Two keywords change the course of a loop while it runs.
continue skips the rest of the current round and moves to the next one. This program prints only the odd numbers from 1 to 10:
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;
}
Console.WriteLine(i);
}
1
3
5
7
9
Remember that % gives you the remainder of a division. If i % 2 is 0, the number is even, and continue keeps Console.WriteLine from running in that round. In a for, the i++ still runs before the next round.
break leaves the loop completely, no matter what the condition says. This program finds the first multiple of 7 greater than 50:
int number = 51;
while (true)
{
if (number % 7 == 0)
{
break;
}
number++;
}
Console.WriteLine($"The first multiple of 7 greater than 50 is {number}");
The first multiple of 7 greater than 50 is 56
while (true) is an infinite loop on purpose: the condition is never false. What stops it is the break. It is a valid pattern and you will run into it, but use it with care: if the break is never reached, you are back to an infinite loop. When you can write the exit condition in the while itself, do that, because it is easier to understand.
Coming up: foreach
There is a fourth loop, foreach, which walks through a list of things one by one. To use it you first need to know what a list is, and that is exactly what the next chapter covers.
Mini-exercise: guess the number
Write a game where the computer picks a number from 1 to 100 and you try to guess it. To have the computer pick a random number, use this line:
int secret = Random.Shared.Next(1, 101);
Random.Shared.Next(1, 101) gives you a random number from 1 up to 100. The second number is not included, which is why it is 101 and not 100.
The game has to:
- Ask you for a number again and again until you guess it.
- Tell you “Higher.” or “Lower.” after each guess.
- If you type something that is not a number, warn you and ask again, without counting it as a guess.
- At the end, tell you how many guesses it took.
Try to write it without looking at the solution. Think first about which kind of loop fits.
Suggested solution
int secret = Random.Shared.Next(1, 101);
int attempts = 0;
int guess = 0;
Console.WriteLine("I picked a number from 1 to 100. Guess it.");
while (guess != secret)
{
Console.Write("Your guess: ");
if (!int.TryParse(Console.ReadLine(), out guess))
{
Console.WriteLine("That is not a number. Try again.");
continue;
}
attempts++;
if (guess < secret)
{
Console.WriteLine("Higher.");
}
else if (guess > secret)
{
Console.WriteLine("Lower.");
}
}
Console.WriteLine($"You got it in {attempts} guesses.");
Since the secret number is random, every run will be different. This is an example game where the secret was 43:
I picked a number from 1 to 100. Guess it.
Your guess: 50
Lower.
Your guess: 25
Higher.
Your guess: hello
That is not a number. Try again.
Your guess: 37
Higher.
Your guess: 43
You got it in 4 guesses.
I chose while because I do not know how many guesses you will need. The loop keeps going while guess is different from secret. guess starts at 0, which can never be the secret, so the loop always enters the first time. When TryParse fails, it leaves guess at 0, continue goes back to the top without adding to the counter, and the condition is still true.
If you want an extra challenge, limit the game to 7 guesses and, if you run out, show what the number was.
What you learned
whilerepeats while the condition is true, and might never run.do-whileruns the block at least once and checks the condition at the end.forputs the start, the condition and the step on one line. Use it when you know how many times to repeat.++,--,+=and-=are shortcuts for changing a variable.continueskips the rest of the round;breakleaves the loop.- An infinite loop happens when the condition never becomes false. Stop it with Ctrl+C.
In the next chapter we look at collections: how to keep many values in a single variable and walk through them with foreach.
Stuck on a loop?
If your loop will not stop, or stops too early, send me a DM on Instagram or ask in the Discord community. Paste your code and what showed up in the terminal, and we will look at it together.
