Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 8 / 68

Loops (while statements)

In this lesson you will learn to repeat work with a while statement in Kotlin and how to tell it apart from a for statement. This is for anyone searching for "Kotlin while loop how to use".

A while statement repeats as long as its condition holds. The rule of thumb is to use a for statement when you already know the stopping point and a while statement when you do not.

The sample code initialises var i = 1, repeats while i <= 5, and increases the value by one with i++ inside the loop. You can see the loop exit at the moment the condition becomes false.

A common stumbling block for beginners is forgetting to update the variable the condition depends on. Miss that update and you get an infinite loop. Note too that a variable used this way has to be declared with var.

In real-world development, while statements are common where the number of repetitions is not known in advance - work that repeats until a condition is met.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)