Skip to content

Beginner: Kotlin · Kotlin basics · topic 4 of 50 · 25 min

Loops and ranges

Explanation

Loops repeat code. for goes over ranges like 1..5 (both ends included), 1 until 5 or 1..<5 (end excluded), 5 downTo 1, and step 2, and over lists. while repeats while a condition is true, do-while runs at least once, and repeat(n) runs a block n times. break stops a loop; continue skips to the next round.

Why loops?

Many jobs repeat: print a bill line for each item, send a reminder to every student, try an OTP up to three times. A loop runs a block of code again and again, so you write it once. Each run is called an iteration.

Ranges

A range is a sequence of values from a start to an end. Kotlin has several ways to write one:

RangeValuesNotes
1..51, 2, 3, 4, 5Both ends included
1 until 5 or 1..<51, 2, 3, 4End excluded; handy for list positions
5 downTo 15, 4, 3, 2, 1Counting down
1..10 step 31, 4, 7, 10Skip by 3
'a'..'e'a, b, c, d, eRanges of characters work too

for loops

kotlin
fun main() {
    for (i in 1..3) {
        println("Round $i")
    }
    for (i in 10 downTo 0 step 5) {
        print("$i ")           // 10 5 0
    }
    println()

    val cities = listOf("Delhi", "Agra", "Jaipur")
    for (city in cities) {
        println("Tour stop: $city")
    }
    for ((index, city) in cities.withIndex()) {
        println("${index + 1}. $city")
    }
}
withIndex() gives each position together with the item. listOf creates a list (module 3).

Most of the time in real apps you loop over a collection directly (for (city in cities)) rather than over numbers. Use a numeric range only when you really need the numbers, such as a table or a countdown.

while and do-while

while checks its condition before each round; if it is false at the start, the body never runs. do-while checks after, so the body always runs at least once, which suits "ask, then check" situations.

kotlin
fun main() {
    var balance = 1000
    var months = 0
    while (balance > 0) {
        balance -= 300            // monthly EMI
        months++
    }
    println("Paid off in $months months")   // 4

    var attempts = 0
    do {
        attempts++
        println("Attempt $attempts")
    } while (attempts < 2)
}
months++ adds 1 to months. The do-while runs twice.

repeat

kotlin
repeat(3) {
    println("Reminder: pay your electricity bill")
}
repeat(n) is the simplest way to do something exactly n times. Inside, it holds the round number starting at 0.

break and continue

kotlin
fun main() {
    for (n in 1..10) {
        if (n % 2 == 0) continue    // skip even numbers
        if (n > 7) break            // stop the loop
        print("$n ")                // 1 3 5 7
    }
}
continue jumps to the next round; break leaves the loop completely.

With nested loops, break and continue affect only the innermost loop. To leave an outer loop, Kotlin lets you add a label like outer@ and write break@outer. Use this sparingly; often a function with return is clearer.

Think of it like this: A for loop over a list is like a teacher taking attendance: she goes through the register name by name, from the first to the last, and never skips or repeats a name by accident. A while loop is like eating gol gappas: you keep going while you are still hungry, and nobody knows in advance how many rounds that will be.

Common mistakes

  • Using 0..list.size to loop over positions: the last value equals size, which is past the end and crashes. Use 0 until list.size, list.indices, or loop over the items directly.
  • A while loop whose condition never becomes false: an endless loop. Make sure something inside changes the condition.
  • Writing 5..1 to count down: it is an empty range. Use 5 downTo 1.
  • Changing a val counter inside a loop. Counters must be var.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Loops and ranges · 1/6

for | while | do-while | repeat

Loops repeat code so you write it once. Each repeat is an iteration.

Prefer a video by a teacher? Find free videos on “kotlin for loop while ranges until downTo step” on YouTube ↗

In real life: A multiplication table for a school app

A learning app for primary school children shows multiplication tables. One for loop over 1..10 builds each line with a string template. When a child picks a different number, the same loop prints a new table.

kotlin
fun main() {
    val n = 7
    for (i in 1..10) {
        println("$n x $i = ${n * i}")
    }
}
Prints 7 x 1 = 7 up to 7 x 10 = 70.

Practice (0/3 done)

Task 1 · Question

What does this print? for (i in 1..10 step 4) print("$i ")

Task 2 · Question

How many times does the body run? var n = 10 while (n < 5) { n++ }

Task 3 · Practice

Write a program that (1) prints the 13 times table with for, (2) counts down from 10 to 1 with downTo and prints "Lift off!", (3) uses a while loop to find how many years it takes Rs 10,000 at 8% yearly interest to double, and (4) prints only the odd numbers from 1 to 20 using continue.

Quick quiz

Question 1

1.Which range gives 0, 1, 2, 3?

Question 2

2.Which loop always runs its body at least once?

Question 3

3.What does continue do?

Question 4

4.What does 5..1 contain?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which range gives 0, 1, 2, 3?

Answer: 0 until 4

until excludes the end value.

Which loop always runs its body at least once?

Answer: do-while

do-while checks the condition after the body.

What does continue do?

Answer: Skips the rest of this round and starts the next

continue moves to the next iteration.

What does 5..1 contain?

Answer: Nothing: it is an empty range

Use 5 downTo 1 to count down.

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks its condition after the body.

From Loops: for, while, do-while and range-for

Which loop is best to visit every item of an array?Related

Answer: for...of

for...of gives you each item in turn, with no index to manage.

From Loops: repeating work

What is special about loop compared to while?Related

Answer: It can return a value with break value

loop can hand a value out with break, which makes it an expression.

From Control flow: if, loop, while and for

Which loop always runs its body at least once?Related

Answer: do…while

do…while checks the condition after the first run.

From Loops: for, while, do…while, for…of and for…in

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Kotlin basics”. The module exam comes next.
  2. Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.

← Previous: Conditions: if and when