The while
and do-while
loops are control structures in C# that allow you to repeat the execution of a block of code as long as 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 or depends on an exit condition.
If you want to learn more
consult the Introduction to Programming Course read more ⯈
WHILE Loop
The while
loop repeats a block of code as long as 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 is executed 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 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
is evaluated as 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 is executed at least once, even if the condition is false
from the beginning. The basic syntax is as follows:
do
{
// Code to execute at least once
} while (condition);
The block of code is executed first and then the condition is checked. If the condition is true
, the block is executed again; if it is false
, the loop ends.
Let’s see 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 in 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 beginning.
Practical Examples
Counting up 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 counter by 1
}
This while
loop runs as long as the value of counter
is less than or equal to 10. In each iteration, it prints the current value of counter
and then increments it by 1.
Adding positive numbers entered by the user
In this example, a while
loop is used to add positive numbers entered by the user until a negative number is entered.
int sum = 0;
int number;
Console.WriteLine("Enter a positive number (negative number to end): ");
number = int.Parse(Console.ReadLine());
while (number >= 0)
{
sum += number; // Adds the entered number to the 'sum' variable
Console.WriteLine("Enter another positive number (negative number to end): ");
number = int.Parse(Console.ReadLine());
}
Console.WriteLine($"The total sum of the positive numbers is: {sum}");
This while
loop runs as long as the user enters positive numbers. Each number is added to the sum
variable. The loop ends when a negative number is entered.
Searching 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 runs as long as 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 is indicated that it was not found in the list.
User Input Validation
In this example, a do-while loop is used to prompt 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 is executed at least once and then repeats as long as the user does not enter a valid response.
These examples are intended to show how to use the While loop. It doesn’t mean it’s the best way to solve the problem they address