for (condition) {
// code block
}This prints numbers 1 through 5 using a range.
for (i in 1..10 step 2) {
println(i) // 1, 3, 5, 7, 9
}
for (i in 5 downTo 1) {
println(i) // 5, 4, 3, 2, 1
}val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
println(fruit)
}A while loop repeats a block of code as long as a condition is true. The condition is checked before each iteration, so if the condition is false at the start, the loop may not run at all.
Here is this general structure of a while loop in a kotlin program.
while (condition) {
// code block
}A do-while loop always runs the code block at least once, because the condition is checked after the block executes.
do {
// code block
} while (condition)break exits a loop. continue skips the current iteration.
for (i in 1..5) {
if (i == 3) continue
if (i == 5) break
println(i)
}This prints: 1, 2, 4
Kotlin allows breaking from nested loops using labels:
outer@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) break@outer
println("i=$i, j=$j")
}
}Ask the AI if you need help understanding or want to dive deeper in any topic