Kotlin - While Loop


Advertisements

Kotlin while loop executes its body continuously as long as the specified condition is true.

Kotlin while loop is similar to Java while loop.

Syntax

The syntax of the Kotlin while loop is as follows:

while (condition) {
    // body of the loop
}

When Kotlin program reaches the while loop, it checks the given condition, if given condition is true then body of the loop gets executed, otherwise program starts executing code available after the body of the while loop .

Example

Following is an example where the while loop continue executing the body of the loop as long as the counter variable i is greater than 0:

fun main(args: Array<String>) {
   var i = 5;
   while (i > 0) {
      println(i)
      i--
   }
}

When you run the above Kotlin program, it will generate the following output:

5
4
3
2
1

Kotlin do...while Loop

The do..while is similar to the while loop with a difference that the this loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.

Syntax

The syntax of the Kotlin do...while loop is as follows:

do{
    // body of the loop
}while( condition )

When Kotlin program reaches the do...while loop, it directly enters the body of the loop and executes the available code before it checks for the given condition. If it finds given condition is true, then it repeats the execution of the loop body and continue as long as the given condition is true.

Example

Following is an example where the do...while loop continue executing the body of the loop as long as the counter variable i is greater than 0:

fun main(args: Array<String>) {
   var i = 5;
   do{
      println(i)
      i--
   }while(i > 0)
}

When you run the above Kotlin program, it will generate the following output:

5
4
3
2
1

Quiz Time (Interview & Exams Preparation)

Q 1 - Which of the following is a loop statement in Kotlin?

A - for

B - while

C - do...while

D - All of the above

Answer : D

Explanation

All the mentioned statements are loop statements in Kotlin.

Answer : C

Explanation

Statement C is correct about while and do...while loops in Kotlin and in any other modern programming language.

Advertisements