Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

while & dowhile

Kotlin has a while loop that operates in the same way as the while loops of C and Python:

var x = 0.0
while (x <= 100.0) {
    val y = sqrt(x)
    println("%5.1f %6.3f".format(x, y))
    x += 2.5
}
double x = 0.0;
while (x <= 100.0) {
    double y = sqrt(x);
    printf("%5.1f %6.3f\n", x, y);
    x += 2.5;
}
x = 0.0
while x <= 100.0:
    y = math.sqrt(x)
    print(f"{x:5.1f} {y:6.3f}")
    x += 2.5
[Run the Kotlin example]

Once again, Kotlin is stricter than C with regard to the test that follows the while keyword. This test must yield a boolean result.

Like C (but unlike Python), Kotlin also has a dowhile loop.

Remember that a while loop will not execute at all if the test associated with the while evaluates to false immediately—whereas a dowhile loop is guaranteed to execute at least once, because the test is done at the end rather than the start.

Task 4.4

  1. Copy Pizza.kt from the task4_2 subdirectory of your repository to the task4_4 subdirectory.

  2. Modify the copy of Pizza.kt, so that it repeatedly prompts for input until a valid option has been supplied by the user.

    Use a while or dowhile loop to achieve this.