0. The Real Goal of This Lesson A while loop repeats based on a condition, but what...
A
whileloop repeats based on a condition,
but what actually stops the loop is state change.
The tools that create state change are:
+=-=*=++--Without them, loops do not evolve.
They freeze.
And frozen state inside a loop is dangerous.
int number = 0;
while (number < 5)
{
number = number + 1;
Console.WriteLine(number);
}
This prints:
1
2
3
4
5
Why?
Because the state (number) changes every iteration.
+= Operator (Compound Assignment)
This line:
number = number + 1;
Can be simplified to:
number += 1;
It means:
Take the current value of
number,
add 1,
and store the result back intonumber.
No logic change.
Only structural simplification.
using System;
class Program
{
static void Main()
{
int number = 0;
while (number < 10)
{
number += 2;
Console.WriteLine(number);
}
Console.WriteLine("Finished.");
Console.ReadKey();
}
}
Output:
2
4
6
8
10
The loop progresses because the state moves forward.
+= Also Works With Strings
using System;
class Program
{
static void Main()
{
string text = "ab";
text += "cd";
Console.WriteLine(text); // abcd
Console.ReadKey();
}
}
Strings can accumulate values.
This is still state change.
Different type.
Same principle.
Now the critical part.
using System;
class Program
{
static void Main()
{
int number = 0;
while (number < 10)
{
number *= 2;
Console.WriteLine(number);
}
}
}
What happens?
The console keeps printing:
0
0
0
0
...
The program never stops.
Initial state:
number = 0
Inside the loop:
number *= 2;
0 × 2 = 0
The state does not change.
Condition:
0 < 10 → always true
The loop never reaches a false condition.
This is an infinite loop.
A loop whose condition never becomes false.
The usual causes:
Infinite loops are logic failures.
Not syntax failures.
Change the initial value:
int number = 1;
Now the flow becomes:
1 → 2 → 4 → 8 → 16
When number becomes 16:
16 < 10 → false
The loop exits correctly.
Termination restored.
++ Operator (Increment Operator)
This:
number += 1;
Can be shortened to:
number++;
It means:
Increase
numberby 1.
Same state change.
Cleaner syntax.
number++;
++number;
Inside a loop body:
There is no visible difference.
The difference only matters when used inside expressions.
At this stage, treat them as equivalent for loop progression.
Every loop requires three components:
| Component | Purpose |
|---|---|
| Condition | Decides whether to continue |
| State variable | Value used inside condition |
| State change | Mechanism that eventually makes the condition false |
If one is missing:
Loops are not magic.
They are structured repetition systems.
Before writing any loop, ask:
“When does this loop stop?”
If you cannot answer that clearly,
Do not write the loop yet.
Implement the following using while:
Each one forces you to think about:
+= accumulates++ increments by one