Kotlin Ranges

In Kotlin, ranges define a sequence of values with a start, an end, and an optional step. Ranges are widely used with loops, conditions, and collections to simplify iteration and value checking.

1. Why use Ranges?

Ranges make your code concise, readable, and expressive. Instead of manually checking or looping through numbers, Kotlin lets you define a range using simple syntax.

2. How to use? Examples

// Simple numeric range
for (i in 1..5) {
    print("$i ")
}
// Output: 1 2 3 4 5

// Using 'downTo'
for (i in 5 downTo 1) {
    print("$i ")
}
// Output: 5 4 3 2 1

// Using 'step'
for (i in 1..10 step 2) {
    print("$i ")
}
// Output: 1 3 5 7 9

// Exclusive range using 'until'
for (i in 1 until 5) {
    print("$i ")
}
// Output: 1 2 3 4

3. Types of Ranges

4. When to use and when not?

5. Complex Examples

// Check if a value lies in a range
val score = 87
if (score in 80..100) {
    println("Excellent!")
} else {
    println("Keep trying!")
}

// Character ranges
for (ch in 'a'..'f') {
    print("$ch ")
}
// Output: a b c d e f

// Using ranges in conditions
val age = 25
when (age) {
    in 0..12 -> println("Child")
    in 13..19 -> println("Teenager")
    in 20..60 -> println("Adult")
    else -> println("Senior")
}

// Nested ranges
for (x in 1..3) {
    for (y in 1..2) {
        println("x=$x, y=$y")
    }
}

6. When not to use ranges (Pitfalls)

7. Interview Questions

8. Summary Table

KeywordDescriptionExample
..Inclusive range1..5 → 1,2,3,4,5
untilExclusive range1 until 5 → 1,2,3,4
downToDescending range5 downTo 1 → 5,4,3,2,1
stepChange step value1..10 step 2 → 1,3,5,7,9

9. Example Program

fun main() {
    val numbers = 1..10
    println("Numbers in range: ${numbers.joinToString()}")

    val evenNumbers = (2..10 step 2).toList()
    println("Even numbers: $evenNumbers")

    for (i in 10 downTo 1 step 3) {
        println("Counting down: $i")
    }

    val charRange = 'A'..'E'
    println("Characters: ${charRange.joinToString()}")
}

Output:

Numbers in range: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Even numbers: [2, 4, 6, 8, 10]
Counting down: 10
Counting down: 7
Counting down: 4
Counting down: 1
Characters: A, B, C, D, E