← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 5 of 7

Ranges

A range is a shortcut for describing a whole sequence of numbers or letters, like saying 1-to-10 instead of listing every number.

Inclusive Ranges with ..

The .. operator creates a range that includes both its start and end values, commonly used directly inside for loops or in checks.

Example: Inclusive Ranges with ..

markup
fun main() {
    val range = 1..5
    for (n in range) {
        println("Value: $n")
    }
}

Excluding the End with until

until builds a range that excludes its upper bound, which is the idiomatic way to loop exactly n times starting from zero.

Example: Excluding the End with until

markup
fun main() {
    for (i in 0 until 5) {
        println("Index: $i")
    }
}

Counting Down with downTo

downTo creates a descending range, letting a for loop count backward from a higher number to a lower one.

Example: Counting Down with downTo

markup
fun main() {
    for (i in 5 downTo 1) {
        println("Countdown: $i")
    }
    println("Liftoff!")
}

Custom Increments with step

Chaining .step(n) onto a range changes how much the value increases (or decreases) each iteration, letting you skip over values.

Example: Custom Increments with step

markup
fun main() {
    for (i in 0..10 step 2) {
        println("Even step: $i")
    }
}
Common Mistakes
  1. Using .. when the upper bound should be excluded, off-by-one errors are common; until (or ..<) excludes the end value.
  2. Forgetting downTo for counting backward; a plain .. range always goes in increasing order.
  3. Ignoring the step function when a non-1 increment is needed, and instead manually skipping values inside the loop body.
Chapter Summary
  • a..b creates an inclusive range from a to b.
  • a until b (or a..<b) creates a range that excludes the upper bound b.
  • a downTo b creates a descending range from a down to b.
  • .step(n) changes the increment of any range, letting you skip values.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.