0
0
Kotlinprogramming~5 mins

For loop with step and downTo in Kotlin

Choose your learning style9 modes available
Introduction
A for loop with step and downTo helps you count up or down by a specific amount, making it easy to repeat actions in a controlled way.
When you want to count backwards through numbers, like counting down a timer.
When you want to skip numbers while looping, like checking every second item in a list.
When you want to print numbers in reverse order with a fixed gap.
When you need to perform an action a certain number of times but not one by one.
Syntax
Kotlin
for (i in start downTo end step stepValue) {
    // code to repeat
}
Use downTo to count backwards from start to end.
Use step to skip numbers by the stepValue.
Examples
Counts down from 10 to 1, skipping every other number.
Kotlin
for (i in 10 downTo 1 step 2) {
    println(i)
}
Counts down from 5 to 0 by 1 each time.
Kotlin
for (i in 5 downTo 0) {
    println(i)
}
Counts down from 20 to 10, jumping 3 numbers each time.
Kotlin
for (i in 20 downTo 10 step 3) {
    println(i)
}
Sample Program
This program prints numbers from 10 down to 1, skipping every second number.
Kotlin
fun main() {
    println("Counting down from 10 to 1, stepping by 2:")
    for (i in 10 downTo 1 step 2) {
        println(i)
    }
}
OutputSuccess
Important Notes
If you omit step, the loop counts down by 1 by default.
The downTo keyword always counts backwards, so start should be greater than or equal to end.
Using step with a value less than 1 will cause an error.
Summary
Use downTo to count backwards in a for loop.
Use step to skip numbers while looping.
Together, they let you control how the loop counts down.