Menu
Coddy logo textTech

Ranges In Loops

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 51 of 93.

So far, we've used 1..5 to create ranges that count upward by one. Kotlin offers more flexible ways to define ranges for your loops.

To count backward, use downTo:

for (i in 5 downTo 1) {
    println(i)
}
// Output: 5, 4, 3, 2, 1

To skip numbers, add step to control the increment:

for (i in 0..10 step 2) {
    println(i)
}
// Output: 0, 2, 4, 6, 8, 10

You can combine downTo with step for backward counting with custom intervals:

for (i in 10 downTo 1 step 3) {
    println(i)
}
// Output: 10, 7, 4, 1

If you need to exclude the last value, use until instead of ..:

for (i in 1 until 5) {
    println(i)
}
// Output: 1, 2, 3, 4

The until keyword is especially useful when working with zero-based indices, where you often need to stop before reaching a certain number.

challenge icon

Challenge

Medium

Read two integers from input: start and end.

Print all even numbers from start down to end (inclusive), each on a separate line.

Use downTo with step to create the range. If start is odd, begin from the first even number below it.

For example, if the input is:

10
2

The output should be:

10
8
6
4
2

If the input is:

9
3

The output should be:

8
6
4

If there are no even numbers in the requested range, print No even numbers on one line. Otherwise, print each even number on its own line.

Try it yourself

fun main() {
    // Read input
    val start = readLine()!!.toInt()
    val end = readLine()!!.toInt()
    
    // TODO: Write your code below
    // Use downTo with step to print all even numbers from start down to end
    // If start is odd, begin from the first even number below it
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground