How Kotlin while loop works?

In Kotlin, the while works just like in Java. So, if your background is Java then you already know how it works.

For beginners, the while loop executes a block of code until the given condition is True. As the condition is false, the execution moves out of the while loop to the next line of code outside of the loop (if given).

Structure of while loop in Java

The general way of using the while loop:

A few points how Kotlin while loop works:

  • The condition is the Boolean expression in the while loop. In the above syntax x>10 is the condition.
  • First, the condition is tested and results in True or False.
  • If the condition is True, the code inside the curly braces execute.
  • The condition is tested again after executing the code and if again evaluated as True, the code keeps on executing until the condition is False.
  • Because first the condition is tested so there is a possibility that code inside the curly braces does not execute if condition is false at first call.
  • If you want to execute the code at least once (whether the condition is True or False) then use the do..while loop (as shown in the last section of this tutorial).

An example of Kotlin while loop

The example below displays the numbers from one to ten by using a while loop. For that, we have declared a variable with an initial value of 1. This is used in the while loop and the while loop will keep on executing this until its value is less than or equal to 10:

The output:











You can see, we incremented the value of x by 1 in each iteration and as it reached the value 11, the condition in the while loop became false.

Using the decrement example

The example below decrements the variable’s value by 10 in each iteration. It’s initial value is set as 100 and the loop will keep on displaying the variable value until it reaches less than or equal to 10:

The output:

Kotlin while loop

Kotlin do while loop

The do while loop executes the given block of code at least once as the condition is tested at the end. The general way of using the do..while loop in Kotlin is:

An example of do while loop

The example below shows using a do..while loop. Although, the condition is false upfront, however, do while still executes the code once:

The result:


Execution out of do..while loop