Sometimes we want to count backwards, or count by 2s, or both! Using certain functions alongside or instead of the normal range operator (..
) can enhance the iterative abilities of our for
loops. The functions downTo
, until
and step
give us more control of a range and therefore more control of our loops.
The downTo
function simply creates a reverse order group of values, where the starting boundary is greater than the ending boundary. To accomplish this, replace the range operator (..
) with downTo
:
for (i in 4 downTo 1) { println("i = $i") }
We can see in the output that the first number in i
is 4
and the last is 1
:
i = 4 i = 3 i = 2 i = 1
The until
function creates an ascending range, just like the (..
) operator, but excludes the upper boundary:
for (i in 1 until 4) { println("i = $i") }
The upper boundary, 4
, is not included in the output:
i = 1 i = 2 i = 3
Up until now, each of these functions, including the range operator (..
), have counted up or down by one. The step
function specifies the amount these functions count by:
for (i in 1..8 step 2) { println("i = $i") }
The loop variable i
now increases by 2 for every iteration. The last number output is 7
, since 2 steps up from that is 9
which is outside the defined range, 1..8
:
i = 1 i = 3 i = 5 i = 7
Instructions
Let’s look at how we can change the behavior of ranges in for
loops by implementing a loop that counts backwards.
Create a for
loop that contains:
i
as the loop variable.- an iterator that starts at
10
and ends at1
. - a
println()
statement in the loop body with the string template"i= $i"
.
Below the first loop, implement a for
loop that counts up but stops just before the upper boundary of the range. Make sure it contains:
j
as the loop variable.- the range
1
up to but not including10
as the iterator. - a
println()
statement in the loop body with string template"j = $j"
.
Finally, implement a for loop that iterates over a range in steps greater than 1. Make sure it contains:
k
as the loop variable.- a range
1
through10
as the iterator that counts up by2
. - a
println()
statement in the loop body with string template"k = $k"
.
Run the code and you will see that the new loop does not output the iterator’s upper boundary 10
. Counting up by 2
from 1
does not include 10
.