A do-while loop is similar to while loop except that it checks the condition at the end of iteration. A do-while loop will at least run once even if the given condition is false.
Kotlin do-while loop Example
/**
* created by Chaitanya for Beginnersbook.com
*/
package beginnersbook
fun main(args : Array<String>){
var num = 100
do {
println("Loop: $num")
num++
}
while (num<=105)
}
Output:

A do-while loop at least run once
As I mentioned in the beginning of this guide, a do-while loop will at least run once even if the given condition returns false. This happens because the do-while loop checks the condition after execution of the loop body.
/**
* created by Chaitanya for Beginnersbook.com
*/
package beginnersbook
fun main(args : Array<String>){
var num = 100
do {
println("Loop: $num")
num++
}
while (false)
}
Output:

Infinite do while loop in Kotlin
A do while loop that runs infinitely and never stops is called infinite do while loop. Lets look at the few examples of infinite do while loop.
Example 1:
var num = 100
do {
println("Loop: $num")
num++
}
while (true)
Example 2:
var num = 100
do {
println("Loop: $num")
num--
}
while (num<=105)
Example 3:
var num = 105
do {
println("Loop: $num")
num++
}
while (num>=100)
Leave a Reply