Signup/Sign In

Kotlin do-while Loop

In this tutorial, we will cover the do-while loop in Kotlin. The do-while loop is just like the Kotlin while loop with just one difference, that no matter what condition you provide in the do-while loop, the loop will execute once because the condition is checked after the loop code has been executed.

Kotlin do-while loop:

Here is the basic syntax for the do-while loop:

do {
    // Block of code to be executed
}while (condition)

The working of do-while loop is as follows:

  • For the first time, the statements written in do block is executed without checking the condition.

  • After executing the do block, the condition specified in while is checked.

  • If the condition is true, again do block is executed. Else, execution of the loop ends.

Kotlin do-while Loop Example

Let us take an example to print all the even numbers from 1 to 10:

fun main() {
    var number = 1
    do {
        if(number % 2 == 0)
            println(number)
        number++
    }while (number <= 10)
}


2
4
6
8
10

Try running the above code to print even numbers from 1 to 100, all you have to do is modify the condition for the do-while loop.

Like we mentioned in the introduction, the do-while loop will execute at least once, even if the condition is always false. Let us see this with an example:

fun main() {
    do {
        println("Hello World!!")
    }while (false)
}


Hello World!!

In the above code example, we can see that the output is printed once even if the condition is always false.

Difference between while and do-while loop

There is a slight difference between while loop and do-while loop:

  • while loop is entry controlled loop and do-while loop is exit controlled loop.

  • At minimum, do-while loop will execute atleast one time but while loop may not execute even a single time if the condition is false.

Summary

In this tutorial we covered the Kotlin do-while loop, with code examples and we also saw how it is different from Kotlin while loop. In the next tutorial we will cover the Kotlin for loop.



About the author:
I'm a writer at studytonight.com.