Thuta Learning
Kotlin
BasicProgrammingBeginner

Loops (For, While)

KotlinLesson 830 min

What you'll walk away with

  • Choose between for, while and do-while depending on whether you know the number of iterations
  • Build ranges with .., until, downTo and step and predict the values they produce
  • Use break, continue and labelled break to leave or skip loops precisely
  • Avoid the classic loop bugs: the endless while, the off-by-one and the empty descending range

Explain it simply

Explain it simply

Think of washing a pile of dishes. Washing each plate is something you do "for every plate in the pile", which is a for loop. Scrubbing while the water is still hot is something you do "as long as a condition holds", which is a while loop. A loop is how you ask the computer to repeat the same work so you do not have to write it out again and again.

In Kotlin, for works on anything you can walk through, such as a range (1..4), a list or a string. while is the right tool when you do not know in advance how many rounds you need. This lesson covers both, plus do-while, repeat, break and continue.

Problem → Why → Solution

The problem: the loop that never stops and the loop that never starts

Say you are writing a rocket launch countdown. You use while (countdown > 0) and print the number, but forget countdown--. The program prints "Countdown: 3" over and over, burns a full CPU core and floods the terminal. Another day you want to count from 5 down to 1 and write for (i in 5..1). That one gives no error and prints nothing at all.

loop-bugs.kt
fun main() {
    var countdown = 3
    while (countdown > 0) {
        println("Countdown: $countdown")
        // forgot countdown-- : the condition can never become false
    }

    for (i in 5..1) {
        println(i)   // never runs: 5..1 is an empty range
    }
}

Why do these loops misbehave?

A loop stops only when its condition becomes false. In a while, changing whatever the condition reads is your job, and nothing warns you if you forget. A for over a range advances the counter for you, but .. only counts upward. 5..1 is a perfectly valid empty range, so Kotlin does not guess that you meant downward; you have to say so with downTo.

Core concept: how a loop turns

for (x in something) takes each value from something in turn, binds it to x, and runs the body once per value. something can be a range, a list, a set, a string, or anything that can hand out an iterator. The loop variable x is a fresh val on every round, so writing x = x + 1 in the body gives the compile error 'val' cannot be reassigned. If you want a changing value, use your own var.

while (condition) { } tests the condition before running the body, so if it is false from the start the body never runs. do { } while (condition) runs the body first and tests afterwards, so it runs at least once, which suits "try once, then decide whether to try again", such as a retry. repeat(n) { } is for doing something exactly n times when you do not need a counter of your own.

Two keywords steer a loop from the inside. break ends the innermost loop immediately, and continue abandons the rest of the current round and jumps to the next one. With nested loops, break only affects the innermost one; to leave an outer loop, put a label (outer@) in front of it and write break@outer.

Which one should you pick? Use for when there is something to go through item by item, while when the number of rounds depends on a condition you cannot predict, do-while when the first round must always happen, and repeat when you only need a count. When you loop over a list, taking the elements directly with for (item in list) avoids a whole class of off-by-one bugs that index-based loops invite.

Mental model: check, act, check again
  1. Check the condition or get the next item
  2. Run the body once
  3. break leaves, continue skips ahead
  4. Go back to the check until it fails

In a while loop, if nothing in the body changes what the condition reads, the check can never fail.

General pattern

kotlin
for (item in collectionOrRange) {
    // body runs once per item
}

while (condition) {
    // body must change something the condition reads
}

do {
    // body runs at least once
} while (condition)

for runs once per item, while tests before the body, and do-while tests after it. The condition in the parentheses must be a Boolean; an Int does not count as true or false.

Example: one for and one while

This program has two loops. The first is a for that counts from 1 to 4, the second a while that counts down from 3 to 1. In the for, Kotlin manages the counter; in the while, notice that you write countdown-- yourself.

Loops.kt
fun main() {
    for (number in 1..4) {
        println("Number: $number")
    }

    var countdown = 3
    while (countdown > 0) {
        println("Countdown: $countdown")
        countdown--
    }
}

