Introduction
Loops are one of the most fundamental programming concepts in C#. They allow you to execute a block of code repeatedly as long as a specified condition is true.
Without loops, you would have to write the same code multiple times, making programs longer, harder to maintain, and more error-prone.
C# provides several looping statements:
whiledo...whileforforeach
This article focuses exclusively on the while and do...while loops, explaining their syntax, behavior, differences, best practices, common pitfalls, and practical examples.
What Is a while Loop?
A while loop repeatedly executes a block of code as long as a condition evaluates to true.
The condition is checked before each iteration. If the condition is false initially, the loop body will never execute.
Syntax
while (condition)
{
// Code to execute
}
How It Works
- Evaluate the condition.
- If the condition is
true, execute the loop body. - Return to step 1.
- Stop when the condition becomes
false.
Flow of a while Loop
Start
│
▼
Check Condition
│
┌─┴──────────┐
│ │
True False
│ │
▼ ▼
Execute End
Body
│
└────────────┘
Example 1: Printing Numbers
int number = 1;
while (number <= 5)
{
Console.WriteLine(number);
number++;
}
Output
1
2
3
4
5
Explanation
- The loop starts with
number = 1. - Since
1 <= 5, the loop executes. numberis incremented.- The loop continues until
numberbecomes6.
Example 2: Countdown Timer
int countdown = 5;
while (countdown > 0)
{
Console.WriteLine(countdown);
countdown--;
}
Console.WriteLine("Done");
Output
5
4
3
2
1
Done
Example 3: Reading User Input
string input = "";
while (input != "exit")
{
Console.Write("Enter a command: ");
input = Console.ReadLine();
Console.WriteLine($"You entered: {input}");
}
This loop continues until the user types:
exit
Example 4: Calculating a Sum
int i = 1;
int sum = 0;
while (i <= 10)
{
sum += i;
i++;
}
Console.WriteLine(sum);
Output
55
Example 5: Processing an Array
string[] fruits =
{
"Apple",
"Orange",
"Banana",
"Mango"
};
int index = 0;
while (index < fruits.Length)
{
Console.WriteLine(fruits[index]);
index++;
}
Output:
Apple
Orange
Banana
Mango
Infinite while Loop
If the condition never becomes false, the loop never ends.
while (true)
{
Console.WriteLine("Running...");
}
This creates an infinite loop.
To stop it, use break.
while (true)
{
Console.Write("Enter q to quit: ");
string input = Console.ReadLine();
if (input == "q")
break;
}
Common Mistake: Forgetting to Update the Loop Variable
Incorrect:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
}
Since i never changes, the condition remains true forever.
Correct:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
Nested while Loops
A while loop can contain another while loop.
int row = 1;
while (row <= 3)
{
int column = 1;
while (column <= 4)
{
Console.Write("* ");
column++;
}
Console.WriteLine();
row++;
}
Output:
* * * *
* * * *
* * * *
What Is a do...while Loop?
A do...while loop is similar to a while loop, but it checks the condition after executing the loop body.
Therefore, the body always executes at least once.
Syntax
do
{
// Code
}
while (condition);
Notice the semicolon after the condition.
Flow of a do...while Loop
Start
│
▼
Execute Body
│
▼
Check Condition
│
┌─┴─────────┐
│ │
True False
│ │
▼ ▼
Repeat End
Example 1: Basic do...while
int number = 1;
do
{
Console.WriteLine(number);
number++;
}
while (number <= 5);
Output
1
2
3
4
5
Example 2: Condition Initially False
int number = 10;
do
{
Console.WriteLine(number);
}
while (number < 5);
Output
10
The body executes once before checking the condition.
Equivalent while Loop
int number = 10;
while (number < 5)
{
Console.WriteLine(number);
}
Output
(No output)
This demonstrates the biggest difference between the two loops.
Example 3: Menu Program
int choice;
do
{
Console.WriteLine("1. View");
Console.WriteLine("2. Save");
Console.WriteLine("3. Exit");
Console.Write("Choose: ");
choice = Convert.ToInt32(Console.ReadLine());
}
while (choice != 3);
Console.WriteLine("Program closed.");
Example 4: Input Validation
int age;
do
{
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
} while (age < 0);
Console.WriteLine($"Age: {age}");
This guarantees that the user is prompted at least once.
Example 5: Guessing Game
int secret = 8;
int guess;
do
{
Console.Write("Guess the number: ");
guess = Convert.ToInt32(Console.ReadLine());
} while (guess != secret);
Console.WriteLine("Correct!");
while vs do...while
| Feature | while | do...while |
|---|---|---|
| Condition checked | Before execution | After execution |
| Executes at least once | No | Yes |
| Semicolon required | No | Yes |
| Typical use | Unknown number of iterations | Menus and input validation |
Using break
The break statement immediately exits the loop.
int number = 1;
while (true)
{
if (number > 5)
break;
Console.WriteLine(number);
number++;
}
Output
1
2
3
4
5
Using continue
continue skips the remaining statements in the current iteration and moves to the next iteration.
int number = 0;
while (number < 10)
{
number++;
if (number % 2 == 0)
continue;
Console.WriteLine(number);
}
Output
1
3
5
7
9
Multiple Conditions
int x = 1;
while (x >= 1 && x <= 10)
{
Console.WriteLine(x);
x++;
}
Conditions can use:
&&||!- Comparison operators (
<,>,<=,>=,==,!=)
Common Mistakes
1. Infinite Loop
while (true)
{
}
Avoid unless intentionally creating a continuous process.
2. Forgetting the Semicolon in do...while
Incorrect:
int number = 10;
do
{
Console.WriteLine(number);
}
while (number < 5)
Correct:
int number = 10;
do
{
Console.WriteLine(number);
}
while (number < 5);
3. Wrong Comparison
Incorrect:
while (count = 5)
This is invalid in C# because = is assignment, not comparison.
Correct:
while (count == 5)
4. Modifying the Wrong Variable
int x = 1;
int y = 1;
while (x < 5)
{
y++;
}
Since x never changes, the loop never ends.
Best Practices
- Ensure the loop condition will eventually become false.
- Keep loop conditions simple and readable.
- Use meaningful variable names.
- Avoid deeply nested loops when possible.
- Use
breaksparingly for exceptional exit conditions. - Use
continueonly when it improves readability. - Choose
do...whilewhen the code must execute at least once, such as prompting for user input.
When to Use Each Loop
Use a while loop when:
- The number of iterations is unknown.
- The loop may not need to run.
- The condition should be checked before execution.
Use a do...while loop when:
- The loop must execute at least once.
- Creating menus.
- Validating user input.
- Prompting users until valid data is entered.
Summary
The while and do...while loops are powerful tools for repeating operations in C#. The key difference is when the condition is evaluated:
- A
whileloop checks the condition before each iteration, so the body may never execute if the condition is initially false. - A
do...whileloop checks the condition after the body executes, guaranteeing at least one execution.
Understanding this distinction helps you choose the appropriate loop for tasks such as processing user input, implementing menus, reading data until a condition is met, or repeatedly performing actions until a goal is reached. By combining these loops with statements like break and continue, and by ensuring loop conditions are correctly updated, you can write efficient, readable, and reliable C# programs.