How to Use While Loop in Kotlin: Syntax and Examples
In Kotlin, a
while loop repeatedly executes a block of code as long as the given condition is true. The syntax is while (condition) { /* code */ }, where the condition is checked before each iteration.Syntax
The while loop in Kotlin runs the code inside its block repeatedly while the condition remains true. It checks the condition before each loop iteration.
- condition: A Boolean expression evaluated before each loop.
- code block: The statements to run repeatedly.
kotlin
while (condition) { // code to execute }
Example
This example counts from 1 to 5 using a while loop. It shows how the loop runs as long as the condition counter <= 5 is true.
kotlin
fun main() {
var counter = 1
while (counter <= 5) {
println("Count: $counter")
counter++
}
}Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Common Pitfalls
Common mistakes with while loops include:
- Forgetting to update the condition variable inside the loop, causing an infinite loop.
- Using a condition that is always false, so the loop never runs.
Always ensure the condition changes inside the loop to eventually become false.
kotlin
fun main() {
var count = 1
// Wrong: no update to count, causes infinite loop
// while (count <= 3) {
// println(count)
// }
// Correct: increment count to avoid infinite loop
while (count <= 3) {
println(count)
count++
}
}Output
1
2
3
Quick Reference
Remember these tips when using while loops in Kotlin:
- Check the condition before each iteration.
- Update variables inside the loop to avoid infinite loops.
- Use
whilewhen the number of iterations is not known beforehand.
Key Takeaways
Use
while loops to repeat code while a condition is true.Always update the condition variable inside the loop to prevent infinite loops.
The condition is checked before each iteration, so the loop may not run if false initially.
Use
while loops when you don't know how many times the loop should run in advance.