//
In programming, there are often scenarios where you need to execute a block of code repeatedly until a certain condition is met. This is where loops come in handy. One type of loop that is particularly useful for such tasks is the while loop.
A while loop allows you to repeat a block of code as long as a specified condition remains true. Once the condition becomes false, the loop terminates, and the program continues with the next line of code after the loop.
The basic syntax of a while loop in C# is as follows:
while (condition)
{
// Code to be executed repeatedly
}
Here's how it works:
1. The condition is evaluated before each iteration of the loop.
2. If the condition is true, the code block inside the loop is executed.
3. After executing the code block, the condition is re-evaluated.
4. Steps 2 and 3 repeat until the condition becomes false.
It's important to ensure that the condition will eventually become false; otherwise, you'll end up with an infinite loop, which can cause your program to crash or hang indefinitely.
## Examples
Let's look at some practical examples to understand how `while` loops work in C#.
### Example 1: Counting Numbers
Suppose we want to print numbers from 1 to 5 using a `while` loop. Here's how you can do it:
```csharp
int number = 1;
while (number <= 5)
{
Console.WriteLine(number);
number++;
}
**Output:**
<OutputBlock>
{`1
2
3
4
5`}
</OutputBlock>
In this example:
- We initialize a variable `number` to 1.
- The condition `number <= 5` is checked before each iteration.
- If the condition is true, the current value of `number` is printed.
- Then, we increment `number` by 1 (`number++`).
- This process repeats until `number` becomes greater than 5.
### Example 2: Summing Numbers
Let's say we want to calculate the sum of numbers from 1 to 10 using a `while` loop. Here's how you can achieve that:
```csharp
int number = 1;
int sum = 0;
while (number <= 10)
{
sum += number;
number++;
}
Console.WriteLine("The sum is: " + sum);
Output:
The sum is: 55
In this example:
number to 1 and sum to 0.number <= 10 is checked before each iteration.number to sum.number by 1 (number++).number becomes greater than 10.Let's see what happens if we create an infinite loop:
int number = 1;
while (true)
{
Console.WriteLine(number);
number++;
}
**Output:**
<OutputBlock>
{`1
2
3
...`}
</OutputBlock>
In this example:
- The condition `true` is always true, so the loop will run indefinitely.
- This can cause your program to hang or crash if not handled properly.
<Tip variant="info">
Always be cautious when using conditions that might never become false. Ensure that there's a way to break out of the loop eventually.
</Tip>
## What's Next?
In this tutorial, we learned how to use `while` loops for repetitive tasks in C#. In the next section, we'll explore another type of loop called "Do-While Loops" and understand how they differ from `while` loops.
Stay tuned!