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

In Kotlin, Range expressions are defined in rangeTo() function whose operator form looks like '..'. Defining range is very simple in Kotlin.

Here are few examples for ranges,

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

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

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

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)
    }
}




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.