Kotlin provides multiple syntaxes of while and does while loops.

While loops allow executing code block repeatedly until the condition satisfies, while and do while loop used.

Let’s talk about while loop in Kotlin.

Kotlin while loop examples

while loop is used to execute a repeated code block until a condition satisfies

while (conditional_statement){
    // code block statements
}

conditional_statement is a conditional expression, that always returns a Boolean value. If the value is true, It executes code block statements.

Here is an example

k = 1;
while (k <= 5){
  println(k)
  k=k+1
}

Output prints values from 1 to 5.

While infinite loop:

Also, if the conditional expression is true and there is no way to break the while, It is in an infinite loop.

k = 1;
while (true)
  println(k)
end

Kotlin Do while loop examples

Do while loop is used to execute a repeated code block until a condition is satisfied.

{
    // code block statements
}while (conditional_statement)

First, Code block statements are executed, next check for conditional_statement, which is a conditional expression, that always returns a Boolean value. If the value is true, It continues code block statement execution.

Here is an example

k = 1;
{
  println(k)
  k=k+1
}
while (k <= 5)

Output prints values from 1 to 5.

While infinite loop:

Also, if the conditional expression is true and there is no way to break the while, It is in an infinite loop.

k = 1;
while (true)
  println(k)
end

Kotlin Break and continue in while loop examples

break: used to break the loop from execution

here is a break usage in the while loop in Kotlin

k = 1;
while k<=10{
  println(k)

  if (k == 3){
    break
    }
  k=k+1
}

Without a break, It prints the values from 1 to 10. with a break, It prints 1,2,3 value

continue in while loop example: continue is used to continue the loop execution by skipping the code after the continue block.

k = 1;
while (k<=10){
  k=k+1
 if k % 3 != 0
    continue
 println(k)

}

Output:

3
6
9