In this tutorial, you shall learn about Do-while loop statement in Kotlin, its syntax, and how to use do-while statement to execute a task repeatedly, with examples.

Kotlin Do-while loop

Kotlin Do-while Loop is the same as while loop, except that the condition is not checked for the first iteration of the loop body. So, it is guaranteed that the iterative block is executed at least once.

In this tutorial, we will learn the syntax of Do-while Loop statement, and its usage with the help of example programs.

Syntax

The syntax of Do-while Loop statement is

</>
Copy
do {
    statements
} while (condition)
  • do, while: Kotlin keywords.
  • condition: a boolean expression, or something that evaluates to a boolean value.
  • statements: one or more Kotlin statements. This can be empty as well, if necessary.
  • () parenthesis enclose the condition, and {} curly braces enclose the while loop body.

Examples

1. Print numbers from 1 to N using Do-while Loop

In this following program, we will use Do-while Loop to print numbers from 1 to n.

Main.kt

</>
Copy
fun main() {
    var n = 4

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

Output

1
2
3
4

Now, let us take a value for n where the condition is always false.

Main.kt

</>
Copy
fun main() {
    var n = 0

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

Output

1

Since we have used do-while loop, the loop body has executed at least once even when the condition is false during first iteration.

Further Reading

Conclusion

In this Kotlin Tutorial, we learned the syntax of do-while loop, and its usage with the help of Kotlin programs.