Back
Close

Kotlin Starter Pack

romainbsl
13.3K views

Ranges

Kotlin provide a way to deal with value ranges, so you might be able to simply create and manipulate ranges effortlessly.

Control if a value belong or not to a range of elements.

// {...}
if (i in 1..10) { // equivalent of 1 <= i && i <= 10
println("$i belongs to the range 1..10")
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Iteration over ranges

// {...}
for (i in 1..5) println("square($i) gives ${i * i}")
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Reverse iteration over ranges

// {...}
for (i in 5 downTo 1) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Iterating over ranges ... step by step

// { autofold
fun main(args: Array<String>) {
//}
for (i in 1..10 step 2) print(i)
// { autofold
println()
// }
for (i in 10 downTo 1 step 2) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Range with exclusion

// {...}
for (i in 1 until 5) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants