A for loop can also count backwards, as long as we define the right conditions. For example:
for (i in 7 downTo 3) {
println(i)
}
The output of this code is:
7
6
5
4
3
Let's break down this code:
The loop variable
itakes the values of the progression7 downTo 3, so we start iterating from number 7.downToincludes its end value, so we'll end at number 3. We could've written7 downTo 3as7 downTo 3 step 1and it would still be correct.There is no update statement to write:
downTodecreases our number by 1 every time (addstepto skip numbers).
Assignment
Let's print all numbers from 5 through -5 in decreasing order.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
