
Ranges in Kotlin
π Ranges in Kotlin
In Kotlin, a Range represents a sequence of values defined between a start and an end value. Ranges are commonly used for looping or checking if a value falls within a specific range.
β Creating Ranges in Kotlin
You can create ranges using the ..
operator, until
, or downTo
.
π 1. Using ..
Operator (Inclusive)
The
..
operator includes both start and end values.
range = 1..5println(range.toList()) // Output: [1, 2, 3, 4, 5]
π 2. Using until
Operator (Exclusive)
Excludes the end value.
val range = 1 until 5println(range.toList()) // Output: [1, 2, 3, 4]
until
is useful when you donβt want to include the last number.
π 3. Using downTo
Operator
Creates a range in descending order.
val range = 5 downTo 1println(range.toList()) // Output: [5, 4, 3, 2, 1]
π 4. Using step
with Ranges
You can specify steps to skip values.
val range = 1..10 step 2println(range.toList()) // Output: [1, 3, 5, 7, 9]
step
is useful when you need to iterate by a certain increment.
β Using Ranges in Control Structures
π 1. Using in
to Check Membership
You can check if a number exists within a range using in
or !in
.
val number = 8if (number in1..10) { println("$number is within the range.")} { println("$number is out of the range.")}
Output:
8iswithin the range.
π 2. Using Ranges in For Loops
for (i in1..5) { println(i)}
Output:
12345
Descending with Step:
for (i in10 downTo 1 step 2) { println(i)}
Output:
108642
β Character and String Ranges
Kotlin supports character ranges using ..
.
val charRange = 'a'..'e'println(charRange.toList()) // Output: [a, b, c, d, e]
You can also check if a character exists within a range:
val letter = 'c'println(letter in'a'..'z') // Output: true
β Conclusion
Use
..
for inclusive ranges.Use
until
for exclusive ranges.Use
downTo
for reverse ranges.Use
step
to customize increments.Use
in
and!in
for membership checks.Ranges work with numbers, characters, and loops.