Loops are used to execute a block of code multiple times. Kotlin provides several loop types to handle repetitive tasks efficiently.
for LoopThe for loop is used to iterate over ranges, arrays, or collections.
fun main() {
for (i in 1..5) {
println("Count: $i")
}
}
Output:
Count: 1
Count: 2
... up to 5
1..5 with 5 downTo 1 and add step 2 to skip numbers.
while LoopRepeats a block of code while a condition is true.
fun main() {
var x = 1
while (x <= 3) {
println("x is $x")
x++
}
}
Output:
x is 1
x is 2
x is 3
do...while LoopThis loop executes the block at least once before checking the condition.
fun main() {
var y = 1
do {
println("y is $y")
y++
} while (y <= 2)
}
This will print y is 1 and y is 2.
Iterate directly through elements of a list or array.
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
}
Output:
Apple
Banana
Cherry
You can get both element and index using withIndex().
fun main() {
val colors = arrayOf("Red", "Green", "Blue")
for ((index, value) in colors.withIndex()) {
println("Index $index: $value")
}
}
Use break to exit a loop and continue to skip an iteration.
fun main() {
for (i in 1..5) {
if (i == 3) continue
if (i == 5) break
println(i)
}
}
Output: 1, 2, 4 (3 is skipped, loop breaks at 5)
for — iterate over ranges, arrayswhile — repeat while a condition is truedo...while — always runs at least oncebreak / continue — control the loop flowHelp others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!