KOTLIN Tutorial



RANGES IN KOTLIN


Ranges in Kotlin

Ranges represent a sequence of values that you can iterate over. They are often used in loops and condition checks.


1. Creating a Range

Use start..end to define a range. It includes both endpoints.

fun main() {
    val range = 1..5
    for (i in range) {
        print("$i ")
    }
}
  

Output: 1 2 3 4 5


2. Using downTo

To count in reverse order, use downTo.

fun main() {
    for (i in 5 downTo 1) {
        print("$i ")
    }
}
  

Output: 5 4 3 2 1

๐Ÿ” Great for countdowns or reverse iteration!

3. Skipping with step

You can skip values by adding step after the range.

fun main() {
    for (i in 1..10 step 2) {
        print("$i ")
    }
}
  

Output: 1 3 5 7 9


4. Checking if Value Exists

Use in or !in to test if a value exists in a range.

fun main() {
    val x = 7
    if (x in 1..10) {
        println("$x is in the range")
    }
}
  
โŒ Try changing x to 15 and see how the condition fails!

5. Character Ranges

Ranges aren't limited to numbers โ€” you can create ranges of characters too.

fun main() {
    for (ch in 'A'..'F') {
        print("$ch ")
    }
}
  

Output: A B C D E F


Summary

  • a..b โ€” from a to b
  • b downTo a โ€” reverse
  • step โ€” skip steps
  • in โ€” check existence
  • Works with numbers and characters
๐Ÿงช Want to explore deeper? Try using ranges inside when expressions!

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review