androidengineers.Book a session

Control Flow and Functions

Loops: for, while, do-while

article15 minEasy

Pick the loop from the stopping rule

A for loop processes known elements or a progression. A while loop repeats while a condition holds and may run zero times. A do-while loop evaluates its condition after the body, so the body runs at least once.

fun main() {
    val topics = listOf("Kotlin", "Compose")
    for ((index, topic) in topics.withIndex()) {
        println("${index + 1}. $topic")
    }
    var remaining = 3
    while (remaining > 0) {
        println(remaining)
        remaining--
    }
}

The countdown terminates because every iteration moves remaining toward the stopping boundary. Missing that update creates an infinite loop. Prefer iterating elements directly unless the index is meaningful; doing so avoids index mistakes and works with collections that do not provide cheap random access.

Do not modify a mutable collection structurally while iterating it with an ordinary for; use a supported iterator operation or create a filtered result.

Exercise

Write an input loop that asks for a positive number until valid input arrives, and exits cleanly at end-of-input. Limit invalid attempts to three.

Check: a valid first entry requires one attempt; three invalid entries terminate; end-of-input does not cause an endless loop.

Reference: Loops

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Loops: for, while, do-while | Kotlin Core Programming | Android Engineers