Using Ranges in Loops
Pyyhkäise näyttääksesi valikon
What is a Range?
A range in Kotlin is a sequence of values between a start and an end. Ranges let you work with a continuous set of values, such as numbers or characters. You define a range using the .. operator, like 1..5, which represents the values from 1 to 5, inclusive. Ranges are commonly used in loops to simplify iterating over a series of values.
Main.kt
Using Ranges in For Loops
You can use ranges in for loops to iterate over a sequence of values. In Kotlin, a range is defined using the .. operator for an inclusive range, which includes both the start and end values. To create an exclusive range (excluding the end value), use the until keyword.
- Use
start..endto include both the start and end values in the loop; - Use
start until endto include the start value but exclude the end value; - Ranges can be used with any type that supports ordering, such as numbers and characters.
Example:
package com.example
fun main() {
// Inclusive range: 1 to 5 (includes 5)
for (i in 1..5) {
println("Inclusive: $i")
}
// Exclusive range: 1 until 5 (does NOT include 5)
for (j in 1 until 5) {
println("Exclusive: $j")
}
}
This code prints numbers from 1 to 5 for the inclusive range, and from 1 to 4 for the exclusive range. Using ranges makes your loops concise and easy to read.
Descending Ranges
You can loop backwards in Kotlin using the downTo keyword. This lets you create a range that starts from a higher number and goes down to a lower number, including both endpoints.
Syntax
for (i in 5 downTo 1) {
println(i)
}
This loop prints the numbers from 5 down to 1, one per line.
Key Points
- Use
downToto create a descending range; - Both start and end values are included in the loop;
- You can use
stepwithdownToto change the decrement value.
Example: Looping with Steps
for (i in 10 downTo 2 step 2) {
println(i)
}
This prints 10, 8, 6, 4, and 2, showing how to count backwards by twos.
You learned how to create numeric and character ranges, use them with for loops, and combine them with collection operations for efficient data processing. Practicing these techniques will help you write cleaner and more expressive Kotlin code. Keep experimenting with different range scenarios to build your confidence and mastery.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme