Learn/Kotlin/5. Loops
Lesson 5 of 8
Sign in

Kotlin, lesson 5

Loops

A loop runs the same block of code many times. Kotlin has two main kinds: for, when you know what you are stepping through, and while, when you keep going until something changes.

for loops and ranges

A for loop walks through a sequence of values. The most common sequence is a range of numbers:

i is a fresh val on every pass, holding the current number. Ranges come in a few shapes:

RangeValues
1..51, 2, 3, 4, 5 (both ends included)
0..<5

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings jar

Press Ctrl Enter or Check to test your code.

0, 1, 2, 3, 4 (end left out)
5 downTo 15, 4, 3, 2, 1
0..10 step 50, 5, 10

If the start is past the end, as in 1..0, the range is simply empty and the loop body never runs. Use downTo when you really want to count backwards.

To do something a fixed number of times when you don't need the counter, there is also repeat(3) { ... }.

while loops

A while loop checks its condition before each pass and stops as soon as the condition is false. Use it when you can't tell in advance how many passes you need:

Make sure something inside the loop moves you toward the end. If the condition never becomes false, the loop runs forever.

There is also do { ... } while (condition), which checks after each pass, so the body always runs at least once.

Leaving early: break and continue

  • break stops the loop right away; the program carries on after the loop.
  • continue skips the rest of this pass and jumps to the next one.

When loops are nested, break and continue affect the innermost one. You can put a label such as outer@ before a loop and write break@outer to leave that one instead.

Loops that build a result

Many loops follow the same pattern: start a var before the loop, update it on every pass, use it after the loop.

for works on lists too, which you'll explore in the Collections lesson.

Further reading

  • Kotlin docs: Conditions and loops
  • Kotlin docs: Ranges and progressions
  • Kotlin docs: Returns and jumps

Read a whole number n and print its times table from 1 to 10, one line each, in the form n x i = result.

Sample input:

Sample output:

You are saving up for something. The first input line is your goal in dollars. The second line lists your deposits, separated by spaces, in the order you made them.

Add deposits one at a time and stop as soon as the total reaches or passes the goal.

  • If the goal is reached, print Goal reached after N deposits.
  • If you run out of deposits first, print Short by X where X is how much is still missing.

A goal of 0 is reached before any deposit, so it prints Goal reached after 0 deposits.

Sample input:

Sample output:

The starter already reads the deposits into a list. deposits[i] is the deposit at position i (counting from 0) and deposits.size is how many there are.

fun main() {
    for (i in 1..5) {
        print("$i ")          // 1 2 3 4 5
    }
    println()
}
fun main() {
    var population = 100
    var years = 0
    while (population < 1000) {
        population *= 2
        years++
    }
    println("$years years")   // 4 years
}
fun main() {
    for (n in 1..20) {
        if (n % 2 == 0) continue    // skip even numbers
        if (n > 9) break            // stop once we pass 9
        print("$n ")                // 1 3 5 7 9
    }
    println()
}
var total = 0
for (price in listOf(3, 8, 5)) {
    total += price
}
println(total)   // 16
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
50
20 15 30 40
Goal reached after 3 deposits