0. The Real Goal of This Lesson A while loop is a mechanism that sends execution flow...
A
whileloop is
a mechanism that sends execution flow back upward as long as a condition remains true.
If you do not understand this:
And your program loses control.
This is not about syntax.
It is about controlling repetition safely.
while (condition)
{
// repeated code
}
In plain language:
“As long as the condition is true,
execute this block repeatedly.”
The condition is the gatekeeper.
using System;
class Program
{
static void Main()
{
int number = 0;
while (number < 10)
{
number++;
Console.WriteLine($"Number is {number}");
}
Console.WriteLine("Loop finished.");
Console.ReadKey();
}
}
Run it.
Do not just read it.
Initial state:
number = 0
while (number < 10)
0 < 10 → true
→ Enter loop.
number++; // number becomes 1
Console.WriteLine("Number is 1");
Condition is checked again:
1 < 10 → true
→ Execute again.
This continues.
Execution is not moving forward only.
It is cycling.
When number becomes 9:
9 < 10 → true
Enter loop
number++ → 10 is printed.
Now check again:
10 < 10 → false
The loop stops.
Execution continues below the loop.
Loop finished.
That exact moment defines control.
A while loop always behaves like this:
[Check condition]
↓ true
[Execute block]
↓
[Check condition]
↓ false
[Exit loop]
Important:
The condition is checked before entering the block.
This is called a pre-check loop.
It may execute zero times.
Consider this code:
int number = 0;
while (number < 10)
{
Console.WriteLine(number);
}
What is missing?
There is no state change.
number never increases.
Result:
number = 0
0 < 10 → true
Print 0
Check again → still 0 < 10
Print 0
Repeat forever
This creates an infinite loop.
The CPU keeps executing.
The program never exits.
You prefer structured thinking.
So break a while loop into three required components:
| Component | Purpose |
|---|---|
| Condition | Defines when to continue |
| State variable | Value used inside condition |
| State change | Modifies the variable so condition eventually becomes false |
All three must exist.
Condition
State variable
State change
If one is missing:
This is not optional.
It is structural.
To truly understand:
while lineWatch:
Flow becomes visible.
And once visible, it becomes predictable.
In a TODO or Calculator app:
Requirement:
If input is invalid, ask again.
Structurally:
Input
Validate
If invalid → ask again
Which becomes:
while (inputIsInvalid)
{
AskAgain();
}
This is not just repetition.
It is controlled validation flow.
A
whileloop sends execution flow back upward
as long as its condition remains true,
and it must contain logic that eventually makes that condition false.