C# While Loop
A while loop repeats a block of C# code as long as a condition remains true. It is useful when you do not know the exact number of repetitions before the loop starts: reading input until it is valid, processing items until a queue is empty, or retrying an operation until it succeeds. A good while loop has a clear condition, changes state each pass, and eventually stops.
Overview: How While Loops Work
C# normally executes statements from top to bottom. A while loop changes that flow by checking a Boolean condition before each repetition. If the condition is true, the loop body runs. When the body reaches its closing brace, execution jumps back to the condition and checks it again. If the condition is false, the body is skipped and execution continues after the loop.
The condition must have type bool. C# does not allow truthy or falsy values, so while (count) is invalid when count is an int. You must write the meaning explicitly, such as while (count > 0). This makes loops easier to read and lets the compiler reject vague conditions.
A while loop is a pre-test loop. The condition is evaluated before the first iteration, so the loop body may run zero times. This is different from a do while loop, whose body runs once before checking its condition. Use while when zero repetitions is a valid result, such as processing an empty list.
The most important part of designing a while loop is the changing state. Something inside the loop usually increments a counter, consumes an item, updates a flag, or reads a new value. Without that progress, the condition may never become false and the loop can run forever.
Under the hood, the C# compiler emits Intermediate Language with a conditional branch. The CLR evaluates the condition, jumps into the body when the condition is true, then branches back to the condition after the body. The loop does not create a new thread or store all iterations in memory. It simply runs the same statements repeatedly. Variables declared before the loop keep their values between iterations, while variables declared inside the block are scoped to the block and are recreated logically on each pass.
Syntax
bool condition = true;
while (condition)
{
// statements to repeat
condition = false;
}
| Part | Meaning |
|---|---|
while |
Starts a pre-test loop. |
condition |
A Boolean expression checked before every iteration. |
{ } |
The loop body. These statements repeat while the condition is true. |
| Progress update | A statement that moves the loop toward completion, such as index++ or removing an item from a queue. |
Examples
Counting Down
using System;
class Program
{
static void Main()
{
int seconds = 5;
while (seconds > 0)
{
Console.WriteLine(seconds);
seconds--;
}
Console.WriteLine("Go!");
}
}
Output:
5
4
3
2
1
Go!
The variable seconds starts at 5. Each iteration prints the current value and then decreases it by one. When seconds becomes 0, the condition seconds > 0 is false, so the loop stops before printing zero.
Scanning an Array Until a Match
using System;
class Program
{
static void Main()
{
string[] tasks = { "compile", "test", "package", "deploy" };
string target = "package";
int index = 0;
bool found = false;
while (index < tasks.Length && !found)
{
if (tasks[index] == target)
{
found = true;
}
else
{
index++;
}
}
if (found)
{
Console.WriteLine($"Found {target} at index {index}");
}
else
{
Console.WriteLine("Task not found");
}
}
}
Output:
Found package at index 2
This loop has two stopping conditions: it stops when the index reaches the end of the array or when the target is found. The && operator short-circuits, so tasks[index] is never evaluated after index has reached tasks.Length. That protects the program from an out-of-range access.
Processing a Queue of Work
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Queue<string> jobs = new Queue<string>();
jobs.Enqueue("resize image");
jobs.Enqueue("send email");
jobs.Enqueue("write audit log");
int completed = 0;
while (jobs.Count > 0)
{
string job = jobs.Dequeue();
completed++;
Console.WriteLine($"{completed}: {job}");
}
Console.WriteLine($"Completed {completed} jobs");
}
}
Output:
1: resize image
2: send email
3: write audit log
Completed 3 jobs
A queue naturally fits a while loop because the number of iterations depends on the current contents. Each call to Dequeue removes one item, so the condition jobs.Count > 0 moves toward false. This is often clearer than managing a numeric index yourself.
Using break and continue Carefully
using System;
class Program
{
static void Main()
{
int number = 0;
int total = 0;
while (number < 8)
{
number++;
if (number == 3)
{
continue;
}
if (number == 6)
{
break;
}
total += number;
Console.WriteLine($"Added {number}, total is {total}");
}
Console.WriteLine($"Final total: {total}");
}
}
Output:
Added 1, total is 1
Added 2, total is 3
Added 4, total is 7
Added 5, total is 12
Final total: 12
continue skips the rest of the current iteration and jumps back to the condition. In this example, 3 is not added. break exits the loop completely when number becomes 6. Both statements are useful, but they should be easy to see and understand because they change the normal flow.
How While Works Step by Step
- The compiler checks that the condition inside parentheses has type
bool. - It checks the loop body for valid names, types, assignments, and reachable code.
- At runtime, the condition is evaluated before the first iteration.
- If the condition is false, the body is skipped completely.
- If the condition is true, the body runs from top to bottom unless
break,continue,return, or an exception changes the path. - After the body finishes, execution jumps back to the condition.
- The cycle repeats until the condition is false or the loop is exited another way.
Because the condition is checked repeatedly, avoid putting expensive work in it unless that work is necessary. For example, repeatedly recalculating a value from a database or remote service inside the condition would be a poor design. In ordinary in-memory checks such as index < array.Length or queue.Count > 0, the cost is normally small and the clarity is worth it.
Common Mistakes
Forgetting to Update the Loop Variable
int count = 3;
while (count > 0)
{
Console.WriteLine(count);
}
This compiles, but it never changes count, so the condition stays true forever. Update the state inside the loop.
using System;
class Program
{
static void Main()
{
int count = 3;
while (count > 0)
{
Console.WriteLine(count);
count--;
}
}
}
Output:
3
2
1
Accidentally Adding a Semicolon
int tries = 0;
while (tries < 3);
{
tries++;
Console.WriteLine(tries);
}
The semicolon creates an empty loop body. The block below it is not part of the loop, so tries is never incremented while the condition is being checked. Remove the semicolon and use braces for the real body.
using System;
class Program
{
static void Main()
{
int tries = 0;
while (tries < 3)
{
tries++;
Console.WriteLine(tries);
}
}
}
Output:
1
2
3
Using the Wrong Boundary
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30 };
int index = 0;
while (index < numbers.Length)
{
Console.WriteLine(numbers[index]);
index++;
}
}
}
Output:
10
20
30
Array indexes run from 0 through Length - 1. The correct condition is index < numbers.Length, not index <= numbers.Length. Using <= would eventually try to read one element past the end of the array and throw an IndexOutOfRangeException.
Best Practices
- Use
whilewhen the number of iterations is not known in advance. - Use
forwhen you have a simple counter with a clear start, end, and update. - Make the stopping condition easy to read. Complex loop conditions often deserve named Boolean variables.
- Ensure the loop body makes progress toward stopping: increment, decrement, dequeue, read new input, or update a flag.
- Prefer braces even for a one-line body. They prevent accidental changes when the body grows.
- Keep
breakandcontinueclose to the condition they depend on, and avoid using many of them in one loop. - Be careful with user input and external resources. Add limits, timeouts, or validation so a loop cannot wait forever.
- Do not modify a collection while iterating over it with
foreach; when removal is part of the algorithm, awhileloop over a queue or index can be clearer.
Practice Exercises
- Write a program that starts with
int value = 1and uses awhileloop to print powers of two until the value is greater than64. - Create an array of prices and use a
whileloop to add them until the total reaches or exceeds100m, then print how many prices were used. - Write a retry loop with
int attempts = 0. PrintTrying...while attempts is less than three, then printStopped.
Summary
- A
whileloop repeats while its Boolean condition is true. - The condition is checked before every iteration, so the body can run zero times.
- Most
whileloops depend on changing state such as a counter, index, queue size, or flag. breakexits the loop, whilecontinueskips to the next condition check.- Infinite loops, stray semicolons, and off-by-one boundaries are the most common beginner mistakes.
