← C# from Scratch
Lesson 16 of 39 · 10 XP
The while loop
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
while repeats a block as long as the condition is true:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++; // forget this and the loop never ends
}
do { … } while (condition); checks after the body: the body runs at least once.
Handy for a menu that "asks until the answer is acceptable".
Reading until the end of the input:
string line;
while ((line = Console.ReadLine()) != null)
{
// process line
}
Task. Read a natural number n. Until n becomes 1: if it's even, halve it; otherwise n = 3n + 1
(the Collatz conjecture). Print the number of steps.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.