In this tutorial, you shall learn about Infinite While loop in Kotlin, and how to write an Infinite While loop in programs, with examples.
Infinite While Loop in Kotlin
An infinite loop is one that runs indefinitely.
In Kotlin, we can implement an infinite while loop by specifying a condition that is always true.
A simple example to implement an infinite while loop is shown in the following.
while (true) {
//statements
}
Examples
1. Print numbers indefinitely
In the following program, we have an infinite while loop to from numbers from 1 to infinity.
Main.kt
fun main() {
var i = 1
while (true){
println(i)
i++
}
}
Output
1
2
3
4
5
6
We have truncated the output, but the execution goes on and on.
2. Infinite While loop with break statement
In the following program, we have an infinite while loop to print from numbers from 1 to infinity. Also, we have a break statement that runs when the value of i
is 5.
Main.kt
fun main() {
var i = 1
while (true){
println(i)
i++
if (i==5) break
}
}
Output
1
2
3
4
Conclusion
In this Kotlin Tutorial, we learned how to write an infinite while loop and how to break it using a break statement.