Open In App

Kotlin do-while loop

Last Updated : 24 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Like Java, the do-while loop is a control flow statement that executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, depending on a Boolean condition at the end of the do-while block. It contrasts with the while loop because the while loop executes the block only when the condition becomes true, but the do-while loop executes the code first, and then the expression or test condition is evaluated.

do-while loop working - First of all, the statements within the block are executed, and then the condition is evaluated. If the condition is true, the block of code is executed again. The process of execution of the code block is repeated as long as the expression evaluates to true. If the expression becomes false, the loop terminates and transfers control to the statement next to the do-while loop. It is also known as a post-test loop because it checks the condition after the block is executed.

Syntax

do {
// code to run
}
while(condition)

Flowchart

Kotlin program to find the factorial of a number using a do-while loop 

Kotlin
fun main(args: Array<String>) {
    var number = 6
    var factorial = 1
    do {
        factorial *= number
        number--
    }while(number > 0)
    println("Factorial of 6 is $factorial")
}


Output

Factorial of 6 is 720


  Kotlin program to print a table of 2 using a do-while loop

Kotlin
fun main(args: Array<String>) {
    var num = 2
    var i = 1
    do {
        println("$num * $i = "+ num * i)
        i++
    }while(i <= 10)
}


Output

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Next Article
Article Tags :

Similar Reads