0
0
KotlinHow-ToBeginner · 3 min read

How to Use For In Range in Kotlin: Simple Loop Guide

In Kotlin, use for (item in start..end) to loop through a range of numbers from start to end inclusive. The .. operator creates the range, and the loop runs once for each number in it.
📐

Syntax

The basic syntax for using a for loop with a range in Kotlin is:

  • for (variable in start..end): Loops from start to end, including both.
  • variable: Holds the current number in each loop step.
  • start..end: Creates a range of numbers from start to end.
kotlin
for (i in 1..5) {
    println(i)
}
💻

Example

This example prints numbers from 1 to 5 using a for loop with a range. It shows how the loop variable changes each time.

kotlin
fun main() {
    for (number in 1..5) {
        println("Number: $number")
    }
}
Output
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
⚠️

Common Pitfalls

Common mistakes when using for with ranges include:

  • Using start..end when you want to exclude end. The range includes end by default.
  • Trying to modify the loop variable inside the loop (it is read-only).
  • Using in with a range incorrectly, like for (i in 5..1) which results in no iterations because the range is empty.
kotlin
fun main() {
    // Wrong: empty range, loop won't run
    for (i in 5..1) {
        println(i)
    }

    // Correct: use downTo for reverse range
    for (i in 5 downTo 1) {
        println(i)
    }
}
Output
5 4 3 2 1
📊

Quick Reference

UsageDescriptionExample
Inclusive rangeLoops from start to end including endfor (i in 1..5)
Exclusive endLoops from start to one less than endfor (i in 1 until 5)
Reverse rangeLoops backward from start down to endfor (i in 5 downTo 1)
StepLoops with a step size skipping numbersfor (i in 1..10 step 2)

Key Takeaways

Use for (i in start..end) to loop through numbers including the end value.
The .. operator creates an inclusive range in Kotlin.
Use downTo to loop backwards from a higher to a lower number.
Use until to loop up to but not including the end value.
Loop variables are read-only and cannot be changed inside the loop.