Code breakdown

  1. for over a rangefor (number in 1..4) {

    1..4 is a range holding 1, 2, 3 and 4, with the right end 4 included. number takes a new value on every round and needs no earlier declaration.

  2. String templateprintln("Number: $number")

    $number is replaced by the current value. Because this line is inside the loop it runs four times and prints Number: 1 through Number: 4.

  3. A counter you ownvar countdown = 3

    The while condition reads this variable. It will change, so it must be a var, not a val.

  4. The conditionwhile (countdown > 0) {

    Before each round it tests countdown > 0. That is true for 3, 2 and 1, and false at 0, which ends the loop.

  5. The updatecountdown--

    This lowers countdown by one. Without it the condition would never turn false and the loop would never end. After writing any while, ask yourself what makes its condition change.

You should see
Number: 1
Number: 2
Number: 3
Number: 4
Countdown: 3
Countdown: 2
Countdown: 1
How the while loop turns (countdown = 3)
  1. 3 > 0? Yes, print, then make it 2
  2. 2 > 0? Yes, print, then make it 1
  3. 1 > 0? Yes, print, then make it 0
  4. 0 > 0? No, the loop is over

Condition true

Run the body, then test again

Condition false

Skip the body and continue after the loop

Ranges: .., until, downTo and step

How you write the range decides which values the loop sees. Study the table below. 1 until 4 leaves the right end out, which is why 0 until list.size is the correct shape for list indexes. step takes a positive number only, and it can be combined with downTo.

RangeValues produced
1..41, 2, 3, 4
1 until 41, 2, 3
4 downTo 14, 3, 2, 1
0..10 step 50, 5, 10
10 downTo 1 step 310, 7, 4, 1
10..1Nothing (an empty range)
Ranges.kt
fun main() {
    println((1..4).toList())
    println((1 until 4).toList())
    println((4 downTo 1).toList())
    println((0..10 step 5).toList())
    println((10 downTo 1 step 3).toList())
    println((10..1).toList())
    println((10..1).isEmpty())
}

Converting each range with toList() lets you see the values directly. The output is [1, 2, 3, 4], [1, 2, 3], [4, 3, 2, 1], [0, 5, 10], [10, 7, 4, 1], [] and true. That is why for (i in 10..1) does nothing and raises no error.

break, continue, labels and the other loops

The code below hunts for the first negative number in a two-dimensional grid. withIndex() pairs each item with its index, which you can unpack as (row, cells). break@outer stops the whole loop labelled outer@, not just the innermost one. It also shows do-while, repeat and continue. The { index -> ... } after repeat is a block of code that runs once per round; it is called a lambda, and a later lesson covers it properly.

Control.kt
fun main() {
    val grid = listOf(listOf(1, 2, 3), listOf(4, -1, 6), listOf(7, 8, 9))
    outer@ for ((row, cells) in grid.withIndex()) {
        for ((col, value) in cells.withIndex()) {
            if (value < 0) {
                println("negative at row $row, col $col")
                break@outer
            }
        }
    }
    println("done")

    var attempts = 0
    do {
        attempts++
        println("attempt $attempts")
    } while (attempts < 2)

    repeat(3) { index -> print("tick$index ") }
    println()

    for (n in 1..6) {
        if (n % 2 == 0) continue
        print("$n ")
    }
    println()
}

The output is negative at row 1, col 1, done, attempt 1, attempt 2, tick0 tick1 tick2 and 1 3 5. With a plain break instead of break@outer, only the inner loop would stop and the outer one would carry on to row 2. The do-while always prints "attempt 1" because it tests only after the first round.

In real projects

Where this shows up in real projects

In production code, for is by far the most common loop: reading a file line by line, adding up the price of each item in an order, or generating thumbnails for a set of images. while shows up where nobody knows the number of rounds in advance, for example calling an API again as long as there is a next page, or retrying a resource that is not ready yet.

Two safety rules apply to these loops. First, every retry loop needs a maximum number of attempts, otherwise a dead server keeps the loop spinning forever. Second, do not modify the collection you are iterating over; that can throw a ConcurrentModificationException, so collect the results into a new list instead. Use break and continue where their purpose is obvious, such as "stop once found" or "skip an invalid record", and keep the loop body short enough to read at a glance.

Common mistakes

Common mistakes

1. Not updating the counter inside a while

Forget countdown-- and the loop never ends; only the IDE's Stop button or Ctrl+C in a terminal will end it. Every time you write a while, check that the body really changes a variable the condition reads, or switch to a for over a range.

2. Off-by-one with 0..list.size

A list of size 3 has indexes 0, 1 and 2 only. for (i in 0..items.size) goes up to i = 3, and on the JVM the exception reads "Index 3 out of bounds for length 3" (an ArrayIndexOutOfBoundsException for a listOf list, an IndexOutOfBoundsException for an ArrayList). Use 0 until items.size or items.indices, or better still take the elements directly with for (item in items).

3. Counting down with ..

for (i in 10..1) compiles and does nothing, and because there is no error it is hard to spot. Write 10 downTo 1, and add step for gaps, as in 10 downTo 1 step 3. A negative step throws an IllegalArgumentException at run time ("Step must be positive, was: -3."), so the direction always comes from downTo.

4. Changing a mutable list while looping over it

Writing for (x in m) { if (x == 2) m.remove(x) } throws java.util.ConcurrentModificationException on the JVM. Build a new list without the unwanted elements using filter, or loop over a copy instead.

Best practices

Best practices

  • Prefer for (item in list) over indexes when you only need the elements, and withIndex() when you need both.
  • Use for or repeat when the number of rounds is known, and while only when it depends on a condition.
  • As soon as you write a while, confirm it has a way to stop: a counter, an attempt limit or an end signal.

Mini challenge

Mini challenge: a shelf stock check

A warehouse sensor reported the item counts of six shelves. Use loops to total the counts, stop at a faulty reading (a negative number), and then work out how many days the stock will last.

  • Use one for loop with withIndex() to get the index and the count together
  • For a count of 0, continue; for a negative count, print an error line and break
  • Print each counted shelf as Shelf index: count and keep a running total
  • Use a while loop to find how many days the stock lasts at 6 items per day
  • Print the reorder check days produced by 10 downTo 1 step 4
StockCheck.kt
fun main() {
    val shelves = listOf(4, 0, 7, 3, -1, 9)
    var total = 0

    // TODO: for loop over shelves.withIndex()
    //   negative count -> print the sensor error line, then break
    //   zero count     -> continue
    //   otherwise      -> print the shelf line and add to total

    println("Total counted: $total")

    // TODO: while loop, subtract 6 per day, count the days

    // TODO: for loop with downTo and step printing the reorder check days
}

Expected: The program should print: Shelf 0: 4 Shelf 2: 7 Shelf 3: 3 Sensor error on shelf 4, stopping Total counted: 14 Stock lasts 3 days Reorder check on day 10 Reorder check on day 6 Reorder check on day 2

Show hint

Write for ((index, count) in shelves.withIndex()) and test the negative case first, then zero. For the while, start stock at total and in each round do stock -= 6 and days++. Check by hand that 14 items at 6 per day last 3 days.

Show solution
StockCheck.kt
fun main() {
    val shelves = listOf(4, 0, 7, 3, -1, 9)
    var total = 0

    for ((index, count) in shelves.withIndex()) {
        if (count < 0) {
            println("Sensor error on shelf $index, stopping")
            break
        }
        if (count == 0) continue
        println("Shelf $index: $count")
        total += count
    }
    println("Total counted: $total")

    var stock = total
    var days = 0
    while (stock > 0) {
        stock -= 6
        days++
    }
    println("Stock lasts $days days")

    for (day in 10 downTo 1 step 4) {
        println("Reorder check on day $day")
    }
}

Quick quiz 1 / 3

Which loop prints 321 (using print, with no separator)?

Quick quiz 2 / 3

What does for (i in 0 until 4) { if (i % 2 == 1) continue; print(i) } print?

Quick quiz 3 / 3

With items = listOf(10, 20, 30), what happens when for (i in 0..items.size) println(items[i]) runs?

What to remember

  • for walks through a range, list or string item by item, and its loop variable is a fresh val on each round.
  • while tests before the body, do-while tests after it, and repeat(n) runs n times without a counter of your own.
  • .. includes both ends and until leaves out the right end; use downTo to count down and step for gaps.
  • break stops the innermost loop and continue skips to the next round; use a label and break@label to leave an outer loop.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Loops (For, While) | Thuta Learning