Kotlin - while and do-while loop example



This post shows how to create while and do while loop using Kotlin programming language.

while Loop -
 While loop executes a block of code repeatedly as long as a given condition is true.
do-while loop - The do-while loop is similar to while loop except that it tests the condition at the end of the loop.

Kotlin - while and do-while loop example

package net.javaguides.kotlin

fun main(args: Array < String > ) {
    // While Loop
    var x = 1
    while (x <= 8) {
        println("$x ")
        x++
    }

    // =======================

    // do-while Loop

    x = 1
    do {
        print("$x ")
        x++
    } while (x <= 8)

    // Since do-while loop tests the condition at the end of the loop. It is executed at least once
    x = 6
    do {
        print("$x ")
        x++
    } while (x <= 8)
}
Output:
1 
2 
3 
4 
5 
6 
7 
8 
1 2 3 4 5 6 7 8 6 7 8 

Comments