← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 4 of 7

while and do-while Loops

while and do-while loops keep repeating an action as long as a condition stays true, like knocking on a door until someone answers.

The while Loop

while repeatedly runs its body as long as the condition remains true, checking the condition before every iteration -- including the very first one.

Example: The while Loop

markup
fun main() {
    var count = 0
    while (count < 5) {
        println("Count is $count")
        count++
    }
}

The do-while Loop

do-while runs its body first and checks the condition afterward, guaranteeing the body executes at least once even if the condition is false from the start.

Example: The do-while Loop

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

Infinite Loops with break

while (true) combined with a break statement inside the body creates a loop whose exit condition is easier to express in the middle of the logic rather than up front.

Note: Always make sure a while (true) loop has a reachable break, or it will run forever.

Example: Infinite Loops with break

markup
fun main() {
    var n = 1
    while (true) {
        println("n is $n")
        n *= 2
        if (n > 20) break
    }
}

Choosing Between while and do-while

Use while when the body might legitimately need to run zero times, and do-while when the body must always run at least once before checking whether to continue.

Example: Choosing Between while and do-while

markup
fun main() {
    val condition = false
    while (condition) {
        println("This never prints")
    }
    do {
        println("This always prints once")
    } while (condition)
}
Common Mistakes
  1. Forgetting to update the loop's condition variable inside the body, causing an infinite loop that never terminates.
  2. Using while when a do-while is actually needed, resulting in a block that should run at least once being skipped entirely when the condition starts false.
  3. Confusing the check order: while checks before running the body, do-while checks after, changing how many times the body might run.
Chapter Summary
  • while checks its condition before each iteration, so the body may run zero times.
  • do-while checks its condition after each iteration, guaranteeing the body runs at least once.
  • Both loops require the condition to eventually become false, usually by updating a variable inside the body.
  • while (true) { ... break ... } is a common pattern for loops whose exit condition is easier to express inside the body.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.