Home »
Kotlin
Ranges in Kotlin (rangeTo() function example)
In this article, we will learn about the ranges in Kotlin: This contains example on rangeTo() function, rangeTo() is used to range expressions.
Submitted by Aman Gautam, on November 26, 2017
Kotlin Range Expressions
In Kotlin, Range expressions are defined in rangeTo() function whose operator form looks like '..'. Defining range is very simple in Kotlin.
Examples of Kotlin Range Expressions
Here are few examples for ranges,
Example: Print Numbers in a Range
This loop will iterate number from 1 to 5 in ascending order.
for(i in 1..5)
print(i)
Output
12345
Note: This code is similar to i= 1 to i<= 5
Example: Print Numbers in Reverse Order in a Range
If we want to iterate in reverse order, we can use downTo() function as in example below.
for(i in 5 downTo 1){
print(i)
}
Output
54321
Example: Print Numbers in a Range with Steps
Both above loops were iterating over number by increasing or decreasing by 1, but, if we want to iterate by an arbitrary step i.e. not equals to 1. We can use step() function.
for (x in 1..10 step 2) {
print(x)
}
Output
13579
For reverse order
for (x in 9 downTo 0 step 3) {
print(x)
}
Output
9630
Example: Print Numbers in a Range Excluding Last Statement
And, if we do not want to include the last element from the range, we can use until() function.
for(i in 5 until 10){
print(i)
}
Output
56789
program
/**
* Created by Aman gautam on 26-Nov-17.
*/
fun main(args : Array<String>){
for(i in 1..5) {
print(i)
}
println()
for(i in 5 downTo 1){
print(i)
}
println()
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
println()
for(i in 5 until 10){
print(i)
}
}