What if you could count backwards skipping numbers without messy code or mistakes?
Why For loop with step and downTo in Kotlin? - Purpose & Use Cases
Imagine you want to count backwards from 10 to 1, but only print every second number. Doing this by writing each number manually or using many if checks is tiring and boring.
Manually writing each step or using many conditions makes your code long, hard to read, and easy to make mistakes. Changing the step size means rewriting lots of code.
Kotlin's for loop with step and downTo lets you count backwards or forwards with any step size simply and clearly, making your code neat and easy to change.
for (i in 10 downTo 1) { if ((10 - i) % 2 == 0) { println(i) } }
for (i in 10 downTo 1 step 2) { println(i) }
This lets you easily control counting direction and step size, making loops flexible and your code cleaner.
When creating a countdown timer that skips every other second, you can use downTo with step to print only the needed seconds without extra checks.
Manual counting backwards with conditions is slow and error-prone.
downTo and step simplify loops with clear direction and step control.
Code becomes easier to read, write, and maintain.