Leave a rating/review
Getting the hang of ranges and iterating over items in a for loop is one of those things that’s will help you throughout your programming career in Kotlin.
And that’s why I’ve got three short challenges for you!
In the first challenge, you have to create a range of twenty numbers, and print them out. You must not start from zero or one. I just want you to print out a range of twenty numbers.
The second challenge is similar, but you need to print out every third number. You should use the same range from challenge one.
In the last challenge, you have to create a decreasing Range of 15 numbers, and print out every second number.
That’s it! :] Now pause the video, and try to solve the challenges. Then once you’re done, hit the play button to check the solution!
Challenge 1:
Create a range of 20 numbers, and iterate over it, printing out the numbers.
Challenge 2:
Iterate over the range in Challenge 1 again, but print every third number.
Challenge 3:
Create a decreasing range of 15 numbers, and print every second number.
For the first challenge, create a range of twenty numbers and print each number out:
val range = 11..30
for(number in range) {
print("$number ")
}
Do note that we start from 11 since the last number from the range will be printed out. This helps us avoid the “Off By One” error that is common when working with loops. Starting from 10 prints out 21 numbers instead of 20 numbers as requested by the challenge.
Go ahead and run the project, and you should see the numbers printed out!
For the second challenge, you have to iterate over the same range, but print out every third number. To do so, add a step to the for loop:
val range = 11..30
for(number in range step 3) {
print("$number ")
}
This will make the number move by three positions for every iteration.
Run the project, and you should see every third number printed out!
For the final challenge, create a reverse range of 15 numbers, and print out every second number:
val reverseRange = 30 downTo 16
for(number in reverseRange step 2) {
print("$number ")
}
We go down to 16 instead of 15 for the same reason stated earlier in the first challenge.
Run the project.
The numbers from the previous challenge are joined to this one. To separate them out, add the following print statement after the first loop:
println("...")
Run the project once again and you should see numbers printed out in the decreasing range!.
Now, remember how the default step in decreasing ranges is -1.
Well, when you use step 2, or any other step in the for loop, you’re actually increasing the step, but in this case, its going to be in the negative direction.
This is why you can print out decreasing ranges based on the step value.