Open In App

Kotlin do-while loop

Last Updated : 15 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes true but do-while loop executes the code first and then the expression or test condition is evaluated. do-while loop working – First of the all the statements within the block is executed, and then the condition is evaluated. If the condition is true the block of code is executed again. The process of execution of code block 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 do-while loop. It is also known as post-test loop because it checks the condition after the block is executed. Syntax of the do-while loop-

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

Flowchart:

Kotlin program to find the factorial of a number using 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 table of 2 using 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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads