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.
for (i in start downTo end step stepValue) { // code to repeat }
downTo to count backwards from start to end.step to skip numbers by the stepValue.for (i in 10 downTo 1 step 2) { println(i) }
for (i in 5 downTo 0) { println(i) }
for (i in 20 downTo 10 step 3) { println(i) }
fun main() { println("Counting down from 10 to 1, stepping by 2:") for (i in 10 downTo 1 step 2) { println(i) } }
step, the loop counts down by 1 by default.downTo keyword always counts backwards, so start should be greater than or equal to end.step with a value less than 1 will cause an error.downTo to count backwards in a for loop.step to skip numbers while looping.downTo keyword do in a Kotlin for loop?downTodownTo keyword in Kotlin is used to create a range that counts backwards, from a higher number down to a lower number.downTo does.downTo = count backwards [OK]downTo means counting downwards [OK]downTo with counting forwardsdownTo skips numbersdownTo stops the loopdownTo and step syntaxfor (i in start downTo end step stepValue). for (i in 10 downTo 1 step 2) { println(i) } matches this.for (i in 1 downTo 10 step 2) { println(i) } has start < end, resulting in empty range. for (i in 10..1 step 2) { println(i) } uses .. which doesn't support down with step correctly. for (i in 10 downTo 1 by 2) { println(i) } uses by instead of step, which is incorrect.downTo with step, not by [OK]by instead of step.. rangefor (i in 8 downTo 2 step 3) {
print("$i ")
}downTo with ..for (i in 5 downTo 1 step 0) {
println(i)
}downTo is spelled correctly, and using .. would count upwards, not downwards. So options A, C, and D are incorrect.downTo with ..for loop with downTo and step, without using an if statement. Which code snippet correctly does this?for (i in 15 downTo 1 step 2) { println(i) } starts at 15 and steps by 2 down to 1, printing 15, 13, 11, ..., 1. for (i in 15 downTo 1 step 1) { if (i % 2 == 1) println(i) } uses step 1 with an if filter (disallowed). for (i in 15 downTo 1 step 3) { println(i) } steps by 3, skipping some odds. for (i in 14 downTo 1 step 2) { println(i) } starts at 14 (even), printing evens.Pass the test and this pattern moves unknown