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 fromstarttoend, including both.variable: Holds the current number in each loop step.start..end: Creates a range of numbers fromstarttoend.
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..endwhen you want to excludeend. The range includesendby default. - Trying to modify the loop variable inside the loop (it is read-only).
- Using
inwith a range incorrectly, likefor (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
| Usage | Description | Example |
|---|---|---|
| Inclusive range | Loops from start to end including end | for (i in 1..5) |
| Exclusive end | Loops from start to one less than end | for (i in 1 until 5) |
| Reverse range | Loops backward from start down to end | for (i in 5 downTo 1) |
| Step | Loops with a step size skipping numbers | for (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.