C# While Loop - Real-Life Examples
Real-Life Examples
A while loop repeats a block of code as long as a condition is true.
This chapter shows how you can use it in small programs that solve everyday problems.
Countdown
This program counts down from 5, like before a race starts, and then prints "Go!":
Example
int countdown = 5;
while (countdown > 0)
{
Console.WriteLine(countdown);
countdown--;
}
Console.WriteLine("Go!");
countdown-- makes the number 1 smaller each time. When countdown reaches 0, the condition is false, and the loop stops.
Add Up Numbers
A loop can keep a running total. This program adds the numbers 1 to 5, one at a time:
Example
int number = 1;
int total = 0;
while (number <= 5)
{
total = total + number;
Console.WriteLine("Add " + number + ": the total is " + total);
number++;
}
Each time the loop runs, the current number is added to total. At the end, total is 15 (1 + 2 + 3 + 4 + 5).
Loop with if...else
You can use an if...else statement inside a loop. In this game, there are 5 levels, and level 5 is the final level:
Example
int level = 1;
while (level <= 5)
{
if (level < 5)
{
Console.WriteLine("Level " + level);
}
else
{
Console.WriteLine("Level " + level + ": Final level!");
}
level++;
}
For levels 1 to 4, the if block runs. For level 5, the else block runs and prints "Final level!".
Play Until You Win
A while loop is a good choice when you do not know how many times the code should run.
In this game, the player gets 30 points each round, and wins with 100 points or more. How many rounds does it take?
Example
int points = 0;
int round = 0;
while (points < 100)
{
round++;
points = points + 30;
Console.WriteLine("Round " + round + ": " + points + " points");
}
Console.WriteLine("You won after " + round + " rounds!");
The loop runs as long as points is less than 100. You do not need to know the number of rounds before the loop starts: the loop finds it for you.