Kotlin Do..While Loop

Kotlin Do..While Loop

Kotlin Do..While loop is kind of a variant to the While loop statement, with a distinction that in Do..While loop, the body of the loop is executed first before evaluating the condition, whereas in While loop, the condition is evaluated first.

Syntax

The syntax of a Do..While loop is

do {
  // body
}
while (condition);

where

  • do is keyword.
  • { denotes the start of the Do..While loop body.
  • } denotes the end of the Do..While loop body.
  • while is the keyword.
  • ( is the syntax to define the start of condition.
  • condition is an expression that evaluates to a boolean value.
  • ) is the syntax to define the end of condition.

Between curly braces, you can write the body of the While loop.

Examples

1. Print “Hello World” five times

In the following program, we use While loop to print “Hello World” five times.

Kotlin Program

fun main(args: Array<String>) {
    var i = 0
    do {
        println("Hello World")
        i++
    } while (i < 5)
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World

2. Print numbers from 1 to n

In the following program, we use While loop to print integers from 1 to n.

Kotlin Program

fun main(args: Array<String>) {
    val n = 10

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

Output

1
2
3
4
5
6
7
8
9
10