How to Use downTo in Kotlin for Descending Ranges
In Kotlin,
downTo is used to create a descending range from a higher number down to a lower number. You can use it in loops like for (i in 10 downTo 1) to count backwards easily.Syntax
The downTo function creates a range that goes from a higher value down to a lower value, including both ends.
Syntax parts:
start downTo end: Creates a range fromstartdown toend.- The range includes both
startandend. - Commonly used in
forloops to iterate backwards.
kotlin
val range = 10 downTo 1
Example
This example shows how to use downTo in a for loop to print numbers from 5 down to 1.
kotlin
fun main() {
for (i in 5 downTo 1) {
println(i)
}
}Output
5
4
3
2
1
Common Pitfalls
One common mistake is to expect downTo to work like .. (upwards range) without realizing it counts backwards. Also, using downTo with a start value less than the end value results in an empty range.
Wrong example: 1 downTo 5 produces no values.
Right way: Always ensure the start is greater than or equal to the end.
kotlin
fun main() {
// Wrong: start less than end, no output
for (i in 1 downTo 5) {
println(i) // This will not print anything
}
// Correct: start greater than end
for (i in 5 downTo 1) {
println(i) // Prints 5 to 1
}
}Output
5
4
3
2
1
Quick Reference
| Usage | Description |
|---|---|
| start downTo end | Creates a descending range from start to end, inclusive |
| for (i in x downTo y) | Iterates from x down to y in a loop |
| start downTo end step n | Iterates down with a step size n |
| start downTo end with start < end | Creates an empty range (no iteration) |
Key Takeaways
Use
downTo to create descending ranges from a higher to a lower number.Always ensure the start value is greater than or equal to the end value to get a valid range.
You can use
downTo in for loops to count backwards easily.Adding
step after downTo lets you skip numbers while counting down.If start is less than end,
downTo creates an empty range with no iterations.