for (i in 0 until n) {
// code
}
This loop will run from 0 to n-1. The until keyword is exclusive of the end value.
for (i in 0..n) {
// code
}
This loop will run from 0 to n inclusive. The .. operator creates an inclusive range.
for (i in 0 until n) {
// code
}
This loop will run from 0 to n-1.
for (i in 0 until n step 2) {
// code
}
This loop will run from 0 to n-1 with a step of 2.
for (i in n downTo 0) {
// code
}
This loop will run from n down to 0 inclusive.
for (item in collection) {
// code
}
// or equivalently using forEach function
collection.forEach { item ->
// code
}
This loop will iterate over each item in the collection.
for ((index, value) in collection.withIndex()) {
// code
}
This loop will iterate over the collection, providing both the index and the value of each element.
for (char in 'a'..'z') {
// code
}
This loop will iterate over a char sequence or range.
- until is exclusive of the end value.
- .. creates an inclusive range.
- downTo is for downward iterations and is inclusive.
- step is for specifying a step value.
- forEach and the standard for loop are for iterating over collections.