SDSnipDojo
← All lessons
Lesson 06 / 126 steps3 exercises

Loops & Ranges

for over ranges, plus modifiers like step and downTo.

1. for and ranges

Loops use for (x in collection). The simplest collection is a range — 1..n produces 1, 2, ..., n (inclusive on both ends):

for (i in 1..5) {
    println(i)               // 1 2 3 4 5
}

var total = 0
for (i in 1..10) {
    total += i               // total = 55
}

Use until for an exclusive upper bound:

for (i in 0 until 5) { ... } // 0 1 2 3 4

2. sumTo

Implement sumTo(n) returning 1 + 2 + ... + n. Use a for loop over the range 1..n and a var accumulator.

Starter code

fun sumTo(n: Int): Int {
    var total = 0
    return total
}

3. downTo — counting backwards

downTo flips the direction so the loop counts from a higher number to a lower one:

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

Same for syntax as before — only the range expression changes. Both ends are inclusive, just like ...

If from is already less than to, the range is empty and the loop body never runs:

for (i in 0 downTo 5) {
    println(i)              // (nothing)
}

4. reverseSum with downTo

Implement reverseSum(n) returning n + (n-1) + ... + 1. Same idea as sumTo from the previous step — only this time iterate downwards with for (i in n downTo 1).

If n is 0 or negative, the range is empty and the result is 0.

Starter code

fun reverseSum(n: Int): Int {
    var total = 0
    return total
}

5. step — controlling the stride

step controls how far each iteration jumps:

for (i in 1..10 step 2) {
    println(i)              // 1 3 5 7 9
}

for (i in 0..20 step 5) {
    println(i)              // 0 5 10 15 20
}

step chains with downTo, so you can skip while counting backwards too:

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

The step value must be positive — even when going downTo. Kotlin handles the direction for you.

6. evenSum with step

Implement evenSum(n) returning the sum of even numbers from 2 up to n (inclusive). Use for (i in 2..n step 2).

For n = 10: 2 + 4 + 6 + 8 + 10 = 30.

Starter code

fun evenSum(n: Int): Int {
    var total = 0
    return total
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →