while Loop
A while loop keeps doing something for as long as a condition stays true, like refilling a glass until it is full. It checks before each round.
In this page:
Syntax
while (condition)
{
// body
// change something so the condition eventually becomes false
}
while Loop
A while loop checks its condition before every iteration and keeps running as long as it evaluates to true. It's ideal when the number of iterations isn't known ahead of time. If the condition starts false, the body never executes.
Warning:
Forgetting to update the loop variable inside the body creates an infinite loop.
Example: while Loop
using System;
class Program
{
static void Main(string[] args)
{
int n = 20;
int steps = 0;
while (n > 1)
{
n = n % 2 == 0 ? n / 2 : n * 3 + 1;
steps++;
}
Console.WriteLine($"Reached 1 in {steps} steps");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to update the condition variable, causing an infinite loop.
- Writing a condition that is false from the start, so the body never runs.
- Off-by-one errors by using
<=instead of<.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: