The while
and do-while
loops are control structures in C# that allow the execution of a block of code to be repeated while a specific condition is met.
Unlike the for
loop, which is used when the exact number of iterations is known, the while
and do-while
loops are ideal when the number of iterations is unknown (because it depends on an exit condition).
If you want to learn more about Loops
check the Introduction to Programming Course read more
WHILE Loop
The while
loop repeats a block of code while a given condition is true
. The basic syntax of a while
loop in C# is as follows:
while (condition)
{
// Code to execute while the condition is true
}
The block of code executes repeatedly as long as the specified condition is true
. It is important to be careful with the condition to avoid infinite loops.
Let’s see it with an example,
int counter = 0;
while (counter < 5)
{
Console.WriteLine(counter);
counter++;
}
In this example, the while
loop will print the numbers from 0 to 4, as the condition counter < 5
evaluates to true
during the first five iterations.
DO-WHILE Loop
The do-while
loop is similar to the while
loop, but it guarantees that the block of code will execute at least once, even if the condition is false
from the start. The basic syntax is as follows:
do
{
// Code to execute at least once
} while (condition);
The block of code executes first and then checks the condition. If the condition is true
, the block executes again; if it is false
, the loop ends.
Let’s see it with an example
int counter = 0;
do
{
Console.WriteLine(counter);
counter++;
} while (counter < 5);
This do-while
loop will produce the same output as the while
loop from the previous example.
Differences between While and Do-While
- The
while
loop checks the condition before each iteration, while thedo-while
loop checks the condition after each iteration. - The
do-while
loop guarantees at least one execution of the block of code, while thewhile
loop may not execute the block if the condition isfalse
from the start.
Practical Examples
Count to 10
In this example, a while
loop is used to count from 1 to 10 and print each number.
int counter = 1;
while (counter <= 10)
{
Console.WriteLine(counter);
counter++; // Increment the counter by 1
}
This while
loop executes while the value of counter
is less than or equal to 10. In each iteration, the current value of counter
is printed and then incremented by 1.
Sum positive numbers entered by the user
In this example, a while
loop is used to sum positive numbers entered by the user until a negative number is entered.
int sum = 0;
int number;
Console.WriteLine("Enter a positive number (a negative number to finish): ");
number = int.Parse(Console.ReadLine());
while (number >= 0)
{
sum += number; // Adds the entered number to the 'sum' variable
Console.WriteLine("Enter another positive number (a negative number to finish): ");
number = int.Parse(Console.ReadLine());
}
Console.WriteLine($"The total sum of positive numbers is: {sum}");
This while
loop executes while the user enters positive numbers. Each number is added to the sum
variable. The loop ends when a negative number is entered.
Search for a number in a list
In this example, a while
loop is used to search for a specific number in a list of numbers.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int searched = 7;
int index = 0;
bool found = false;
while (index < numbers.Count && !found)
{
if (numbers[index] == searched)
{
found = true; // Marks that the number has been found
Console.WriteLine($"Number {searched} found at position {index}");
}
index++; // Increment the index
}
if (!found)
{
Console.WriteLine($"Number {searched} not found in the list");
}
This while
loop executes while the searched number has not been found and the index is within the range of the list.
If the number is found, it is marked as found and its position is printed. If the loop ends without finding the number, it indicates that it was not found in the list.
User input validation
In this example, a do-while loop is used to ask the user to enter “y” or “n” to confirm if they want to continue.
string response;
do
{
Console.WriteLine("Do you want to continue? (y/n): ");
response = Console.ReadLine().ToLower();
} while (response != "y" && response != "n");
Console.WriteLine("Program finished.");
This do-while
loop prompts the user to enter “y” or “n” to confirm if they want to continue. The block of code executes at least once and then repeats while the user does not enter a valid response.
These examples are intended to show how to use the While loop. It does not mean that it is the best way to solve the problems they address.