In Kotlin, you can use ranges and step values in for
loops to iterate over a sequence of numbers or characters. Here’s a detailed guide:
1. Ranges in Kotlin
A range is defined using the ..
operator. For example:
for (i in 1..5) {
println(i)
}
- Output:
1 2 3 4 5
- The loop iterates from
1
to5
(both inclusive).
2. Stepping Through a Range
To define the step value, you can use the step
function. For instance:
for (i in 1..10 step 2) {
println(i)
}
- Output:
1 3 5 7 9
- The loop starts from
1
and increments by2
on each iteration.
3. Descending Ranges
If you want to iterate in reverse order, use the downTo
function:
for (i in 10 downTo 1) {
println(i)
}
- Output:
10 9 8 7 6 5 4 3 2 1
You can combine downTo
with step
:
for (i in 10 downTo 1 step 2) {
println(i)
}
- Output:
10 8 6 4 2
4. Iterating Over Characters
Kotlin ranges also work with characters:
for (ch in 'a'..'e') {
println(ch)
}
- Output:
a b c d e
You can also provide a step value:
for (ch in 'a'..'z' step 3) {
println(ch)
}
- Output:
a d g j m p s v y
5. Using until
The until
function creates a range that excludes the upper boundary:
for (i in 1 until 5) {
println(i)
}
- Output:
1 2 3 4
- The loop stops before reaching
5
.
Summary of Functions and Keywords
..
: Creates a range that includes the start and end values.downTo
: Creates a descending range.step
: Sets the step value for the range.until
: Excludes the upper boundary of the range.
These features make Kotlin’s for
loops flexible and expressive.