Kotlin provides multiple looping constructs to repeat code execution: for, while, and do-while. Understanding when and how to use each loop is essential for writing clean, efficient code.
The for loop is ideal for iterating over a known range, array, list, or collection. It is concise and readable for fixed iterations.
// Iterating over a range
for (i in 1..5) {
println(i)
}
// Iterating over a collection with index
val colors = listOf("Red","Green","Blue")
for ((index, color) in colors.withIndex()) {
println("$index -> $color")
}
// Using step and downTo
for (i in 10 downTo 1 step 2) println(i)
// Nested loop with continue
for (i in 1..3) {
for (j in 1..3) {
if (i == j) continue // Skip diagonal elements
println("i=$i, j=$j")
}
}
The while loop is used when the number of iterations is not known in advance and depends on a runtime condition.
var i = 1
while (i <= 5) {
println(i)
i++
}
// Loop based on user input
var input: String
while (true) {
print("Enter text (type exit to quit): ")
input = readLine() ?: ""
if (input == "exit") break
}
// Accumulate sum until a limit
var sum = 0
var number = 1
while (sum < 20) {
sum += number
println("Added $number, sum=$sum")
number++
}
The do-while loop guarantees the loop executes at least once before checking the condition.
var i = 1
do {
println(i)
i++
} while (i <= 5)
// User input example
var input: String
do {
print("Enter text (type exit to quit): ")
input = readLine() ?: ""
} while (input != "exit")
// Input validation example
var age: Int
do {
print("Enter your age (must be > 0): ")
age = readLine()?.toIntOrNull() ?: 0
} while (age <= 0)
| Loop | Use Case | Key Point |
|---|---|---|
| for | Known iterations, collections, ranges | Concise, readable |
| while | Unknown iterations, runtime conditions | Condition checked before execution |
| do-while | At least one execution required | Condition checked after execution |