Kotlin while and do-while Loops, break and continue

Kotlin course · Control flow · Lesson 17 of 51

A for loop is great when you know how many times to repeat. When you don’t know (keep asking until the password is right, keep reading until the file ends), use a while loop.

while loop

The condition is checked before each repetition. If it’s false at the start, the body never runs:

fun main() {
    var balance = 1000
    var months = 0
    while (balance < 2000) {
        balance += balance / 10   // 10% growth
        months++
    }
    println("Doubled after $months months: ₹$balance")
}

Output:

Doubled after 8 months: ₹2142

do-while loop

The condition is checked after each repetition, so the body always runs at least once:

fun main() {
    var attempts = 0
    do {
        attempts++
        println("Attempt $attempts")
    } while (attempts < 3)
}

Output:

Attempt 1
Attempt 2
Attempt 3

do-while is a natural fit for menus and input checks, where you have to show the prompt at least once:

fun main() {
    var number: Int?
    do {
        print("Enter a positive number: ")
        number = readln().toIntOrNull()
    } while (number == null || number <= 0)
    println("Thanks, you entered $number")
}

Output (the user typed abc, then -5, then 8):

Enter a positive number: abc
Enter a positive number: -5
Enter a positive number: 8
Thanks, you entered 8

while vs do-while vs for

LoopChecks the conditionUse when
forover a range/collectionyou know what to loop over
whilebefore each run (may run 0 times)you repeat until something changes
do-whileafter each run (runs at least once)the body must run once first

break: stop the loop

fun main() {
    val numbers = listOf(4, 9, 15, 22, 7)
    for (n in numbers) {
        if (n > 20) {
            println("Found $n, stopping")
            break
        }
        println("Checked $n")
    }
}

Output:

Checked 4
Checked 9
Checked 15
Found 22, stopping

continue: skip to the next round

fun main() {
    for (i in 1..10) {
        if (i % 3 == 0) continue   // skip multiples of 3
        print("$i ")
    }
    println()
}

Output:

1 2 4 5 7 8 10 

Labeled break for nested loops

A plain break only stops the innermost loop. To stop an outer loop, give it a label (a name followed by @):

fun main() {
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i * j == 4) {
                println("Found i=$i, j=$j")
                break@outer
            }
        }
    }
    println("Done")
}

Output:

Found i=2, j=2
Done

continue@outer works the same way, jumping straight to the next round of the outer loop.

Avoiding infinite loops

A while loop runs forever if its condition never becomes false:

var i = 0
while (i < 5) {
    println(i)
    // forgot i++ – this never ends!
}

Make sure something inside the loop moves the condition towards false. A while (true) loop is fine on purpose, as long as it contains a break.

Common mistakes

  • Forgetting to update the variable: the loop never ends.
  • Using while when for is clearer: for (i in 1..10) is simpler than managing a counter by hand.
  • Expecting break to exit all loops: it only exits the innermost one. Use a label.

Exercise

Find the first number greater than 1 that divides 91 exactly, using a while loop.

fun main() {
    val n = 91
    var d = 2
    while (n % d != 0) {
        d++
    }
    println("Smallest divisor of $n (other than 1): $d")
}

Output:

Smallest divisor of 91 (other than 1): 7

FAQ

What is the difference between while and do-while in Kotlin?

while checks the condition first and may never run. do-while runs once before checking.

How do I break out of nested loops in Kotlin?

Put a label on the outer loop, like outer@ for (...), and use break@outer.

Can I use break inside forEach?

No, break and continue work only in for, while and do-while. In forEach, return@forEach skips to the next item, but nothing stops the whole loop early. Use a regular for loop if you need break.

WhatsApp us📞 Call now