C# While Loop
C# While Loop
The while loop in C# is used to repeat a block of code as long as a condition is true. It is best used when you don’t know in advance how many times the loop will run.
Basic while Loop Syntax
Simple Example
Output:
While Loop with User Input
Infinite while Loop
⚠ Be careful—this loop never stops unless broken.
break Statement
Used to exit the loop.
continue Statement
Used to skip the current iteration.
While vs Do-While
| while | do-while |
|---|---|
| Condition checked first | Executes at least once |
| May not run at all | Always runs once |
Common Mistakes
❌ Forgetting to update loop variable
❌ Infinite loops
❌ Wrong condition
Summary
✔ while repeats while condition is true
✔ Best when iterations are unknown
✔ Use break to exit
✔ Use continue to skip
