while Loop
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: