The title speaks for itself. I know how to create a while loop count down from 1000 to 0, that counts down by one:
fun main(args: Array<String>) {
var i = 1000
while (i > 0) {
println(i)
i--
}}
BUT, I need to count down by ten: 1000, 990, 980. I'm struggling to wrap my head around it for whatever reason. Willing to lend me a hand?
(Please provide explanation. I don't just want the answer, as I want to understand! I appreciate you all!)
CodePudding user response:
In the while loop, you just have to change i--
to i -=10
.
But this is little more straight forward using the for
loop.
for(i in 1000 downTo 0 step 10) {
println(i)
}
CodePudding user response:
If the decreasing interval is 10, your code i--
needs to be modified to i -= 10
i--
is equivalent to i = i -1
, subtracting 1 from the original, which does not meet your requirements.
fun main() {
var i = 1000
while (i >= 0) {
println(i)
i -= 10
}
}