0Pricing
Kotlin Academy · Lesson

while and do-while: When to Use Each

Write while and do-while loops and understand their use cases.

while and do-while: When to Use Each is a free Kotlin Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Two Kinds of While Loops

Kotlin offers both while (pre-test) and do-while (post-test). The difference: do-while always runs the body at least once.

Basic while Loop

A while checks the condition before each iteration. If false initially, the body never runs.

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

Basic do-while Loop

A do-while runs the body, then checks the condition. The body always runs at least once.

fun main() {
    var n = 10
    do {
        println("n = $n")
        n--
    } while (n > 7)
}

Reading Until Sentinel

while loops are ideal when you do not know how many iterations you need — e.g. reading until a sentinel value.

fun main() {
    val data = listOf(3, 7, 0, 9)
    var i = 0
    while (i < data.size && data[i] != 0) {
        println("got ${data[i]}")
        i++
    }
    println("stopped at index $i")
}

Searching a List

Use while for early-exit search where you stop as soon as a condition is met.

fun main() {
    val nums = listOf(2, 4, 7, 8, 10)
    var i = 0
    while (i < nums.size && nums[i] % 2 == 0) i++
    println("first odd at index $i = ${nums[i]}") // 2 = 7
}

do-while for Input Validation

Use do-while when you must perform an action (prompt, read, attempt) before you can test for success.

fun main() {
    val validInputs = listOf("y", "n", "y")
    var idx = 0
    var input: String
    do {
        input = validInputs[idx++]
        println("user typed: $input")
    } while (input != "n" && idx < validInputs.size)
}

Counter with Decrement

while loops cleanly handle counters that decrement to zero.

fun main() {
    var lives = 3
    while (lives > 0) {
        println("Lives left: $lives")
        lives--
    }
    println("Game over")
}

Infinite Loop with Break

Use while (true) with break for event-loop style code where the exit condition is complex.

fun main() {
    val items = listOf(1, 2, 3, -1, 4)
    var i = 0
    while (true) {
        if (i >= items.size || items[i] < 0) break
        println("ok: ${items[i]}")
        i++
    }
}

Comparing while and for

If you know the iteration count up front, prefer for. Use while when iterations depend on runtime state.

fun main() {
    // for: known bounds
    for (i in 1..3) print("$i ")
    println()
    // while: state-driven
    var n = 1
    while (n <= 3) { print("$n "); n++ }
    println()
}

Loop with Two Variables

while loops can track multiple variables, helpful for algorithms like Fibonacci.

fun main() {
    var a = 0
    var b = 1
    while (b < 50) {
        print("$b ")
        val next = a + b
        a = b
        b = next
    }
    println() // 1 1 2 3 5 8 13 21 34
}

do-while Always Runs Once

Even if the condition is false from the start, the body of do-while executes once. Sometimes this is exactly what you want — other times it is a bug.

fun main() {
    var x = 100
    do {
        println("x = $x") // prints once
        x--
    } while (x > 1000) // false immediately
}

Quick Check

Which loop guarantees its body runs at least once regardless of the condition?

Recap

Use while when the iteration count depends on a runtime condition. Use do-while when the body must execute at least once (e.g. validation, retry). Prefer for if iteration count is known.

Frequently asked questions

Is the “while and do-while: When to Use Each” lesson free?

Yes — the full text of “while and do-while: When to Use Each” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “while and do-while: When to Use Each”?

Write while and do-while loops and understand their use cases. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “while and do-while: When to Use Each” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. for Loop Over Ranges and Collections
  2. while and do-while: When to Use Each
  3. forEach, repeat, and forEachIndexed
  4. break, continue, and Labeled Returns
← Back to Kotlin Academy