While and Do-While Loops

While Loops

  • Iterates while the condition is true.

  • To exit the loop, either the condition must become false, or there must be a check inside the loop that forces the exit.

Exit when condition becomes false

int i = 0;
// Loops 'while' i is less than 10. Exists when i is 10 or more.
while (i < 10)
{
    Console.WriteLine(i);
    i++;    // Without incrementing i, the loop will become an infinite loop
}

Exit when a condition is met inside the loop

  • These loops are more riskier.

int i = 0;
// Infinite loop by design. Must have a way to exit in the code within the loop
while (true)
{
    Console.WriteLine(i);
    i++;
    if (i >= 10)
    {
        break;
    }
}

Do-While Loops

  • Condition check is done at the end of the loop, after executing the body

  • Ideal for scenarios where the body needs to be executed at least once

Last updated