Ranges and for Loops
A range in Kotlin is an object that represents an interval of values, created with .., until, and similar operators. Combined with a for loop, ranges let you write concise iteration.
Syntax
// Creating ranges.
1..10 // 1 to 10 inclusive (closed range)
1 until 10 // 1 to 9 inclusive (open end, excludes 10)
10 downTo 1 // 10 down to 1 (descending)
1..10 step 2 // 1, 3, 5, 7, 9 (with step)
// Basic for loop syntax.
for (variable in rangeOrCollection) {
// body
}
Syntax Reference
| Syntax | Description |
|---|---|
| a..b | A closed range from a to b, inclusive. Also works with characters. |
| a until b | A half-open range from a up to but not including b. Convenient for array index traversal. |
| a downTo b | A descending range from a down to b. |
| range step n | Sets the step size to n. |
| in range | Checks whether a value is contained in the range. |
| !in range | Checks whether a value is not contained in the range. |
| withIndex() | Iterates over a collection with both index and value. |
Sample Code
fun main() {
// Basic range loop.
for (i in 1..5) {
print("$i ") // Prints "1 2 3 4 5 ".
}
println()
// Loop using until to exclude the end value.
val list = listOf("A", "B", "C")
for (i in 0 until list.size) {
print("${list[i]} ") // Prints "A B C ".
}
println()
// Reverse loop using downTo.
for (i in 5 downTo 1) {
print("$i ") // Prints "5 4 3 2 1 ".
}
println()
// Loop with a custom step size.
for (i in 0..10 step 3) {
print("$i ") // Prints "0 3 6 9 ".
}
println()
// Iterating over a collection directly with for.
val fruits = listOf("apple", "orange", "grape")
for (fruit in fruits) {
println(fruit) // Prints each fruit name.
}
// Use withIndex() to get both index and value.
for ((index, value) in fruits.withIndex()) {
println("$index: $value") // Prints "0: apple", etc.
}
// Using the in operator to check if a value is within a range.
val score = 85
if (score in 70..89) {
println("Grade B") // Prints "Grade B".
}
// Ranges also work with characters.
for (ch in 'A'..'E') {
print("$ch ") // Prints "A B C D E ".
}
}
Notes
Kotlin ranges are commonly used for index-based iteration over collections. For iterating over array or list indices, list.indices is more concise than 0 until list.size. You can also control nested loops with labeled break and continue (e.g., break@outer).
Ranges can also be used inside when expressions (see when expression). For iteration using higher-order functions, see Higher-Order Functions.
If you find any errors or copyright issues, please contact us.