Kotlin do While Loop

In Kotlin, the do-while loop is a control flow statement that executes a block of code repeatedly while a condition is true, but with a different flow than the regular while loop. In contrast to the while loop, the do-while loop executes the block of code at least once, even if the condition is initially false.

The general syntax of a do-while loop is:

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

The code block is executed first, and then the condition is evaluated. If the condition is true, the block of code is executed again. The loop continues until the condition is false.

Here’s an example of a do-while loop that prints the numbers from 1 to 5:

var i = 1
do {
    println(i)
    i++
} while(i <= 5)

In this example, the code block is executed first, and then the condition is evaluated. The condition is i <= 5, which is true for the first five iterations of the loop. Inside the loop, the value of i is printed, and then incremented by 1 using the i++ statement. After the fifth iteration, the condition i <= 5 is no longer true, and the loop exits.

Like the while loop, it’s important to be careful when using a do-while loop, because if the condition is never false, the loop will continue indefinitely, resulting in an infinite loop.