How to Use While Loop in C# - Simple Guide
In C#, a
while loop repeats a block of code as long as a specified condition is true. You write it using while (condition) { /* code */ }, where the condition is checked before each loop iteration.Syntax
The while loop syntax in C# consists of the keyword while, followed by a condition in parentheses, and a block of code inside curly braces. The loop runs repeatedly as long as the condition is true.
- while: starts the loop
- (condition): a boolean expression checked before each loop
- { ... }: code to repeat
csharp
while (condition) { // code to execute repeatedly }
Example
This example shows a while loop that counts from 1 to 5 and prints each number. The loop stops when the count becomes greater than 5.
csharp
using System; class Program { static void Main() { int count = 1; while (count <= 5) { Console.WriteLine(count); count++; } } }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes with while loops include:
- Forgetting to update the condition variable inside the loop, causing an infinite loop.
- Using a condition that is always false, so the loop never runs.
- Modifying the loop variable incorrectly, leading to unexpected behavior.
Always ensure the condition will eventually become false to stop the loop.
csharp
/* Wrong: Infinite loop because count is never changed */ int count = 1; while (count <= 5) { Console.WriteLine(count); // Missing count++ here } /* Correct: Increment count to avoid infinite loop */ int count = 1; while (count <= 5) { Console.WriteLine(count); count++; }
Quick Reference
Remember these tips when using while loops:
- Check the condition before each iteration.
- Update variables inside the loop to avoid infinite loops.
- Use
whilewhen the number of iterations is not known in advance.
Key Takeaways
Use
while loops to repeat code while a condition is true.Always update the condition variable inside the loop to prevent infinite loops.
The condition is checked before each loop iteration, so the loop may not run at all if false initially.
Use
while loops when you don't know how many times you need to repeat beforehand.