In Kotlin, you can use both for
and while
loops to iterate through items. Here is a quick overview of how you can use these loops with examples:
1. Using a for
Loop
A for
loop is used to iterate through a range, array, list, or any iterable.
Iterating through a range:
for (i in 1..5) {
println("Current number is $i")
}
1..5
creates a range from 1 to 5 (inclusive).- You can also use
until
to exclude the end value:
for (i in 1 until 5) {
println("Current number is $i") // 1 to 4
}
- To iterate in reverse, use the
downTo
keyword:
for (i in 5 downTo 1) {
println("Countdown: $i")
}
- To skip steps, use the
step
keyword:
for (i in 1..10 step 2) {
println("Step: $i")
}
Iterating through a list or array:
val items = listOf("Apple", "Banana", "Orange")
for (item in items) {
println(item)
}
Iterating with index:
val items = arrayOf("A", "B", "C")
for ((index, value) in items.withIndex()) {
println("Index: $index, Value: $value")
}
2. Using a while
Loop
A while
loop is used when you want to execute a block of code as long as a condition is true.
Example of a while
loop:
var counter = 1
while (counter <= 5) {
println("Count: $counter")
counter++
}
Example of a do-while
loop:
The do-while
loop ensures the block of code executes at least once.
var counter = 1
do {
println("Count: $counter")
counter++
} while (counter <= 5)
Summary of Differences:
for
Loop: Best for iterating over ranges, collections, and when the number of iterations is known.while
(anddo-while
) Loop: Best for scenarios where the number of iterations depends on a condition.