Thuta Learning
BasicProgrammingbeginner

Loops (For, While)

Relax. We'll talk through this in plain words — no textbook voice.

A loop is a control structure you use when you want to repeat the same task over and over. In Kotlin, you use a for loop to go through a range or collection, and a while loop to keep running as long as a condition holds true.

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

    var countdown = 3
    while (countdown > 0) {
        println("Countdown: $countdown")
        countdown--
    }
}
You should see
Number: 1 Number: 2 Number: 3 Number: 4 Countdown: 3 Countdown: 2 Countdown: 1

Summary

Whenever you have a task that needs repeating, use a loop. Reach for for with a range or collection, and while for a condition.

Easy traps

  • If you forget to update the counter inside a while loop, the program can end up running forever without finishing.

Practical example — total price

Practical example — total price

kotlin
fun main() {
    val prices = listOf(1000, 2500, 1500)
    var total = 0

    for (price in prices) {
        total += price
    }

    println("Total: $total MMK")
}

You'll know it worked when: Total: 5000 MMK

Loops (For, While) | Thuta Learning